text:
Q: Trying to use PHPMailer to send mass-emails everyone!
I've to send monthly a lot of a emails with a QRcode png in attachment. Because of that, i'm planning change my script with the 'built-in' mail() function to use PHPMailer class.
The problem is, by using the PHPMailer class, only the first database query receive the email.
If could be useful, i'm attaching my script below:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Envio de chaves PIX por email em massa</title>
<link rel="shortcut icon" href="<?=SITE_IMAGES_PATH?>favicon.ico" />
<link rel="stylesheet" href="../styles.css">

<?php
// page setup
ob_start();
session_start();
require('../constants.php');
require('../functions.php');
require('../db.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require('../mailer/src/Exception.php');
require('../mailer/src/PHPMailer.php');
require('../mailer/src/SMTP.php');

// codificação
header('Content-Type: text/html; charset=UTF-8');
@ini_set('default_charset','UTF-8');

// dados de permissoes
try{
    $sql = "SELECT * FROM " . CONFIG;
    $configdata = $link->prepare($sql);
    $configdata->execute();
    $data = $configdata->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error){
    die($error->getMessage());
}
if(!empty($_COOKIE['user']) && empty($_SESSION['id'])){
    $logindata = unserialize($_COOKIE['user']);
    try{
        $sql1 = "SELECT * FROM " . USERS . " WHERE user = :user AND pass = :pass";
        $sessionmngt = $link->prepare($sql1);
        $sessionmngt->bindValue(':user',$logindata['user']);
        $sessionmngt->bindValue(':pass',$logindata['pass']);
        $sessionmngt->execute();
        $userdata = $sessionmngt->fetch(PDO::FETCH_ASSOC);
    } catch(PDOException $error){
        die($error->getMessage());
    }
    $_SESSION['id']     = $userdata['id'];
    $_SESSION['user']   = $userdata['user'];
    $_SESSION['pass']   = $userdata['pass'];
    $_SESSION['level']  = $userdata['level'];
    $_SESSION['status'] = $userdata['status'];
}
$config = array(0=>'Visitante',1=>'Usuário',2=>'Moderador',3=>'Administrador',4=>'FUCKING GOD',5=>'Ninguém');
$status = array(0=>'Desativado',1=>'Ativo');
(!isset($_SESSION['level'])) ? $_SESSION['level'] = 0 : NULL;

if(isset($_SESSION['level']) ? $_SESSION['level']>=ROOT : NULL)
{
    $sql = "SELECT * FROM " . EMPRESAS;
    $empresas = $link->prepare($sql);
    $empresas->execute();

    if(isset($_GET['lista']) ? $_GET['lista'] == 'enviar' : NULL)
    {
        while($empresa = $empresas->fetch(PDO::FETCH_ASSOC))
        {
            var_dump($empresa);
            try
            {
                /********************************************************
                *
                *   RELACIONAMENTO EMPRESA X MODALIDADE
                *
                ********************************************************/
                $sql = "SELECT id,valor,nome_modalidade FROM " . MODALIDADES . "
                        INNER JOIN " . EMP_MODALIDADES . " ON " . MODALIDADES . ".mid = " . EMP_MODALIDADES . ".mid
                        WHERE eid=:eid";
                $consulta_modalidades = $link->prepare($sql);
                $consulta_modalidades->bindValue(':eid',$empresa['id']);
                $consulta_modalidades->execute();
            }
            catch(PDOException $error)
            {
                die($error->getMessage());
            }

            $chave_pix          ="04729502000109";
            $beneficiario_pix   ="FUNDEPI";
            $cidade_pix         ="PRES PRUDENTE";
            $identificador      ="***";
            $descricao          ="";
            $gerar_qrcode=true;

            while($modalidade = $consulta_modalidades->fetch(PDO::FETCH_ASSOC))
            {
                /**************************************************

                *   INICIO - GERAR QRCode

                ***************************************************/
                $chave_pix="04729502000109";
                $beneficiario_pix="FUNDEPI";
                $cidade_pix="PRES PRUDENTE";
                $identificador="***";
                $descricao="";
                $gerar_qrcode=true;
                $valor_pix=preg_replace("/[^0-9.]/","",$modalidade['valor']);

                if ($gerar_qrcode)
                {
                    include "phpqrcode/qrlib.php";
                    include "funcoes_pix.php";
                    $px[00]="01"; //Payload Format Indicator, Obrigatório, valor fixo: 01
                    // Se o QR Code for para pagamento único (só puder ser utilizado uma vez), descomente a linha a seguir.
                    //$px[01]="12"; //Se o valor 12 estiver presente, significa que o BR Code só pode ser utilizado uma vez.
                    $px[26][00]="BR.GOV.BCB.PIX"; //Indica arranjo específico; "00" (GUI) obrigatório e valor fixo: br.gov.bcb.pix
                    $px[26][01]=$chave_pix;
                    if (!empty($descricao))
                    {
                        $tam_max_descr=99-(4+4+4+14+strlen($chave_pix));
                        if (strlen($descricao) > $tam_max_descr)
                        {
                            $descricao=substr($descricao,0,$tam_max_descr);
                        }
                        $px[26][02]=$descricao;
                    }
                    $px[52]="0000"; //Merchant Category Code "0000" ou MCC ISO18245
                    $px[53]="986"; //Moeda, "986" = BRL: real brasileiro - ISO4217
                    $px[54]=$valor_pix;
                    $px[58]="BR"; //"BR" – Código de país ISO3166-1 alpha 2
                    $px[59]=$beneficiario_pix; //Nome do beneficiário/recebedor. Máximo: 25 caracteres.
                    $px[60]=$cidade_pix; //Nome cidade onde é efetuada a transação. Máximo 15 caracteres.
                    $px[62][05]=$identificador;
                    $px[62][50][00]="BR.GOV.BCB.BRCODE"; //Payment system specific template - GUI
                    $px[62][50][01]="1.0.0"; //Payment system specific template - versão
                    $pix=montaPix($px);
                    $pix.="6304"; //Adiciona o campo do CRC no fim da linha do pix.
                    $pix.=crcChecksum($pix); //Calcula o checksum CRC16 e acrescenta ao final.
                    $linhas=round(strlen($pix)/40)+1;
                    ?>
                    Modalidade: <?=$modalidade['nome_modalidade']?>

                    Valor: R$ <?=$valor_pix?>,00

                    <?php
                    ob_start();
                    QRCode::png($pix, null,'M',5);
                    $imageString = base64_encode(ob_get_contents());
                    ob_end_clean();
                }
                /**************************************************

                *   FIM - GERAR QRCode

                ***************************************************/
                /***********************************************

                    DADOS DO Email

                    ***********************************************/
                $valor_pix      = preg_replace("/[^0-9.]/","",$modalidade['valor']);
                $uid            = md5(uniqid(time()));
                $remetente      = "financeiro@inovaprudente.com.br";
                $nome_remetente = "Departamento Financeiro - Fundação Inova Prudente";
                $headers        = "From: " . $nome_remetente . " <" . $remetente . ">\r\n";
                $headers        .= "Reply-To: " . $remetente . "\r\n";
                $headers        .= "MIME-Version: 1.0\r\n";
                $headers        .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
                $destinatario   = "financeiro@inovaprudente.com.br"; //$empresa['email'];
                $assunto        = "Chave PIX para " . $empresa['nome'];
                $corpo          = "<!DOCTYPE html>

                                    <meta charset=\"utf-8\" />
                                    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
                                    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />" .
                                    "Saudações, " . $empresa['nome'] . "!

                                    Segue os dados do PIX para quitação da mensalidade.

                                    O QRCode correspondente está anexo a este email, mas você também poderá usar a linha digitável para pagamento, caso não tenha um celular por perto ;)

                                    Modalidade: " . $modalidade['nome_modalidade'] . "

                                    Valor: R$ " . $modalidade['valor'] . ",00

                                    Linha digitável: " . $pix . "

                                    Estamos realizando testes com o sistema de cobrança PIX para que em breve possamos migrar nosso sistema de cobrança. Estamos enviando essa mensagem contendo um QRcode (e sua chave correspondente) para que possamos confirmar o seu recebimento. NÃO EFETUE O PAGAMENTO! Agradeceríamos se, em vez disso, nos desse um feedback informando se: 1) o email caiu na sua caixa de SPAM e 2) se o app do seu banco pôde fazer a leitura do código QRcode.

                                    Grato pela vossa atenção.

                                    At.te,

                                    Fernando
                                    ";
                $email = new PHPMailer();
                $email->Encoding = 'base64';
                $email->CharSet = 'UTF-8';
                /*
                $mail->IsSMTP();                            // set mailer to use SMTP
                $mail->Host = 'mail.blah.com';    // specify main mail server
                $mail->SMTPAuth = true;                        // turn on SMTP authentication
                $mail->Username = 'myusername';                // SMTP username
                $mail->Password = 'my***password';            // SMTP password

                $mail->From = 'alerts@remindalert.com';
                $mail->FromName = 'RA Mailer';
                */
                $email->SetFrom($remetente, $nome_remetente);
                $email->Subject = $assunto;
                $email->isHTML(true);
                $email->Body    = $corpo;
                //mail->AltBody = "Mensagem simplificada.";
                $email->AddAddress($destinatario);
                $file_to_attach = '../mailer/tmp/';
                // Exibe a imagem diretamente ao cliente codificada em base64.
                //echo '
';
                $filename = 'Chave PIX.png';
                $email->addStringAttachment(base64_decode($imageString), $filename);

                return $email->Send();

                if(!$mail->Send())
                {
                    echo "Erro no envio do email: " . $mail->ErrorInfo;
                }
                else
                {
                    echo "Deu bom!";
                }
                $email->ClearAllRecipients(); //necessario para a proxima iteracao
            }
        }
    }
    /***********************************************

    *   APENAS LISTA OS DESTINATARIOS

    *************************************************/
    ?>

                Nome
                Chaves PIX
                Email
                Celular

            <?php
            while($empresa = $empresas->fetch(PDO::FETCH_ASSOC))
            {
                $sql = "SELECT * FROM " . EMP_MODALIDADES . " WHERE eid=:eid";
                $modalidades = $link->prepare($sql);
                $modalidades->bindParam(':eid',$empresa['id']);
                $modalidades-> execute();
                ?>

                    <a href="<?="../empresas.php?modo=visualizar&id=" . $empresa['id']?>" title='Clique para ver detalhes'><?=$empresa['nome']?>

                        <?php
                            while($modalidade = $modalidades->fetch(PDO::FETCH_ASSOC))
                            {
                                ?><a target='_blank' onclick="window.open('./qrcode_empresas.php?id=<?=$empresa['id']?>&mid=<?=$modalidade['mid']?>', '_blank','menubar=no,resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no, width=600, height=600')"><img class='imgbutton' src='.<?=SITE_IMAGES_PATH?>qrcode.png' alt='Será gerada uma chave temporária no valor da mensalidade' title='Será gerada uma chave temporária no valor da mensalidade' style='margin-left: 7px; width:25px; '><?php
                            }
                        ?>

                    <?=$empresa['email']?>
                    <?=$empresa['celular']?>

            <?php
            }
            ?>

    <?php
}
else
{
    die(FORBIDDEN_ERROR);
}
?>

A: Take a look at the mailing list example provided with PHPMailer - you could probably improve the efficiency of what you're doing so far. I'd also recommend making your script less monolithic - break it up into small pieces that link together and you should find it easier to work with.
I think your immediate problem is simply this:
return $email->Send();

That will send the first email, then quit! Just delete the return (and maybe add some error handling as per the example) and the loop will be able to continue.


text:
Q: How to get the height of iframe source url https using jquery? I want to assign a height based on iframe body content to iframe on page load using jquery.
My code is:
<iframe id="loginFrame" class="loginFrame" align="middle" style="border:none;float: left;margin-top: -100px; overflow:hidden;" frameborder="0" src="https://www.example.com" width="700px" scrolling="no"></iframe>

How to set a height for a iframe on page load using jquery.
Thanks,

A: You can try getting the iframe height after the iframe loads, see the code below
Jquery:
$("#loginFrame").load(function() {
    $(this).height( $(this).contents().find("body").height());
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot catch custom exception thrown in MSScriptControl's Eval function This is a MVCE of my problem.
I have this method using MSScriptControl to dynamically evaluate some formula.
public void DoCalculate()
{
    try
    {
        var evaluator = new Evaluator();
        IScriptControl ctrl = new ScriptControl();
        ctrl.Language = "JavaScript";
        ctrl.AddObject("Evaluator", evaluator, false);
        var calcFunction = "Number(Evaluator.Divide(4,0))";
        double rs = ctrl.Eval(calcFunction);
    }
    catch (CustomException cex)
    {
        // Handle CustomException.
    }
    catch (Exception ex)
    {
        // Handle general Exception.
    }
}

This is the Evaluator class.
public class Evaluator
{
    public double Divide(int a, int b)
    {
        if (b == 0)
        {
            throw new CustomException("Cannot divide by zero");
        }
        else
        {
            return a / b;
        }
    }

    public void TestThrow()
    {
        throw new CustomException("This is a test");
    }
}

And this is the CustomException class:
using System;

namespace Library
{
    public class CustomException : Exception
    {
        public CustomException()
            : base()
        {
        }

        public CustomException(string message)
            : base(message)
        {
        }
    }
}

I expected that in this case a CustomException will be throw, and the first catch clause will be entered. However, I got an general Exception (I verified the exception type using GetType().Name) with the message "Cannot divide by zero" instead.
I did get the following error in Evaluator class though:

An exception of type 'Library.CustomException' occurred in XXX.dll but was not handled in user code

If I modify my DoCalculate() like this then I can catch a CustomException just fine:
public void DoCalculate()
{
    try
    {
        var evaluator = new Evaluator();
        evaluator.TestThrow();
    }
    catch (CustomException cex)
    {
        // Handle CustomException.
    }
    catch (Exception ex)
    {
        // Handle general Exception.
    }
}

Does that mean it is impossible to define and throw my own exception from inside Eval function?
I'm using .NET 4.6.2 and Interop.MSScriptControl 1.0.0.0

A: This is the summary of the answer given in this link
COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT. So in order to throw proper exception, Let me suggest the following.
var evaluator = new Evaluator();
IScriptControl ctrl = new MSScriptControl.ScriptControl { Language = "VBScript" };
ctrl.AddObject("Evaluator", new Evaluator(), true);
const string calcFunction = "Evaluator.Divide(4,0)";
try {
    double rs = ctrl.Eval(calcFunction);
}
catch (DivideByZeroException ex) {//Actual DivideByZeroException from .Net
    //How can you divide by zero?!?!
}
catch (Exception ex) {
    //STUFF
}

public class Evaluator {

    public double Divide(int a, int b) {
        if (b == 0) {
            throw new MyDivideByZeroException();
        }
        return a / b;
    }
}

public class MyDivideByZeroException : Exception {

    public MyDivideByZeroException() {
        HResult = -2147352558;
    }
}


text:
Q: I can´t see returned image - PhoneGap Where I make mistakes? I would like to see image after save button click. I see only white screen without returned image. I am using Android and Galaxy S device.
$(function(){

    document.addEventListener("deviceready", phonegapLoaded, false);

    function phonegapLoaded(){

    }

    $("#vyfotit").click(function(){

            navigator.camera.getPicture(onSuccess, onError, {quality: 70, destinationType: Camera.DestinationType.FILE_URI});

        });

    function onSuccess(imageURI){

        var image = document.getElementById("image");

        image.src = imageURI;

        image.style.display = block;

        }

    function onError(message){

        navigator.notification.alert("Failed because: " + message);

    }
});

A: Include permissions for accessing the camera in the AndroidManifest.xml

A: Is there an element with the id image? Only reason I could see this not working is that the element doesn't exist in the DOM.


text:
Q: Why does it work in Safari but not in Chrome? This HTML with simple CSS and JS works perfectly in Safari, but in Chrome (both Mac and Win) it does not work at all, does not even scroll... not sure the is JS, or the CSS or both.
I tried to change the script or the CSS but nothing works.
Please help
https://codepen.io/sinetempore/pen/oNwNKZr
Here is my HTML and my CSS:

document.querySelector('.parallax').addEventListener('scroll', function() {
  if ($(this).scrollTop() > 100) {
    $('.p1, .p2').addClass('hide');
  } else {
    $('.p1, .p2').removeClass('hide');
  }
});

document.querySelector('.parallax').addEventListener('scroll', function() {
  if ($(this).scrollTop() > 1200) {
    $('.p3').addClass('hide');
    $('.p2').removeClass('hide');
  } else {
    $('.p3').removeClass('hide');
  }
});

document.querySelector('.parallax').addEventListener('scroll', function() {
  if ($(this).scrollTop() > 1800) {
    $('.p3-text, .p3sottocntr, .p-main.p4-text').addClass('hidefoot');
  } else {
    $('.p3-text, .p3sottocntr, .p-main.p4-text').removeClass('hidefoot');
  }
});

/// Scroll back to top
$("a[href='.parallax']").click(function() {
  $("html, body").animate({
    scrollTop: 0
  }, "slow");
  return false;
});
@charset "utf-8";
* {
  margin: 0;
}

body {
  height: 100vh;
  overflow-x: hidden;
  overflow-y: hidden;
  font-family: MuseoSans_700;
}

a {
  color: black;
  text-decoration: none;
}

/* ---------- LOGO ----------*/

.logo-p1 {
  overflow: hidden;
  border: 0px solid red;
  width: 120px;
  height: 45px;
  background-color: white;
  position: absolute;
  top: calc(50% - 22.5px);
  left: calc(50% - 60px);
  margin: 0;
}

.logo-p2 {
  left: 0;
  overflow: hidden;
  border: 0px solid red;
  width: 100px;
  height: 100px;
  background-color: white;
  position: absolute;
  top: 40px;
  left: 40px;
  margin: 0;
}

.logo-p3 {
  transform: rotate(180deg);
  left: 0;
  overflow: hidden;
  border: 0px solid red;
  width: 100px;
  height: 100px;
  background-color: white;
  position: absolute;
  top: 40px;
  left: 40px;
  margin: 0;
}

/* ---------- PARALLAX ----------*/

.parallax {
  perspective: 1px;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
  position: static;
  background: rgba(255, 0, 0, 0);
  z-index: 2;
}

.speed-1 {
  transform: translateZ(-6px) scale(7);
}

/* ---------- SECTIONS ----------*/

.p1 {
  height: 100%;
  width: 100%;
  position: absolute;
  display: block;
  z-index: 3;
  background: white;
  opacity: 1;
  transition: all 0.9s ease;
}

.p1.hide {
  opacity: 0;
  transition: all 0.9s ease;
  visibility: hidden;
}

.p2 {
  height: auto;
  width: 100%;
  position: fixed;
  display: block;
  z-index: 2;
  top: 0vh;
  background: white;
  visibility: hidden;
  transition: all 0.4s ease;
  opacity: 0;
}

.p2.hide {
  opacity: 1;
  transition: all 0.9s ease;
  visibility: visible;
}

.p3 {
  height: auto;
  width: 100%;
  position: fixed;
  display: block;
  z-index: 2;
  top: 0vh;
  background: white;
  visibility: hidden;
  transition: all 0.4s ease;
  opacity: 0;
}

.p3.hide {
  opacity: 1;
  transition: all 0.9s ease;
  visibility: visible;
}

.p-main.p4-text.hidefoot {
  width: 100%;
  height: 250px;
  background-color: black;
  /* position: relative; */
  left: 0px;
  margin: auto;
  bottom: 250px;
}

.p-main.p4-text {
  width: 100%;
  height: 0px;
  background-color: black;
  position: fixed;
  left: 0px;
  margin: auto;
  bottom: 0px;
  clip-path: polygon(0 40%, 100% 0, 100% 100%, 0% 100%);
  -webkit-clip-path: polygon(0 40%, 100% 0, 100% 100%, 0% 100%);
  transition: all 0.9s;
  transform: translateY(250px);
  transform-origin: bottom;
}

.p4 {
  height: auto;
  width: 100%;
  position: relative;
  display: block;
  z-index: -1;
}

.p4.hidefoot {
  opacity: 1;
  transition: all 0.9s ease;
  visibility: visible;
}

/* ---------- TESTO SECTIONS ----------*/

.p-main {
  width: 355px;
  height: 230px;
  background-color: transparent;
  position: fixed;
  bottom: 40px;
  left: 40px;
  margin: 0;
  display: flex;
  justify-content: left;
  align-items: flex-end;
  border: 0px solid red;
  filter: invert(0);
  font-family: MuseoSans-100;
  font-size: 13px;
  font-smoothing: antialiased;
}

.p3-text {
  opacity: 1;
  transition: all 0.9s ease;
  visibility: visible;
}

.p3-text.hidefoot {
  opacity: 0;
  transition: all 0.9s ease;
  visibility: hidden;
}

.p-desc {
  line-height: 16px;
}

.p-desc b {
  font-family: MuseoSans_700;
  font-weight: normal;
}

.p-col {
  margin-top: 20px;
  column-count: 2;
  line-height: 16px;
  font-family: MuseoSans_700;
}

/* ---------- MENU SOTTO ----------*/

.sottocentro {
  width: 250px;
  height: 140px;
  background-color: transparent;
  position: fixed;
  bottom: 40px;
  right: calc(0% - 0px);
  margin: 0;
  display: -webkit-box;
  justify-content: center;
  align-items: flex-end;
  filter: invert(0);
  font-family: MuseoSans-100;
  font-size: 13px;
  font-smoothing: antialiased;
  border: 0px solid red;
  right: 40px;
}

.p3sottocntr {
  opacity: 1;
  transition: all 0.9s ease;
  visibility: visible;
}

.p3sottocntr.hidefoot {
  opacity: 0;
  transition: all 0.9s ease;
  visibility: hidden;
}

.sottocentro ul {
  list-style: none;
  text-align: right;
  width: auto;
  border: 0px solid red;
  line-height: 16px;
  text-decoration: none;
  clear: both;
  margin: 0;
  padding: 0px;
  right: 40px;
  position: absolute;
  right: 0px;
  position: absolute;
  bottom: 0px;
}

.sottocentro ul li {
  border: none;
  text-align: right;
  width: auto;
}

.sottocentro ul li.begins {
  border: none;
  text-align: right;
  width: auto;
  padding: 30px 0 0 0;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" media="all" href="css/style.css" />

 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
          aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum..

 Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem
          quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam
          eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit
          qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?


text:
Q: How to test the function of a component present inside prop of other component? I have used List component of material-ui. Inside this component I have a prop subheader which contains a checkbox. I want to test the onClick function for checkbox.
            <List
                component="nav"
                subheader={<span style={{ display: 'inline-flex', width: '100%' }}>
                    < ListSubheader style={{ top: 'inherit', width: '80%', fontSize: '30px', fontWeight: 'bold' }}>
                        {HEADING.industries}
                    </ListSubheader >
                    <Checkbox
                        color="default"
                        checked={this.state.checkedSelectAll}
                        onClick={handleSelectAll}
                    />
                    <Typography className="selectAllText">
                        Select All
                    </Typography>
                </span>}
            >

I wrote :
it('should call handleSelectAll', () => {

    wrapper = shallow(<IndustryGroupModal {...props} />);

    wrapper.find(Checkbox).simulate('click');

});

It is giving this error:
Method "simulate" is meant to be run on 1 node. 0 found instead.

A: Try this, I think it should be enough:
it('should call handleSelectAll', () => {

    wrapper = shallow(<IndustryGroupModal {...props} />);

    wrapper.prop("subheader").props.children[1].props.onClick()

});

I hope this solves your problem, Have a good day!


text:
Q: Possible to bind HTML5 audio currentTime to input range value in Angular2? I'm trying to make a scrub bar for an audio player. I have a HTML 5 audio player created with var audioPlayer = new Audio(). I'd like to bind a HTML <input type="range"> so that 1) the range reflects the audio position but also when I click the range, it changes the audio position to the new position. I am doing like this:
<input type="range" min="0" max="{{ audioPlayer.duration }}" [value]="audioPlayer.currentTime" (input)="audioPlayer.currentTime = $event.target.value">

I am able to change the currentTime by clicking the range slider, but the range slider doesn't move when currentTime changes so it doesn't reflect the current audio position.
What am I doing wrong here? Why doesn't the value bind properly?

A: In addition to the missing ngModel-binding, I had another problem there as well. Property currentTime of Audio-object seems to be a getter/setter so a direct binding doesn't seem to work.
I solved this by binding the range input to a local number variable playbackPosition instead and then added an ontimeupdate-callback to the audio player object that copies the currentTime value to the playbackPosition variable:
  this.audioPlayer = new Audio();
  this.audioPlayer.ontimeupdate = () => {
    this.playbackPosition = this.audioPlayer.currentTime;
    console.log("timeupdate")
  }

A: Use ngModel for two-way binding:
<input
  type="range"
  min="0"
  max="{{max}}"
  [(ngModel)]="currentTime"/>

Here is a working Stackblitz: https://stackblitz.com/edit/two-way-range-input


text:
Q: LNK2005: already defined error I am working on a school assignment, and I get this strange error (I am quite new to C++).
I should find the first value between 1500 and 1900. When I build it the first time, everything is ok, but when I build it the next time, I get this error:
error LNK2005: "bool __cdecl greaterThan1500SmallerThan1900(int)" (?greaterThan1500SmallerThan1900@@YA_NH@Z) already defined in Lab5.obj

If I then change the code slightly (change the type in the predicate function to double) it builds again one time.
template<typename T>
T MyStlClass<T>::myFindIf(list<T> &theList) {

    list<T>::iterator it = find_if(theList.begin(), theList.end(), greaterThan1500SmallerThan1900);
    return *it;
}

bool greaterThan1500SmallerThan1900(int value){
    return (value >= 1500 && value <= 1900);
}

I have read on this site that it is because that I include the ".cpp" file, but on the other hand, I have also read, that I need to include the ".cpp" file, when I am using templates.

A:
I have also read, that I need to include the ".cpp" file, when I am using templates.

Throw away/downvote/identify for us the resource that told you to do that.
There is a good reason that it did so, but the recommendation was wrong and it has led you directly to this issue.
Never #include a .cpp.
The file you put template definitions in should be called something like .ipp rather than .cpp, so that then your IDE does not confuse it with a "regular" source file and build it with the rest of your project. Such a file is then, like a .h, only #included.

A: Your greaterThan1500SmallerThan1900 is not a template, that's why it's wrong to #include its body multiple times (and that's why it must be linked exactly once).
You have to split out this function from the templated stuff. This function should be in a cpp file never #included by anything, but added to your project. (It seems that you already have its declaration where it's called -- it should remain so).
As of the templates, you may heed another answer's advice (renaming to *.ipp which you will #include, removing from project), but the error will disappear before you do (compiling additional template-only source file to an empty object is useless, but it does not hurt).

A: If you are writing an header-only library/module, then use #pragma once to avoid multiple inclusions, and mark the greaterThan1500SmallerThan1900 function inline:
// MyStlClass.hpp

#prgma once

....

template<typename T>
T MyStlClass<T>::myFindIf(list<T> &theList) {

    list<T>::iterator it = find_if(theList.begin(), theList.end(), greaterThan1500SmallerThan1900);
    return *it;
}

// NOTE inline here:
inline bool greaterThan1500SmallerThan1900(int value){
    return (value >= 1500 && value <= 1900);
}


text:
Q: Nodejs recommended clean folder structure I'm planning a medium-sized node project because I have a java background, grade did everything for me regarding the general structure of the project. And as far as i already know, the MVC pattern is not very common in Node projects.
Now i am wondering how i can structure my project.
I already have some files:
Server-related:
-server.js just the app.listen(port, callback) function
-app.js in here are all expressjs settings like app.use(xyz)
client-related:
my public files index.html, index.css and some client side javascript
And some business logic:
my project does some heavy calculations on the server side and just displays the results in the index.html, so my business logic contains the most files.
For example: a PriorityQueue.js File, that is just a library class for a PriorityQueue Implementation.
Furthermore I have implemented some other Data structures and Algorithms.
I do not have many routes, just /error and /home
My Questions is now: How do i structure all these files, to have a clean and beautiful project structure?
I already read the AirBnB and the Google JS Style Guide, but they don't say anything about the project structure.
Your help is much appreciated! Thanks.

A: I generally create a server.js main file and  routes/, controllers/ and services/ and models/ subdirectories. If I have a "files" service I will then create files.route.js, files.controller.js, files.service.js and files.model.js.


text:
Q: Gstreamer Is there any video codec that supports alpha channel I have a raw video data with alpha channel. I want to stream this video data but as you know, raw data streaming is a burden over network.
I couldn't find any video encoder that supports alpha channel.
I tried openh264enc and vp8enc encoders but alpha is lost while encoding.
Is there any video codec that is on Gstreamer that supports alpha channel ?


text:
Q: Using Terraform to dump/restore a MariaDB database No cloud resources are in use here.
I am new to using Terraform.
I am using Terraform 0.12 to install software on a server.  That software expects the remote MariaDB database to be empty, which is done manually. (The software will cause Terraform to abort if the database is not empty.)  Right now it is all dummy data.
I would like use Terraform to mysqldump the database prior to destroying the database so that same dump can be restored on a terraform apply.  Eventually, the contents of the database need to be preserved between software upgrades.
I have Terraform code to create and destroy the server and install the software.  That works fine. The database is handled manually at the moment.  When uncommented, the Terraform code to connect to the database works, but I do not have enough experience to do anything more beyond that.
provider "mysql" {
    endpoint = "10.0.1.2"
    username = "terraform"
    password = "changeme"
    version  = "~> 1.6"
}

resource "mysql_database" "default" {
    default_character_set = "utf8"
    name = "terraform_test_db"
}

A: You can use destroy time provisioners to trigger an provisioner action to happen before Terraform tries to destroy the resource.
provider "mysql" {
  endpoint = "10.0.1.2"
  username = "terraform"
  password = "changeme"
  version  = "~> 1.6"
}

resource "mysql_database" "default" {
  name = "terraform_test_db"

  default_character_set = "utf8"

  provisioner "local-exec" {
    when    = "destroy"
    command = "mysqldump [options] > dump.sql"
  }
}


text:
Q: How should I annotate a function returning a ctypes array in Python? Consider the following Python code:
def foo(aqs : typing.List[int]) -> ??? :
    array_type = ctypes.c_int64 * len(aqs)
    ans = array_type(*aqs)
    return ans

What's the correct annotation for the return value of this function? (In place of ???)

A: This function doesn't have a consistent return type, since the length of the returned array is part of the array's type. However, the type is always a subclass of ctypes.Array, which is the most specific annotation you can use:
def foo(aqs: List[int]) -> ctypes.Array:
    ...

A: I'm new to Python, but it seems that typing.List[T] is what you're looking for (like @JörgBeyer said in its comment, above).
Example of a function that returns a List of instances of class RegistrationRequest :
import string
import typing
from datetime import datetime

from dataclasses import dataclass

@dataclass()
class RegistrationRequest:
    activity: string
    start_at: datetime

def registrations_requests() -> typing.List[RegistrationRequest]:
    return [
        RegistrationRequest('Zumba', datetime(2019, 6, 25, 12, 30, 0, 0)),
        RegistrationRequest('Zumba', datetime(2019, 6, 27, 19, 15, 0, 0)),
    ]

print('{0}'.format(registrations_requests()))

Output is:
[RegistrationRequest(activity='Zumba', start_at=datetime.datetime(2019, 6, 25, 12, 30)), RegistrationRequest(activity='Zumba', start_at=datetime.datetime(2019, 6, 27, 19, 15))]

A: Use python's built in List type List[T]
def foo(aqs : typing.List[int]) -> List[T]:
array_type = ctypes.c_int64 * len(aqs)
ans = array_type(*aqs)
return ans

Replace T with the list type


text:
Q: How to return a data from list or any db object, group by days,weeks or months Hiii!
I have a database model which has information like "receivedMsg","receivedTime","SentBy"
Now I wanna sort these informations in arrays..
If the message is under 24 hours old, then it should be in today array, if the is more than 24 hours old, then it should be in week array.
Everything older than a week should be  in Earlier array.
The output should be displayed in the following format
Today[
   {receivedMsg : "hii",
   sentBY : "xyz"},

   {receivedMsg : "hii2",
   sentBY : "xyz"},

],
This Week[
   {receivedMsg : "hii3",
   sentBY : "xyz"},

   {receivedMsg : "hii4",
   sentBY : "xyz"},

],
Earlier[
   {receivedMsg : "hii5",
   sentBY : "xyz"},

   {receivedMsg : "hii6",
   sentBY : "xyz"},

]

Pls note that im using linq with C#

A: I hope, I understood you:
    public class RearrangeMessagesInArray
    {
        public void RearrangeMessagesInArrays(Message[] today, Message[] week, Message[] earlier)
        {
            // To work with linQ, convert array to list.
            var earlierAsList = earlier.ToList();
            // Add all messages to "earlier" - array, when its older then 7 days
            earlierAsList.ToList().AddRange(GetAllMessagesForGivenArrayAndTime(today, Times.Earlier));
            earlierAsList.ToList().AddRange(GetAllMessagesForGivenArrayAndTime(week, Times.Earlier));
            //return to "earlier" - array.
            earlier = earlierAsList.ToArray();

            // Add all messages to "week"-array, which is older than one day and newer than 7 days and remove all which is over 7 days
            week = GetAllMessagesForGivenArrayAndTime(week, Times.Week).ToArray();

            // Reassign "today"-array without messages, which are older than 1 one day.
            today = GetAllMessagesForGivenArrayAndTime(today, Times.Day).ToArray();

            PrintOutArrayAsJson(today, week, earlier);
        }

        private void PrintOutArrayAsJson(Message[] today, Message[] week, Message[] earlier)
        {
            today.ToList().ForEach(message => Console.WriteLine(WriteFromObject(message)));
            week.ToList().ForEach(message => Console.WriteLine(WriteFromObject(message)));
            earlier.ToList().ForEach(message => Console.WriteLine(WriteFromObject(message)));
        }

        private IEnumerable<Message> GetAllMessagesForGivenArrayAndTime(Message[] messages, Times time )
        {
            switch (time)
            {
                case Times.Day:
                    return from message in messages
                        where GetDaysDiffBetweenNowAndGivenDate(message.ReceivedTime) <= 1
                        select message;

                case Times.Week:
                    return from message in messages
                        where GetDaysDiffBetweenNowAndGivenDate(message.ReceivedTime) <= 7
                              && GetDaysDiffBetweenNowAndGivenDate(message.ReceivedTime) > 1
                           select message;

                case Times.Earlier:
                    return from message in messages
                        where GetDaysDiffBetweenNowAndGivenDate(message.ReceivedTime) > 7
                        select message;
                default:
                    return null;

            }
        }

        private int GetDaysDiffBetweenNowAndGivenDate(DateTime givenDateTime)
        {
            return (DateTime.Today - givenDateTime).Days;
        }

        public class Message
        {
            public string ReceivedMessage { get; set; }
            public DateTime ReceivedTime { get; set; }
            public string SentBy { get; set; }
        }

        private enum Times { Day, Week, Earlier};

        // Create a User object and serialize it to a JSON stream.
        public string WriteFromObject(Message message)
        {

            // Create a stream to serialize the object to.
            var ms = new MemoryStream();

            // Serializer the User object to the stream.
            var ser = new DataContractJsonSerializer(typeof(Message));
            ser.WriteObject(ms, message);
            byte[] json = ms.ToArray();
            ms.Close();
            return Encoding.UTF8.GetString(json, 0, json.Length);
        }

    }

A: You could first define your ranges and use a select to get the desired result.
Haven't really checked if these ranges are correct, but you should get an idea on how to proceed. See dotnetfiddle example.
    var ranges = new List<GroupRange>
    {
        new GroupRange
        {
            Name = "Today",
            DateRange = (DateTime.Now.Date, DateTime.Now.AddDays(1).AddTicks(-1))
        },
        new GroupRange
        {
            Name = "This Week",
            DateRange = (DateTime.Now.FirstDayOfWeek(), DateTime.Now.LastDayOfWeek())
        },
        new GroupRange
        {
            Name = "Earlier",
            DateRange = (DateTime.MinValue, DateTime.Now.FirstDayOfWeek().AddDays(-1))
        },
    };

    var result = ranges
        .Select(r => new
        {
            Period = r.Name,
            Messages = data
                .Where(d => d.ReceivedTime >= r.DateRange.Item1 &&
                            d.ReceivedTime <= r.DateRange.Item2)
        });

A: Doesn't some like it ought to be much more complicated than something like this:
class Program
{
  static void Main( string[] args )
  {
    IEnumerable<Item> items = Enumerable.Empty<Item>();

    ( Age Age, Item[] Items )[] partitioned =
      items
      .Select( item => ComputeAge(item) )
      .GroupBy( x => x.Age )
      .Select( g => (
        Key    : g.Key ,
        Values : g.Select( x => x.Item )
                  .ToArray()
      ))
      .ToArray();
      ;

  }
  static ( Item Item, Age Age ) ComputeAge(Item item)
  {
    double days = (DateTime.Now - item.Received).TotalDays;
    Age age;

    // Does "week" means "with the last 7 days" or "within the current calendar week"
    // We'll assume it means within the last 7 days.
    if      ( days <  0.0 ) age = Age.Unknown;
    else if ( days <= 1.0 ) age = Age.Today;
    else if ( days <= 7.0 ) age = Age.Today;
    else                    age = Age.Earlier;

    return (item, age) ;
  }

}

public enum Age { Unknown = 0, Today = 1, ThisWeek = 2, Earlier = 3 }

class Item
{
  public string   Message  { get; set; }
  public string   Sender   { get; set; }
  public DateTime Received { get; set; }
}


text:
Q: Mock Lambda Parameterless Expression Getting my head all banged up trying to moq the interface below. The GetOrSet has me tripped up. The service comes from here
public interface ICacheService
{
    T GetOrSet<T>(string cackeKey, int expiryInMinutes, Func<T> getItemCallback) where T : class;
}

public class CacheService : ICacheService
{
    public T GetOrSet<T>(string cacheKey, int expiryInMinutes, Func<T> getItemCallback) where T : class
    {

        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(expiryInMinutes));
        }
        return item;
    }
}

Example in code:
var result = _cacheService.GetOrSet(
        cacheKey,
        cacheExpiry,
      () => this.GetRoutes(routeType));
return result.Select(x => new Route(x));

A: Basic setup could look like:
public static ICacheService GetMockCacheService<T>() where T : class
{
     var mock = new Mock<ICacheService>();

     mock.Setup(service => service.GetOrSet(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<Func<T>>()))
         .Returns(default(T));

     return mock.Object;
}

Use a generic method to build your mock for whatever type you need in the implementation.


text:
Q: What exactly does dirty-chai.js do? The package description for dirty-chai is a bit opaque for a newbie:

Function form for terminating assertion properties

What is an 'assertion property' in this context and what does terminating mean? Why are they not normally "terminated"? I have so many questions. An example without dirty-chai and and an example with, that shows the benefit would be great.

A: I think one of the key reasons for dirty-chai is that it is not considered good practice to make assertions on property access (at least for some in the JavaScript community).
Without the plug-in chai allows you write tests like this:
chai.expect(someFunctionThatReturnsTrue(args)).to.be.true

If the test failed, that means someFunctionThatReturnsTrue(args) must have been returning something other than true and from that you know to start debugging its code to see why.
However, for this test to function, accessing the true property needs to make assertions and disrupt the code execution if the assertion fails (for example, by throwing an Exception).
Linters generally do not know how property access is done and would by default assume that the accessing of a property will not have any side-effects (i.e. alter the environment), especially not things like throwing exceptions (or cause other control-flow disrupting consequences).
Therefore, if you write something.true (without parentheses), the linter will assume that you simply want to access a property of something named true. If the expression goes nowhere (not used in an assignment, as function parameters, or in other evaluations), the linter would flag this a a potential typo or something else. Therefore, the previous valid case in chai will generate a linter error.
And these kind of linter errors can be useful in some cases because JavaScript does not complain if you try to access properties that do not exist. For example, what if you do have a typo in your test code?
chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture
                                                  // ~~~~ not `true`, obviously a typo

This test would pass no matter what someFunctionThatReturnsTrue(args) returns. Because accessing .ture simply returns undefined and will not throw an error. Then you may miss some coding errors in someFunctionThatReturnsTrue() if you are forced to ignore these linter errors by chai.
Worse, if there is any error, you may assume that it's not in someFunctionThatReturnsTrue() because that test (wrongly) passes.
Thus the plugin, dirty-chai, by converting assertions by property access (like .true) into calling these properties as function (.true()) make sure linters will know that these statements can change the control flow:
chai.expect(someFunctionThatReturnsTrue(args)).to.be.true()
// Linter now knows you are expecting something to happen during `.true()` call
// and won't complain anymore

And now if you make a typo, the test will fail (by throwing an exception)
chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture()
                                                  // ~~~~ Will throw something like
                                                  // `...to.be.ture is not a function`


text:
Q: D-Link 6850U dropping LAN connections My router seems to be dropping connections briefly on the LAN side.  I say this because a) My ISP reports no interruptions and b) I'm seeing interruption both with VPN connections and with watching videos from a hard disc connected to the router's USB port -- which is obviously only internal.
Can anybody explain my experience?  Are there configuration options that I can use to prevent -- or at least minimize -- these interruptions?
I turned on the router's "system log" and set it to "warning" level.  I see a bunch of lines that look like this:

warn  radvd[3801]: received RA from fe80::290:4cff:fe0c:0

this:

alert kernel: Intrusion -> IN=ppp1.1 OUT=

and this:

alert kernel: Intrusion -> IN=ppp1.1 OUT= MAC= SRC=110.55.1.230
  DST=109.67.177.38 LEN=48 TOS=0x00 PREC=0x00 TTL=111 ID=24881 DF
  PROTO=TCP SPT=54569 DPT=30650 WINDOW=8192 RES=0x00 SYN URGP=0
  MARK=0x8000002

I don't know what any of them means, but perhaps that will help someone diagnose my problem.
Thanks in advance.
Michael


text:
Q: Routing IP addresses in Ubuntu 20.04 I have several servers on a private network, each with a private IP address assigned and a public IP assigned. I want the servers to only communicate with each other using their private IP addresses.
I have set up the IP addresses using Netplan, but am now trying to set up the routes so that if Server A is trying to communicate with Server B it does so via Server A's private ip, not through any other IP assigned to the server.
This is my Netplan configuration file so far (I've XXX'd out parts of the public IP addresses for security):
network:
  ethernets:
    ens160:
      addresses:
      - 217.147.XXX.43/26
      - 172.17.1.151/24
      dhcp4: false
      #gateway4: 217.147.XXX.1
      #gateway4: 172.17.1.1
      nameservers:
        addresses:
        - 172.17.1.2
        - 172.17.1.3
        - 8.8.8.8
        search: []
      routes:
      - to: 0.0.0.0/0
        via: 217.147.XXX.1
        metric: 100
      - to: 172.17.1.0/24
        via: 172.17.1.1
        metric: 101
  version: 2

The output of ip route command:
$ ip route
default via 217.147.XXX.1 dev ens160 proto static metric 100
172.17.1.0/24 dev ens160 proto kernel scope link src 172.17.1.151
172.17.1.0/24 via 172.17.1.1 dev ens160 proto static metric 101
217.147.XXX.0/26 dev ens160 proto kernel scope link src 217.147.XXX.43

Output of the ifconfig command:
$ ifconfig
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 217.147.XXX.43  netmask 255.255.255.192  broadcast 217.147.XXX.63
        inet6 fe80::2cc:29cc:fef5:966f  prefixlen 64  scopeid 0x20<link>
        ether 00:cc:29:cc:96:6f  txqueuelen 1000  (Ethernet)
        RX packets 728  bytes 71057 (71.0 KB)
        RX errors 0  dropped 119  overruns 0  frame 0
        TX packets 355  bytes 58475 (58.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 102  bytes 8213 (8.2 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 102  bytes 8213 (8.2 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

The problem that I have is that private network is not visible.
$ ping 172.17.1.155
PING 172.17.1.155 (172.17.1.155) 56(84) bytes of data.
From 172.17.1.151 icmp_seq=1 Destination Host Unreachable
From 172.17.1.151 icmp_seq=2 Destination Host Unreachable
From 172.17.1.151 icmp_seq=3 Destination Host Unreachable
. . .

the server 172.XXX.XXX.155 is available from other servers in private network.
Any help would be greatly appreciated. I'm fairly new to networking and Netplan and I'm struggling with the official documentation.

A:   - to: 172.17.1.0/24
    via: 172.17.1.1
    metric: 101

This is incorrect.  172.17.1.0/24 is your local network, and you are trying to route all traffic for it via 172.17.1.1.  That machine is probably not configured to route traffic both to and from 172.17.1..0 on the same interface.  If you drop this route, traffic to 172.17.1.155 will be routed via your local network instead, which should work.


text:
Q: How to create form with multiple page on JSF with PrimeFaces Hi I wanna ask something, I try to make a form for website using java with primeface, I make this form with 2 page but when I try to input data, the data from second page can't set on database sometimes when I try to modify the code the data on first page can't set but the data on second page can be set on database
this my code for save data
public String save(){
    String nextPage = "";

    PRPKUserNonIt PRPKUser = new PRPKUserNonIt();

    PRPKUser prpkUser = new PRPKUser();
    setListUserSelected(chooseBean.getListSelecteduser());

    try{
        prpkUserController.save(prpkUser);
        nextPage = "/prpk/master_prpk.xhtml?faces-redirect=true";
        RequestContext rq = RequestContext.getCurrentInstance();
        rq.execute("PF('successDialog').show();");
    }catch(Exception e){
        e.printStackTrace();
        FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error","Save data failed");
        RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
        nextPage = "#";
    }

    Group group = new Group();
    setListGroupSelected(chooseTargetSDDialogBean.getGroupSelection());
    try{
        groupController.save(group);
        nextPage = "/prpk/master_prpk.xhtml?faces-redirect=true";
        RequestContext rq = RequestContext.getCurrentInstance();
        rq.execute("PF('successDialog').show();");
    }catch(Exception e){
        e.printStackTrace();
        FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error","Save data failed");
        RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
        nextPage = "#";
    }

    PRPKNon PRPKNon = new PRPKNon();

    PRPKNon.setUser_non_itId(userLogin.getId());
    PRPKNon.setSenderId(userLogin.getId());
    PRPKNon.setPic_prpkId(userLogin.getId());
    PRPKNon.setCreatedBy(userLogin.getName());
    PRPKNon.setUpdatedBy(userLogin.getName());
    for (Map.Entry<String, Integer> e : prpkTypeIdMap.entrySet()) {
        if (prpkTypeTypeId.equals(e.getValue())) {
            prpkTypeType = e.getKey();
            continue;
        }
    }
    PRPKNon.setPrpkTypeId(prpkTypeTypeId); //diubah
    PRPKNon.setPrpkTypeName(prpkTypeType);
    PRPKNon.setPrpkDesc(prpkDesc);
    PRPKNon.setMemoNumber(memoNumber);

    for (Map.Entry<String, Integer> e : priorityIdMap.entrySet()) {
        if (priorityTypeId.equals(e.getValue())) {
            priorityType = e.getKey();
            continue;
        }
    }
    setPriorityLevelId(priorityTypeId);
    setPriorityName(priorityType);

    for (Map.Entry<String, Integer> e : departmentIdMap.entrySet()) {
        if (departmentTypeId.equals(e.getValue())) {
            departmentType = e.getKey();
            continue;
        }
    }

    for (Map.Entry<String, Integer> e : businessUnitIdMap.entrySet()) {
        if (businessUnitTypeId.equals(e.getValue())) {
            businessUnitType = e.getKey();
            continue;
        }
    }

    PRPKNon.setPriorityId(getPriorityLevelId());//diubah
    PRPKNon.setPriorityLevel(getPriorityName());
    PRPKNon.setBusinessUnitId(getBusinessId());
    PRPKNon.setBusinessUnitName(getBussinessName());
    PRPKNon.setPicDepartmentId(getDepartmentId());
    PRPKNon.setDepartmentName(getDepartmentNames());

    PRPKNon.setBusinessUnitId(getBusinessUnitId());

    PRPKNon.setPicDepartmentId(departmentTypeId);//diubah
    System.out.println("Pic : "+ prpk.getPicDepartmentId());
    PRPKNon.setDepartmentName(departmentType);

    PRPKNon.setBusinessUnitId(businessUnitTypeId);//diubah
    PRPKNon.setBusinessUnitName(businessUnitType);
    nextPage = "/prpk/next_prpk_new.xhtml?faces-redirect=true";
    PRPKNon.setPrpkRequest(prpkRequest);
    PRPKNon.setPrpkBackground(prpkBackground);
    PRPKNon.setPrpk_analysisBenefit(prpk_analysisBenefit);

    try{
        prpkNonController.save(PRPKNon);
        nextPage = "/prpk/next_prpk_new.xhtml?faces-redirect=true";
        RequestContext rq = RequestContext.getCurrentInstance();
        rq.execute("PF('successDialog').show();");
    }catch(Exception e){
        e.printStackTrace();
        FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error","Save data failed");
        RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
        nextPage = "#";
    }

    return nextPage;
}

this xhtml for the first page

<ui:define name="metadata">
</ui:define>
<ui:define name="content">
    <h:form id="formId" style="margin-top:35;" prependId="false">

        <h:panelGrid id="TableInputId" columns="2" cellpadding="10" >
             <h:panelGrid id="inputGridId1" columns="3" cellpadding="10" >

                    <f:selectItem itemLabel="None Selected" itemValue=""
                        noSelectionOption="true" />
                    <f:selectItems value="#{pRPKUserNonItBean.prpkTypeIdMap}" />

                <h:panelGrid columns="2" cellpadding="0" border="0">

                </h:panelGrid>

                </h:panelGrid>

            <h:panelGrid id="inputGridId2" columns="3" cellpadding="10" >

                    <f:selectItem itemLabel="None Selected" itemValue=""
                        noSelectionOption="true" />
                    <f:selectItems value="#{pRPKUserNonItBean.priorityIdMap}" />

                    <f:selectItem itemLabel="None Selected" itemValue=""
                        noSelectionOption="true" />
                    <f:selectItems value="#{pRPKUserNonItBean.departmentIdMap}" />

                    <f:selectItem itemLabel="None Selected" itemValue=""
                        noSelectionOption="true" />
                    <f:selectItems value="#{pRPKUserNonItBean.businessUnitIdMap}" />

                </h:panelGrid>
    </h:panelGrid>

            <h:panelGrid width="60%">

                <p:dataTable
                    paginatorPosition="bottom" rows="3" paginator="true"
                    rowsPerPageTemplate="10,15,25,50,100" rowIndexVar="rowIndex"
                    currentPageReportTemplate="Showing {startRecord}-{endRecord} out of {totalRecords}"
                    paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                    style="font-size:12px;"
                    var="group" widgetVar="targetTables" value="#{chooseTargetSDDialogBean.listGroupTemp}" id="targetTable">

                        <h:outputText value="#{rowIndex+1}" />

                        <h:outputText value="#{group.name}" />

                        <h:outputText value="#{group.description}" />

            </h:panelGrid>

    </h:form>
</ui:define>

and this xhtml for the second page

<ui:define name="metadata">
</ui:define>
<ui:define name="content">
    <h:form id="formId" style="margin-top:35;">

        <h:panelGrid style="margin-left:5;margin-top:20;">

PIC PRPK *

        </h:panelGrid>
        <h:panelGrid style="margin-left:0;margin-bottom:20;margin-top:5;">

                    <h:outputText value="#{prpk.name}" />

                    <h:outputText value="#{prpk.departmentName}" />

                    <h:outputText value="#{prpk.headUserName}" />

        </h:panelGrid>

        <h:panelGrid columns="3" cellpadding="5" style="margin-left:10;">

        </h:panelGrid>

        <h:panelGrid columns="2" style="margin-left:120;">

        </h:panelGrid>

            <h:panelGrid columns="1" cellpadding="2">
                <h:outputText value="Save data berhasil" />

            </h:panelGrid>

            <h:panelGrid columns="1" cellpadding="2">
                <h:outputText value="Save data failed" />

            </h:panelGrid>

    </h:form>
</ui:define>


text:
Q: How can i display in label the real size of a file on the hard disk? I'm using this method:
public static long GetFileSizeOnDisk(string file)
        {
            FileInfo info = new FileInfo(file);
            uint dummy, sectorsPerCluster, bytesPerSector;
            int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy);
            if (result == 0) throw new Win32Exception();
            uint clusterSize = sectorsPerCluster * bytesPerSector;
            uint hosize;
            uint losize = GetCompressedFileSizeW(file, out hosize);
            long size;
            size = (long)hosize << 32 | losize;
            return ((size + clusterSize - 1) / clusterSize) * clusterSize;
        }

And use it like this:
label10.Text = GetFileSizeOnDisk(previewFileName).ToString();

The result for example is: 5074944
But what i want it to dispaly is if it's low then mega byte then display as kb and if above then as mb or gigabyte i mean if 5074944 is megabyte then display it for example as: 5,074944 MB
Including the MB
Or how it known to display/write sizes.

A: You should just use some if statements:
long size = GetFileSizeOnDisk(previewFileName);

if(size > 1024 * 1024 * 1024)
{
    label10.Text = (size / 1024 * 1024 * 1024F).ToString() + " Gb";
}
else if(size > 1024 * 1024)
{
    label10.Text = (size / 1024 * 1024F).ToString() + " Mb";
}
else if(size > 1024)
{
    label10.Text = (size / 1024F).ToString() + " Kb";
}
else
{
    label10.Text = size.ToString();
}

A: The nice thing about programming is, that repetative tasks can be automated. A solution that automatically calculates the size could be:

*

*find file size

*repeat until size is bigger than 1024

*divide size by 1024

*store size position

*loop

The code can look like this:
private String sizeFormatter(Int64 filesize)
{
    var sizes = new List<String> { "B", "KB", "MB", "GB", "TB", "PB" };
    var size = 0;
    while (filesize > 1024)
    {
        filesize /= 1024;
        size++;
    }
    return String.Format("{0}{1}", filesize, sizes[size]);
}

And the usage:
var bigFile = new FileInfo("C:\\oracle\\OracleXE112_Win32.zip");
var smallFile = new FileInfo("C:\\oracle\\ScriptCreateUser.sql");
var verySmallFile = new FileInfo("C:\\ScriptCreateTable.sql");
Console.WriteLine(sizeFormatter(bigFile.Length));
Console.WriteLine(sizeFormatter(smallFile.Length));
Console.WriteLine(sizeFormatter(verySmallFile.Length));

The output is:
312MB
12KB
363B

This method could be optimized regarding accuracy, but for the general usage it should be alright.


text:
Q: How to remove item from treeview and update the total order cost I am building billing system using Python & MySQL. I have done a lot but one problem arises: how to update the total cost of an order if one item is removed from the order. I have designed the below function. It is working partially and the item is getting removed from the order. But when the first item is removed, the total cost is not updating.
Below is the treeview for order and remove order function:
scrollBar=Scrollbar(bill_frame,orient="vertical",command=billsTV.yview)
scrollBar.grid(row=5,column=4,sticky="NSE")

billsTV.configure(yscrollcommand=scrollBar.set)

billsTV.heading("#0",text="Item Name")
billsTV.column('#0',minwidth=0,width=100)
billsTV.heading("#1",text="Rate")
billsTV.column('#1',minwidth=0,width=250)
billsTV.heading("#2",text="Quantity")
billsTV.column('#2',minwidth=0,width=150)
billsTV.heading("#3",text="Cost")
billsTV.column('#3',minwidth=0,width=150)

def removeOrder():
    totalCost=0.0
    for child in billsTV.get_children():
         totalCost+=float(billsTV.item(child,"values")[2])
         totalCostVar.set("Total Cost={}".format(totalCost))
    selected_item=(billsTV.selection()[0])
    billsTV.delete(selected_item)

I appreciate your help. Thanks.


text:
Q: Make a function that is not of bounded variation on $[a,b]$
A function $f$ ,defined on [a,b],is said to satisfy a uniform Lipschitz condition of order $\alpha > 0$ on [a,b] if there exists a constant $M>0$ such that $|f(x)-f(y)|<M|x-y|^{\alpha}$
Give an example of a function satisfying a uniform Lipschitz condition of order $\alpha<1$ on [a,b] such that f is not of bounded variation on [a,b].
Give an example of a function $f$ which is of bounded variation on [a,b],but which satisfies no uniform Lipschitz condition.

I think of function like $f=\sqrt{x}sin(\frac{1}{x})$,and like $f=xcos(\frac{\pi}{2x})$,but they are not work,I don't know how to deal with $|\sqrt{x}sin(\frac{1}{x})-\sqrt{y}sin(\frac{1}{y})|$
Could you help me? I don't know how to make a such function.
What do you think the problem when the problem ask you to give a specific example ?
Thank you very much!!

A: The Weierstrass function is not of bounded variation since it is nowhere differentiable, but is Hölder continuous, i.e., it satisfies a Lipschitz condition of order $\alpha < 1$.
For the second part, a discontinuous step function (or any monotone or piecewise monotone function with a jump discontinuity) has bounded variation but cannot satisfy a Lipschitz condition.


text:
Q: Excel Range Count within a cell I am trying to compare qty and number of entries in an excel spreadsheet.
For instance,
QTY RefDes      # of Entries    QTY Match RefDes?
3   R1,R5,R22   3               MATCH
3   C1,C2,C3    3               MATCH
3   U1-U3       1               MISMATCH
4   U1-U3, U5   2               MISMATCH

By using =LEN(TRIM(B2))-LEN(SUBSTITUTE(TRIM(B2),",",""))+1 for the column listed # of Entries, I can easily compare the listed QTY vs. ReDes when the values individually are separated by commas as in R1,R5,R22.
(QTY Match RefDes? is simply comparing if the QTY column matches the # of Entries column.)
However, I also have cases where U1-U3 would denote a range from U1 to U3 or U1,U2,U3. The actual quantity is 3, but the formula above returns a value of 1 because there is no comma separation. How can I account for this case?

A: This CAN be done with a formula, but there is a caveat.
Excel has a handy function called EVALUATE(), that evaluates text strings as equations and produces a numeric result.  The caveat has to do with the restrictions on how it can be used.
I guessed that your ranges in Column U could be any size, so a good way to get the count would be to do the subtraction. i.e. for U1-U3, extract the "1-3" and do the math.  This formula does that:
 =IFERROR(ABS(EVALUATE((REPLACE(MID(B2,FIND("-",B2)-1,4),3,1,"")))),0)

Using B5 as an example, the MID() portion gets characters on either side of the "-", and gives 1-U3. The REPLACE() removes the U, and EVALUATE() performs the subtraction, giving -2. ABS() gives 2 and IFERROR() handles the rows with no U range.  Here is the data with the above equation in Column E, and the sum of this column plus your equation above in Column F:

Now about the caveat.  For whatever reason, EVALUATE() is ONLY available if it is used in the definition of a named range.  So to use the above equation, click on any cell, give the cell a name (I used "Funk" here), and paste the equation into the "Refers to:" box.

Now the name can be used like a function. Type "=Funk" (with no quotes) in E2 and fill down.
If you can't have the helper column, you could combine the two equations in the name definition.  But I'll warn you that troubleshooting formulas in the little box is a PITA.  It's a shame this function isn't available without jumping through these hoops.
I hope this helps.


text:
Q: WPF Centering Pinch to Zoom with LayoutTransform UPDATE 1
I believe I need to set the Vertical and Horizontal offset's of the ScrollViewer based on the Manipulation Origin value to keep the image under the "pinch". However, I'm having the trouble with how to calculate those values.

As part of a larger application, we want users to be able to pinch-zoom and drag to pan an image inside of a scroll viewer. What I have below will allow panning and pinch-to-zoom. However, the zoom seems to take place from the upper left, and I want it centered under the "pinch". How can I modify this code to do that?
I've found examples that do this perfectly with RenderTransform, but can't figure out how to do it with LayoutTransforms.
Here is my xaml setup:
   <ScrollViewer Name="MainScrollViewer" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"  >
        <Image Name="MainImage" Source="/test.jpg" Stretch="None" IsManipulationEnabled="True">
            <Image.LayoutTransform>
                <ScaleTransform x:Name="ScaleTrans"/>
            </Image.LayoutTransform>
        </Image>
    </ScrollViewer>

Here is the code behind:
Private Sub MainImage_ManipulationStarting(sender As Object, e As ManipulationStartingEventArgs) Handles MainImage.ManipulationStarting
    e.ManipulationContainer = MainScrollViewer
    e.Handled = True
End Sub

Private Sub MainImage_ManipulationDelta(sender As Object, e As ManipulationDeltaEventArgs) Handles MainImage.ManipulationDelta
    Dim delta = e.DeltaManipulation
    Dim element = TryCast(e.Source, FrameworkElement)
    If element IsNot Nothing Then
        'Apply Scale Value
        ScaleTrans.ScaleX *= delta.Scale.X
        ScaleTrans.ScaleY *= delta.Scale.Y

        'Panning
        MainScrollViewer.ScrollToHorizontalOffset(MainScrollViewer.HorizontalOffset + delta.Translation.X * -1)
        MainScrollViewer.ScrollToVerticalOffset(MainScrollViewer.VerticalOffset + delta.Translation.Y * -1)
    End If
End Sub

A: Set the transform's center point.
<ScrollViewer Name="MainScrollViewer" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"  >
    <Image Name="MainImage" Source="/test.jpg" Stretch="None" IsManipulationEnabled="True">
        <Image.LayoutTransform>
            <ScaleTransform x:Name="ScaleTrans" CenterX="0.5" CenterY="0.5" />
        </Image.LayoutTransform>
    </Image>
</ScrollViewer>

If you need it to be relative to where the pinch is, do it code behind. Like the xaml version, you change the CenterX and CenterY properties of ScaleTransform. However, do note that these two properties are not point values, but rather values from 0.0 to 1.0 relative to itself. CenterX = 0.0/CenterY = 0.0 refer top left, while CenterX = 1.0/CenterY = 1.0 is bottom right. You need to do some calculation on your own.


text:
Q: Troubles with Background Resposive I'm have a problem with responsive background on Chrome mobile. My problem is only with Chrome.
What I gonna do?
    body{
     background-image: url(images/home.png);
     background-position:center;
     background-color:#2e4053;
     background-size:cover;
    }

  @media only screen and (max-device-width: 1100px) {
    body {
     background-image: url(images/homemobile.png);
     background-position:center;
     background-color:#2e4053;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -ms-background-size:cover;
     -o-background-size:cover;
     }
    }

Chrome on desktop: http://prntscr.com/necegy
Chrome Mobile: http://prntscr.com/necf2a
Firefox Mobile: http://prntscr.com/necf8t

A: Try to give margin and padding to the body too.
body{
        margin:0;
        padding:0;
        background-attachment: fixed;
}

A: *

*Make sure you add background-repeat: no-repeat

*Make sure your page is forced to a minimum height of 100%

*Also you don't need to repeat the entire style in the media query – just the one changed

... something like this
html {
    height: 100%;
}

body{
    min-height: 100%;
    background-image: url(images/home.png);
    background-position: center;
    background-color: #2e4053;
    background-size:cover;
    background-repeat: no-repeat;
}

@media only screen and (max-device-width: 1100px) {
    body {
        background-image: url(images/homemobile.png);
    }
}


text:
Q: Как вывести результат функции на экран через нажатие кнопки (модуль Tkinter) Столкнулся с проблемой. Есть функция
def get_one(name, descr)
 return print(f'{name}:{descr}')
get_one('Aim of life', 'Drama')

Нужно вывести результат её работы на экран в окошко при нажатии кнопки. И простой передачей функции и через get у меня не вышло. Может, кто-то сможет подсказать решение проблемы
root = Tk()
def one_click():
    get_one()

root.title('Kino Afisha')
root.geometry('500x650')
root.resizable(width=False, height=False)
one = get_all_films()
btn = Button(root, text="Не нажимать!", command=one_click)

btn.pack()
root.mainloop()


text:
Q: Rails inline mail attachments not working properly I am using ActionMailer to send an inline image. The user_mailer.rb file looks like this:
def welcome_mail(user, mail_content, subject)
  @user = user
  @mail_content = mail_content.html_safe
  attachments.inline['orglogo.png'] = File.read("#{Rails.root}/app/assets/images/orglogo.png")
  mail(:to => ["testuser@domain.com"],:Subject => subject)
end

And the view contains:
<%= image_tag attachments['orglogo.png'].url %>

The image isn't appearing in the mail. This is how it appears in the mail client. I have tested on Outlook and Hotmail.

A: In my production app we are sending inline image using the above method and for me everything is working very fine for me. So i created the public gist for that working snippet of code. Please see if it helps you.
GistPublic gist with mailers
If doesn't work please try to paste your development.log here.
Thanks

A: Well, the solution or rather workaround that worked was to upgrade to Rails 4. I am able to send  inline images without any problem in Rails 4.


text:
Q: struct tms values returned by times() all zero or negative  I'm trying to implement the times() function in C programming.
I'm using the struct tms structure which consists of the fields: tms_utime, tms_cutime,
tms_stime and tms_cstime.
In order to implement the times() function in my program, I do:

*

*Before I fork and create a child, I call the times function (in the parent process).
times(&start_tms);

*I create a pipe and I pass the times of start structure to the pipe when I'm in the child process.

*The child executes a simple ls -l command

*When the child finishes he execution, the father calls for the second time the times() function.
times(&end_tms);

Unfortunately, the times of end_tms are all zero! Weird, but I don't know why.
Some things I don't understand in my program are:
1) In the first printfs the times of the struct start are negative. Why is that?
2) When I run the program, why do I get zeros for times? What am i doing wrong?
My program is as follows:
Thanks, in advance

#include <sys/times.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main() {

printf("test\n");

int     fd[2]; //two pointers
int nbytes;
char    string[] = "Hello, world!\n";
char    readbuffer[80];
struct tms start_tms;
struct tms end_tms;
clock_t start, end;
double cpu_time_used;

pipe(fd);

//once we have established the pipeline we fork the child
pid_t   childpid;
pid_t pid_waitpid;

//NEW MODIFICATION!!! call times before fork()!!!
times(&start_tms);

//they return negative values, but why???
printf("Test start_tms.tms_utime = %f\n\n",start_tms.tms_utime);
printf("Test start_tms.tms_cutime = %f\n\n",start_tms.tms_cutime);
printf("Test start_tms.tms_stime = %f\n\n",start_tms.tms_stime);

if((childpid = fork()) == -1)
            {
                    perror("fork");
                    exit(1);
            }

if(childpid == 0)
            {

                    /* Child process closes up input side of pipe */
                     close(fd[0]);

                   /* call times function */
                   /*times(&start_tms);*/

                      //REMOVED!!!!
                    //write(fd[1], string, (strlen(string)+1));
                    write(fd[1], &start_tms.tms_cutime, sizeof(clock_t));
                    write(fd[1], &start_tms.tms_utime, sizeof(clock_t));
                    write(fd[1], &start_tms.tms_stime, sizeof(clock_t));

                     //execute /bin/ls
                    execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);

                    exit(0);

            }
else
            {
                    /* Parent process closes up output side of pipe */
                    close(fd[1]);

                    /* NEW MODIFICATION, wait for the child!!! */
                     if( (pid_waitpid  = waitpid(childpid,NULL,0) ) == -1)
                    {
                             perror("waitpid");
                             exit(1);
                     }

                    /* call times for capturing end times */
                    times(&end_tms);

                    /* define t1, t2, variables */
                    clock_t t1,t2,t3;

                     //REMOVED!!!!
                    //nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                    read(fd[0], &t1, sizeof(clock_t));
                    read(fd[0], &t2, sizeof(clock_t));
                    read(fd[0], &t3, sizeof(clock_t));

                    printf("Received string: %s\n\n", readbuffer);
                    printf("Test t1 = %f\n\n",t1);
                    printf("Test end_tms.tms_utime = %f\n\n",end_tms.tms_utime);
                    printf("Test end_tms.tms_cutime = %f\n\n",end_tms.tms_cutime);
                    printf("Test end_tms.tms_stime = %f\n\n",end_tms.tms_stime);

                    /* Calculate times, unfortunately return zero, but why??? */
                    double cpu_time = end_tms.tms_cutime - t1;
                    double utime = end_tms.tms_utime - t2;
                    double stime = end_tms.tms_stime - t3;

                    //Unfortunately printfs return zero, but why???
                    printf("cpu time %f\n\n",cpu_time);
                    printf("cpu Utime %f\n\n",utime);
                    printf("cpu Stime %f\n\n",stime);

}

}

A: Your logic is very strange. The writes you do in the child simply copy data that is already available to the parent in start_tms, so your whole pipe read/write thing is unnecessary.
Secondly, clock_t is not a floating point type, it's an integral type. You can't use %f to print it. Use %jd and intmax_t to be safe in the printfs.
And you're missing #include <sys/wait.h> for waitpid. So turn on your compiler warnings, and read them.
Here's a C99 version of your code that works here:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/wait.h>
#include <sys/times.h>
#include <sys/types.h>

int main() {
    struct tms start_tms;
    struct tms end_tms;

    //once we have established the pipeline we fork the child
    pid_t   childpid;

    times(&start_tms);

    printf("Test start_tms.tms_utime = %jd\n\n",  (intmax_t)start_tms.tms_utime);
    printf("Test start_tms.tms_cutime = %jd\n\n", (intmax_t)start_tms.tms_cutime);
    printf("Test start_tms.tms_stime = %jd\n\n",  (intmax_t)start_tms.tms_stime);
    printf("Test start_tms.tms_cstime = %jd\n\n",  (intmax_t)start_tms.tms_cstime);

    if((childpid = fork()) == -1)
    {
        perror("fork");
        exit(1);
    }

    if(childpid == 0)
    {
        //execute /bin/ls
        execl("/bin/ls", "/bin/ls", "-R", "-t", "-l", (char *) 0);
        exit(0);
    }
    else
    {
        /* Parent process */

        /* NEW MODIFICATION, wait for the child!!! */
        if (waitpid(childpid,NULL,0) == -1)
        {
            perror("waitpid");
            exit(1);
        }

        /* call times for capturing end times */
        times(&end_tms);

        printf("Test end_tms.tms_utime = %jd\n\n",end_tms.tms_utime);
        printf("Test end_tms.tms_cutime = %jd\n\n",end_tms.tms_cutime);
        printf("Test end_tms.tms_stime = %jd\n\n",end_tms.tms_stime);
        printf("Test end_tms.tms_cstime = %jd\n\n",end_tms.tms_cstime);

        /* Calculate times, unfortunately return zero, but why??? */
        clock_t cpu_time = end_tms.tms_cutime - start_tms.tms_cutime;
        clock_t utime = end_tms.tms_utime - start_tms.tms_utime;
        clock_t stime = end_tms.tms_stime - start_tms.tms_stime;
        clock_t cstime = end_tms.tms_cstime - start_tms.tms_cstime;

        //Unfortunately printfs return zero, but why???
        printf("cpu time %jd\n\n",  (intmax_t)cpu_time);
        printf("cpu Utime %jd\n\n", (intmax_t)utime);
        printf("cpu Stime %jd\n\n", (intmax_t)stime);
        printf("cpu CStime %jd\n\n", (intmax_t)cstime);
    }
}

If you don't have intmax_t, check the size of clock_t on your implementation and find a standard integer type that matches it, and use the appropriate format string in your printf calls.


text:
Q: get-event log the handle is invalid I Use the below command for read Event log:
Get-EventLog -LogName 'Operations Manager'

but the system return the below error :
 get-eventlog :the handle is invalid

why?and how can I solve this problem?


text:
Q: Update Navigation drawer listview My application implements a navigation drawer to change fragments. What I need now is to update the navigation drawer items if the user is logged in
For example :
logged in navigation items look like this
Home
My Info
Logout
logged off navigation items look like this
Home
Register
Login
The set up of my project is
a Base activity which extends Navigation fragment and changes to a current fragment based on the selected navigation drawer item.
All my other files are fragments which change depending on the navigation drawer item selected.
I have this kind of working but navgation drawer only updates when I log in then close the app completely and then re start it.

A: Your Activity must be aware of your drawer's ListView. So when you log in, you just need to tell your Activity to tell your ListView that the data has changed, or reload it completely.
In your fragment (or wherever you actually log in):
public void logIn() {
    ...
    ((DrawerActivity) getActivity()).updateDrawer();
}

In your DrawerActivity:
public void updateDrawer() {
    mListViewAdapter.notifyDataSetChanged();
    // OR
    mListView.setAdapter(new AdapterShowingTheRightTitles());
}


text:
Q: count items in a column using pandas A csv file from a DDBB. Some rows in a column have over a item. I would like to count every item in every rows in a column
for example; a line in a column has four items:
column1, column2, column3, column4
aaa, bbb,ccc,ddd ddd ddd ddd, eee
bbb, ccc,eee, ddd, eee
fff, ccc, eee,ddd, eee

df["column3"].value_counts()  must be 6
df["column3"].str.split('\n', expand=True) not work

A: After splitting you can sum the lengths of the results:
>>> df.column3.str.split().str.len().sum()
6

Alternatively, summing the count of whitespaces (plus 1) without splitting:
>>> df.column3.str.count("\s+").add(1).sum()
6

Doing this for every column:
>>> df.apply(lambda s: s.str.count("\s+").add(1).sum())

column1    3
column2    3
column3    6
column4    3


text:
Q: json parse error for html content My problem is html content not being parsed with JSON.parse .

*

*I am getting input from a content editable div.
var content = $("#contentInput").html();

*I am sending it to server after JSON.stringify
var dataToServer= JSON.stringify(content); //sending an object

*The same content I am getting from server, and I attempting to parse it.;
var dataFromServer = JSON.parse(content);
Here my problem raises parser throwing error. content of html data receiving as it is.
I was tried eval but after reading the some articles I was withdrawn my decision.
How to resolve the problem.

A: Here is fiidle demo of working code.
The problem is your server corrupting the content. Please check out your server code, it may add some non printable charaecters.
JSON.parse fails if the content not in JSON format. It strictly follow the rules of jsonstring to parse it( I mean double quotations and other /).
Your server may be adding some other unuseful characters to content or jsonstring.

A: JSON.stringify expects a javascript object. Try like this:
var content = $("#contentInput").html();
var dataToServer = JSON.stringify({ html: content });
...
var dataFromServer = JSON.parse(dataToServer);
var content = dataFromServer.html;


text:
Q: Analysis: Differentiation problem I have been spending times on the following question for 2hrs, and I couldn't get any kind of proper proof yet.
Q: Let $f$ be continuous on $[0,\infty)$ and differentiable on $(0,\infty)$.
If $f(0)=0$ and $|f'(x)|\leq |f(x)|$ for all $x>0$, then $f(x)=0$ for all $x\geq 0$.
What I guessed are as follows:
First trial: Tried to use the MVT to show the contradiction when we assume that there exists a real $k$ s.t $f(k)\neq0$... but I failed.
Second trial: I saw that suppose $|f'(x)|= |f(x)|$ , we set a function $g(x)=\frac{f(x)}{e^x}$, then $f(x)=0$ for all $x\geq0$. But this is not the exact one since the original question involves inequality ($\because |f'(x)|\leq |f(x)|$)
Third trial: I tried to divide the domain into $[0,1]$ and $[1,\infty)$ and show that $f(x)=0$ for each of the intervals... Somehow I think I can prove in this way (for the interval $[0,1]$, used the property of compact set $\to$ so that there exists maxima & minima (supposed to be all 0 for this $f$ I guess)... and so on and for the interval $[1,\infty)$, I had no idea.
Will there be any suggestions on this question?
I would like to know if what I was missing or doing some error on my trials.
Need your help.

A: Here is a hint for the interval $[0,\frac 12]$. Let $M = \max_{[0,1/2]} |f|$ and choose $x \in [0,\frac 12]$ with the property that $|f(x)| = M$.  If $M = 0$ you have that $f$ is identically $0$ on $[0,\frac 12]$. Otherwise $x > 0$.
Now apply the Mean Value Theorem.  There is a point $c \in (0,x)$ satisfying $$\frac{f(x) - f(0)}{x-0} = f'(c).$$  Under the hypotheses of the problem this gives you $M = |f(x)| = |x||f'(c)| \le |x||f(c)| \le \frac 12 M.$ This implies $M = 0$.
The conclusion is that $f$ is constant on $[0,\frac 12]$. Can you extend this to the rest of the line?


text:
Q: share object between worker processes I want to run f(x) on many different worker processes which run one (bonus points for more than one) remote machine, where x is a large object.
My interactive R session runs on node0 and I use the parallel library, so I do the following:
library(parallel)

cl <- makeCluster(rep("node1", times = 64))
clusterExport(cl, "x")
clusterExport(cl, "f")

clusterEvalQ(cl, f(x))

The problem is that sending x takes quite a while, because it is transferred to each worker process separately from the machine where the master process runs through the network connection.
Question:
is it possible to send x only once to each node and have the worker processes copy it locally?

A: Assuming the connection between master and the remote host is what is the bottleneck, you can transfer one copy to the first worker and then cache it to file and have the other workers read the data from that cache file.  Something like:
library("parallel")

## Large data object
x <- 1:1e6
f <- function(x) mean(x)

## All N=64 workers are on the same host
cl <- makeCluster(rep("node1", times = 64))

## Send function
clusterExport(cl, "f")

## Send data to first worker (over slow connection)
clusterExport(cl[1], "x")

## Save to cache file (on remote machine)
cachefile <- clusterEvalQ(cl[1], {
  saveRDS(x, file = (f <- tempfile())); f
})[[1]]

## Load cache file into remaining workers
clusterExport(cl[-1], "cachefile")
clusterEvalQ(cl[-1], { x <- readRDS(file = cachefile); TRUE })

# Resolve function on all workers
y <- clusterEvalQ(cl, f(x))

A: Here is a version that uses fifos, I am not sure how portable this is, works under Linux, I am not sure how this compares performance wise with @HenrikB's anwser:
library(parallel)

# create a very large cluster on a single (remote) node:
cl <- makePSOCKcluster(3)

# create a very large object
o <- 1:10

# create a fifo on the node and retrieve the name
fifo_name <- clusterEvalQ(cl[1], {
                        fifo_name <- tempfile()
                        system2("mkfifo", fifo_name)
                        fifo_name
})[[1]]

# send the very large object to one process on the node and the name of the fifo to all nodes
clusterExport(cl[1], "o")
clusterExport(cl, "fifo_name")

# does the actual sharing through the fifo
# note that a fifo has to be opened for reading
# before writing on it
for(i in 2:length(cl)) {
  clusterEvalQ(cl[i], { ff <- fifo(fifo_name, "rb")  })
  clusterEvalQ(cl[1], { ff <- fifo(fifo_name, "wb")
                        saveRDS(o, ff)
                        close(ff)                    })
  clusterEvalQ(cl[i], { o <- readRDS(ff)
                        close(ff)                    })
}

# cleanup
clusterEvalQ(cl[1], {   unlink(fifo_name)            })

# check if everything is there
clusterEvalQ(cl, exists("o"))

# now you can do the actual work
...


text:
Q: Is this possible in one SSH session? (BASH & PYTHON) I'm writing a python script (on a Linux box) that will perform an SSH and run a string of commands on the remote machine (Sun-OS). I'm having trouble getting the remote commands to run and give expected output and I'm not sure if this is even possible.
Depending on the syntax I use, sometimes I get : "ksh: 28317 Segmentation Fault(coredump)"
If this is not possible, but it is using a different method in either python or at the CLI, please let me know.
Thanks!
ssh user@remote_machine "/dvs/dncs/bin/tellDhct -h mempoll/mempoll_lowmem_ips.out | awk '{print $1}' > mempoll/mempoll.macs && /dvs/dncs/bin/tellDhct -h mempoll/mempoll_nonresp_ips.out | awk '{print $1}' >> mempoll/mempoll.macs"

A: Try something like this:
ssh user@remote << EOT
echo "test"
echo "you can put here anything like in a bash script"
echo "and it should work"
EOT


text:
Q: How to call a specific method in RestFul API? I have created this code:
header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

switch ($method)
{
  case 'PUT':
    break;
  case 'POST':
    do_something_with_post($request);
    break;
  case 'GET':
    do_something_with_get($request);
    break;
  case 'DELETE':
    do_something_with_delete($request);
    break;
  default:
    handle_error($request);
    break;
}

Now suppose that I execute this command:
curl -X GET http://localhost/api/method/1

so in the switch is fired the GET case, how I can call the function method and pass the parameter 1?
how I should configure the code on the switch? Someone could help me to figure out?

A: Here's a simplified way to route request paths to classes. This example assumes your base path is /app and you have a sub-folder called /classes. The class name and file name must match for this to work.
Example request:
curl -X POST http://localhost/api/user/123
Example route:
File....: /app/classes/api/User.php
Class...: new User()
Action..: postAction( $arg1 = 123 )

...
// default route
$base  = rtrim( str_replace( '\\', '/', __DIR__.'/app' ), '/' );
$area  = 'api';   // area (/api, /test, etc.)
$class = 'home';  // class name (Home.php -> new Home(), etc.)

// parse request
$verb  = strtolower( @$_SERVER['REQUEST_METHOD'] );
$path  = parse_url( @$_SERVER['REQUEST_URI'], PHP_URL_PATH );
$args  = explode( '/', trim( $path, '/' ) );

// extract area/class from request path
if( count( $args ) )
{
    $area = array_shift( $args );
}
if( count( $args ) )
{
    $class = array_shift( $args );
}

// finalize class name and file path
$class  = str_replace( ' ', '', ucwords( str_replace( '-', ' ', $class ) ) );
$file   = $base .'/classes/'. $area .'/'. $class.'.php';
$output = null;

// load/execute class
if( is_file( $file ) )
{
    include_once( $file );

    if( class_exists( $class ) )
    {
        $callable = [ new $class(), $verb.'Action' ];

        if( is_callable( $callable ) )
        {
            $output = call_user_func_array( $callable, $args );
        }
    }
}

// send response output...
if( is_null( $output ) === false )
{
    // ...
}
else
{
    // handle error
}
exit;

A: You'll want to parse the URI:
$pieces = explode('?', $_SERVER['REQUEST_URI']);
$endpoint = $pieces[0];
$endpoint_parts = explode('/', $endpoint);
$api_method = $endpoint_parts[2];
$param = $endpoint_parts[3];

Then you can invoke method from your URL with 1 like this:
$api_method($param);


text:
Q: How to output current user's AD sAMAccountName to a textbox I'm designing an eform that submits information into a CSV. I need to display the current user's sAMAccountName and the Datetime.Today in two of the text fields.
Any idea of how this would be done?
I've been trying: c#
public string UserName { get { return Session["UserName"]; } }

to:
  <asp:TextBox ID="UserName" runat="server" Width="44px" ReadOnly="true"></asp:TextBox>

A: You can pre-populate input values in your form in the Page_Load event:
protected void Page_Load(object sender, EventArgs e) {
    UserName.Text = "my value";
    TxtCurrentDate.Text = DateTime.Today.ToString();
}

A: Just augmenting this quickly with another bit of info, I was originally adding the Page_Load cmds to the codebehind's Page_load event, be sure that all prepopulation of text-boxes is handled on the .aspx page.
All contained within the .aspx

protected void Page_Load(object sender, EventArgs e)
{
    txtDate.Text = DateTime.Now.ToString();
}

<asp:TextBox ID="txtDate" runat="server" Width="181px" ReadOnly="true"></asp:TextBox>

Thanks again for the helpful reply mellamokb


text:
Q: Django - Query latest date in an ArrayField I'm making use of Django's postgres ArrayField.
Say I have a model like this:
from django.db import models
from django.contrib.postgres.fields import ArrayField

class Event(models.Model):
    name = models.CharField(max_length=200)
    dates = ArrayField(models.DateField())

And I want to find the Event with the latest date.  Is there a way to build a queryset that can do that?

A: I cannot get into the details of Django (I am not so much proficient in it). However, some pointers:

*

*Using directly the SQL language, you would use:
SELECT
    name, (SELECT max(d) FROM unnest(dates) d) AS latest_date
FROM
    Event ;

*To backconvert this to Django, check Django Postgresql ArrayField aggregation, and adapt it to your specifc case.
I think something along the lines of the following code should do the trick1:
Event.objects.annotate(arr_els=Func(F('dates'), function='unnest')) \
        .values_list('arr_els', flat=True).aggregate(Max('arr_els'))

See the SQL example at dbfiddle here.
1) I do not have the right environment to test the Django part... so, this is untested.


text:
Q: Complex data processing in pivot tables (averages) I'm plotting yield for products. I have two ways of classifying products, lets say these two ways are first as numbers: 1, 2, 3, 4, ect, and then as letters, a, b, c, d, e, ect. The letters are a subcategory of the numbers. So within products, I have many different letters within individual number groups:
1:
a, b, c, e
2:
c, d
3:
a
For each product, I've calculated yield and plotted it in a pivot table. I've plotted the pivot table so that the "letters" are a subcategory of the "numbers" within the column labels, please see picture below (please note that in the picture the subcategory is labelled using numbers as well, the "letters" subcategory is just to try to explain with more contrast in this question)

This is all well and good, but I'd like to find an average of everything within the "numbers" umbrella category. However, there's one final problem to consider with the task: the amount of products that contribute to a yield average may be different per letter subcategory. I.e:
1 - a: 2 out of 2 products yielded = 1 (fractional yield)
1 - b: 2 out of 22 products yielded = 0.09 (fractional yield)
This leads to a problem while using pivot tables. Using the above yield fractions, if I was using the pivot tables's "average of yield" to work out the total yield for all the "1" group, it would calculate:
1 + 0.09 / 2 .... = 0.54 (fractional yield)
But we can see that this isn't a true representation of yield, as it should be:
(2 + 2) / (2 + 22) =
4 / 24 =
0.17 (fractional yield)
Can anyone work out a way of calculating true yield with pivot tables rather than the average of an average?

A: I got it!
I went here: https://support.office.com/en-nz/article/Calculate-values-in-a-PivotTable-report-697406b6-ee20-4a39-acea-8128b5e904b8
And adapted this section:
Create a formula in a PivotTable report
Add a calculated field
1. Click the PivotTable report.
2. On the Options tab, in the Tools group, click Formulas, and then click Calculated Field.
3. In the Name box, type a name for the field.
4. In the Formula box, enter the formula for the field.
5. To use the data from another field in the formula, click the field in the Fields box, and then click Insert Field. For example, to calculate a 15% commission on each value in the Sales field, you could enter = Sales * 15%.
6. Click Add.

to fit my copy of Excel 2010 by doing the following:
Create a formula in a PivotTable report
Add a calculated field
1. Click the PivotTable report.
2. On the Options tab, in the Calculations group, click "Fields, Items, and Sets", and then click Calculated Field.
4. In the Name box, type a name for the field.
5. In the Formula box, enter the formula for the field (=Yielded/Total).
6. To use the data from another field in the formula, click the field in the Fields box, and then click Insert Field. For example, to calculate a 15% commission on each value in the Sales field, you could enter = Sales * 15%.
7. Click Add.

This gives the correct answers you were looking for.