Title: MD5 implementation in PHP - where am I going wrong?

Body:
I know that this might be a long stretch, but could someone possibly tell me where my current implementation of the MD5 algorithm in PHP is going wrong? I just can't seem to work out what's wrong with it.

It returns a 32 character hex string (25% of the time it produces a string less than 32 characters though), but it isn't producing the same 32 chars that the built-in MD5 function does.

Thank you very much.

<?php

function MD($string){
$a = "67452301";
$b = "EFCDAB89";
$c = "98BADCFE";
$d = "10325476";

$words = init($string);

for($i = 0; $i <= count($words)/16-1; $i++){
    $A = $a;
    $B = $b;
    $C = $c;
    $D = $d;

    /* ROUND 1 */
    FF ($A, $B, $C, $D, $words[0 + ($i * 16)], 7, "d76aa478");
    FF ($D, $A, $B, $C, $words[1 + ($i * 16)], 12, "e8c7b756");
    FF ($C, $D, $A, $B, $words[2 + ($i * 16)], 17, "242070db");
    FF ($B, $C, $D, $A, $words[3 + ($i * 16)], 22, "c1bdceee");
    FF ($A, $B, $C, $D, $words[4 + ($i * 16)], 7, "f57c0faf");
    FF ($D, $A, $B, $C, $words[5 + ($i * 16)], 12, "4787c62a");
    FF ($C, $D, $A, $B, $words[6 + ($i * 16)], 17, "a8304613");
    FF ($B, $C, $D, $A, $words[7 + ($i * 16)], 22, "fd469501");
    FF ($A, $B, $C, $D, $words[8 + ($i * 16)], 7, "698098d8");
    FF ($D, $A, $B, $C, $words[9 + ($i * 16)], 12, "8b44f7af");
    FF ($C, $D, $A, $B, $words[10 + ($i * 16)], 17, "ffff5bb1");
    FF ($B, $C, $D, $A, $words[11 + ($i * 16)], 22, "895cd7be");
    FF ($A, $B, $C, $D, $words[12 + ($i * 16)], 7, "6b901122");
    FF ($D, $A, $B, $C, $words[13 + ($i * 16)], 12, "fd987193");
    FF ($C, $D, $A, $B, $words[14 + ($i * 16)], 17, "a679438e");
    FF ($B, $C, $D, $A, $words[15 + ($i * 16)], 22, "49b40821");

    /* ROUND 2 */
    GG ($A, $B, $C, $D, $words[1 + ($i * 16)], 5, "f61e2562");
    GG ($D, $A, $B, $C, $words[6 + ($i * 16)], 9, "c040b340");
    GG ($C, $D, $A, $B, $words[11 + ($i * 16)], 14, "265e5a51");
    GG ($B, $C, $D, $A, $words[0 + ($i * 16)], 20, "e9b6c7aa");
    GG ($A, $B, $C, $D, $words[5 + ($i * 16)], 5, "d62f105d");
    GG ($D, $A, $B, $C, $words[10 + ($i * 16)], 9, "02441453");
    GG ($C, $D, $A, $B, $words[15 + ($i * 16)], 14, "d8a1e681");
    GG ($B, $C, $D, $A, $words[4 + ($i * 16)], 20, "e7d3fbc8");
    GG ($A, $B, $C, $D, $words[9 + ($i * 16)], 5, "21e1cde6");
    GG ($D, $A, $B, $C, $words[14 + ($i * 16)], 9, "c33707d6");
    GG ($C, $D, $A, $B, $words[3 + ($i * 16)], 14, "f4d50d87");
    GG ($B, $C, $D, $A, $words[8 + ($i * 16)], 20, "455a14ed");
    GG ($A, $B, $C, $D, $words[13 + ($i * 16)], 5, "a9e3e905");
    GG ($D, $A, $B, $C, $words[2 + ($i * 16)], 9, "fcefa3f8");
    GG ($C, $D, $A, $B, $words[7 + ($i * 16)], 14, "676f02d9");
    GG ($B, $C, $D, $A, $words[12 + ($i * 16)], 20, "8d2a4c8a");

    /* ROUND 3 */
    HH ($A, $B, $C, $D, $words[5 + ($i * 16)], 4, "fffa3942");
    HH ($D, $A, $B, $C, $words[8 + ($i * 16)], 11, "8771f681");
    HH ($C, $D, $A, $B, $words[11 + ($i * 16)], 16, "6d9d6122");
    HH ($B, $C, $D, $A, $words[14 + ($i * 16)], 23, "fde5380c");
    HH ($A, $B, $C, $D, $words[1 + ($i * 16)], 4, "a4beea44");
    HH ($D, $A, $B, $C, $words[4 + ($i * 16)], 11, "4bdecfa9");
    HH ($C, $D, $A, $B, $words[7 + ($i * 16)], 16, "f6bb4b60");
    HH ($B, $C, $D, $A, $words[10 + ($i * 16)], 23, "bebfbc70");
    HH ($A, $B, $C, $D, $words[13 + ($i * 16)], 4, "289b7ec6");
    HH ($D, $A, $B, $C, $words[0 + ($i * 16)], 11, "eaa127fa");
    HH ($C, $D, $A, $B, $words[3 + ($i * 16)], 16, "d4ef3085");
    HH ($B, $C, $D, $A, $words[6 + ($i * 16)], 23, "04881d05");
    HH ($A, $B, $C, $D, $words[9 + ($i * 16)], 4, "d9d4d039");
    HH ($D, $A, $B, $C, $words[12 + ($i * 16)], 11, "e6db99e5");
    HH ($C, $D, $A, $B, $words[15 + ($i * 16)], 16, "1fa27cf8");
    HH ($B, $C, $D, $A, $words[2 + ($i * 16)], 23, "c4ac5665");

    /* ROUND 4 */
    II ($A, $B, $C, $D, $words[0 + ($i * 16)], 6, "f4292244");
    II ($D, $A, $B, $C, $words[7 + ($i * 16)], 10, "432aff97");
    II ($C, $D, $A, $B, $words[14 + ($i * 16)], 15, "ab9423a7");
    II ($B, $C, $D, $A, $words[5 + ($i * 16)], 21, "fc93a039");
    II ($A, $B, $C, $D, $words[12 + ($i * 16)], 6, "655b59c3");
    II ($D, $A, $B, $C, $words[3 + ($i * 16)], 10, "8f0ccc92");
    II ($C, $D, $A, $B, $words[10 + ($i * 16)], 15, "ffeff47d");
    II ($B, $C, $D, $A, $words[1 + ($i * 16)], 21, "85845dd1");
    II ($A, $B, $C, $D, $words[8 + ($i * 16)], 6, "6fa87e4f");
    II ($D, $A, $B, $C, $words[15 + ($i * 16)], 10, "fe2ce6e0");
    II ($C, $D, $A, $B, $words[6 + ($i * 16)], 15, "a3014314");
    II ($B, $C, $D, $A, $words[13 + ($i * 16)], 21, "4e0811a1");
    II ($A, $B, $C, $D, $words[4 + ($i * 16)], 6, "f7537e82");
    II ($D, $A, $B, $C, $words[11 + ($i * 16)], 10, "bd3af235");
    II ($C, $D, $A, $B, $words[2 + ($i * 16)], 15, "2ad7d2bb");
    II ($B, $C, $D, $A, $words[9 + ($i * 16)], 21, "eb86d391");

    addVars($a, $b, $c, $d, $A, $B, $C, $D);
}
    $MD5 = $a.$b.$c.$d;
    return $MD5;
}

/* General functions */

function hexbin($str){
    $hexbinmap = array("0" => "0000"
                     , "1" => "0001"
                     , "2" => "0010"
                     , "3" => "0011"
                     , "4" => "0100"
                     , "5" => "0101"
                     , "6" => "0110"
                     , "7" => "0111"
                     , "8" => "1000"
                     , "9" => "1001"
                     , "A" => "1010"
                     , "a" => "1010"
                     , "B" => "1011"
                     , "b" => "1011"
                     , "C" => "1100"
                     , "c" => "1100"
                     , "D" => "1101"
                     , "d" => "1101"
                     , "E" => "1110"
                     , "e" => "1110"
                     , "F" => "1111"
                     , "f" => "1111");
    $bin = "";
    for ($i = 0; $i < strlen($str); $i++)
    {
        $bin .= $hexbinmap[$str[$i]];
    }
    $bin = ltrim($bin, '0');
    // echo "Original: ".$str."  New: ".$bin."
";
    return $bin;
}

function strhex($str){
    $hex = "";
    for ($i = 0; $i < strlen($str); $i++)
    {
        $hex = $hex.dechex(ord($str[$i]));
    }
    return $hex;
}

/* MD5-specific functions */

function init($string){
    $len = strlen($string);
    $hex = strhex($string); // convert ascii string to hex
    $bin = hexbin($hex); // convert hex string to bin
    $padded = pad($bin);
    $padded = pad($padded, 1, $len);
    $block = str_split($padded, 32);
    return $block;
}

function pad($bin, $type=0, $len = 0){
    if($type == 0){
        $bin = $bin."1";
        $buff = strlen($bin) % 512;
        if($buff != 448){
            while(strlen($bin) % 512 != 448){
                $bin = $bin."0";
            }
        }
    }
    // append length (b) of string to latter 64 bits
    elseif($type == 1){
        $bLen = decbin($len);
        if(strlen($bLen) > 64){
            $words = truncate64($bLen);
            $bin .= $words[1].$words[0];
        }
        else{
            while(strlen($bLen) < 64){
                $bLen .= "0";
            }
            $words = str_split ($bLen, 32);
            $bin .= $words[1].$words[0];
        }

    }
    return $bin;
}

function truncate64($string){
    $trunc = substr($string, strlen($string) - 64, 64);
    $trunc = str_split ($trunc, 32);
    return $trunc;
}

/* MD5 base functions */

function F($X, $Y, $Z){
    $X = hexbin($X);
    $Y = hexbin($Y);
    $Z = hexbin($Z);
    $calc = ($X & $Y) | ((~ $X) & $Z); // X AND Y OR NOT X AND Z
    $calc = bindec($calc);
    return  $calc;
}

function G($X, $Y, $Z){
    $X = hexbin($X);
    $Y = hexbin($Y);
    $Z = hexbin($Z);
    $calc = ($X & $Z) | ($Y & (~ $Z)) ; // X AND Z OR Y AND NOT Z
    $calc = bindec($calc);
    return  $calc;
}

function H($X, $Y, $Z){
    $X = hexbin($X);
    $Y = hexbin($Y);
    $Z = hexbin($Z);
    $calc = $X ^ $Y ^ $Z; // X XOR Y XOR Z
    $calc = bindec($calc);
    return  $calc;
}

function I($X, $Y, $Z){
    $X = hexbin($X);
    $Y = hexbin($Y);
    $Z = hexbin($Z);
    $calc = $Y ^ ($X | (~ $Z)) ; // Y XOR (X OR NOT Z)
    $calc = bindec($calc);
    return  $calc;
}

/* MD5 round functions */

/*
$A - hex, $B - hex, $C - hex, $D - hex (F - dec)
$M - binary
$s - decimal
$t - hex
*/
function FF(&$A, $B, $C, $D, $M, $s, $t){
    $A = hexdec($A);
    $t = hexdec($t);
    $M = bindec($M);
    $A = hexdec($B) + (($A + F($B, $C, $D) + $M + $t)); //decimal
    $A = rotate($A, $s);
}

function GG(&$A, $B, $C, $D, $M, $s, $t){
    $A = hexdec($A);
    $t = hexdec($t);
    $M = bindec($M);
    $A = hexdec($B) + (($A + G($B, $C, $D) + $M + $t)); //decimal
    $A = rotate($A, $s);
}

function HH(&$A, $B, $C, $D, $M, $s, $t){
    $A = hexdec($A);
    $t = hexdec($t);
    $M = bindec($M);
    $A = hexdec($B) + (($A + H($B, $C, $D) + $M + $t)); //decimal
    $A = rotate($A, $s);
}

function II(&$A, $B, $C, $D, $M, $s, $t){
    $A = hexdec($A);
    $t = hexdec($t);
    $M = bindec($M);
    $A = hexdec($B) + (($A + I($B, $C, $D) + $M + $t)); //decimal
    $A = rotate($A, $s);
}

// shift
function rotate($decimal, $bits) { //returns hex
  $binary = decbin($decimal);
  $shifted = substr($binary, $bits).substr($binary, 0, $bits);
  $hexshift = base_convert($shifted, 2, 16);
  return $hexshift;
}

function addVars(&$a, &$b, &$c, &$d, $A, $B, $C, $D){
    $A = hexdec($A);
    $B = hexdec($B);
    $C = hexdec($C);
    $D = hexdec($D);
    $aa = hexdec($a);
    $bb = hexdec($b);
    $cc = hexdec($c);
    $dd = hexdec($d);

    $aa = $aa + $A;
    $bb = $bb + $A;
    $cc = $cc + $A;
    $dd = $dd + $A;

    $a = dechex($aa);
    $b = dechex($bb);
    $c = dechex($cc);
    $d = dechex($dd);
}

?>

Body:
here my version, simplifying the main iteration

function MD($string)
    {
    $A = $a = "67452301";
    $B = $b = "efcdab89";
    $C = $c = "98badcfe";
    $D = $d = "10325476";

    $words = str2blks_MD5($string);

    $torot=array("A","B","C","D");
    $it=array(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21);
    $funcs=array("F","G","H","I");

    $moduls=array(0,1,1,5,5,3,0,7);

    $acs=array(     "d76aa478","e8c7b756","242070db","c1bdceee",
                    "f57c0faf","4787c62a","a8304613","fd469501",
                    "698098d8","8b44f7af","ffff5bb1","895cd7be",
                    "6b901122","fd987193","a679438e","49b40821",

                    "f61e2562","c040b340","265e5a51","e9b6c7aa",
                    "d62f105d","2441453","d8a1e681","e7d3fbc8",
                    "21e1cde6","c33707d6","f4d50d87","455a14ed",
                    "a9e3e905","fcefa3f8","676f02d9","8d2a4c8a",

                    "fffa3942","8771f681","6d9d6122","fde5380c",
                    "a4beea44","4bdecfa9","f6bb4b60","bebfbc70",
                    "289b7ec6","eaa127fa","d4ef3085","4881d05",
                    "d9d4d039","e6db99e5","1fa27cf8","c4ac5665",

                    "f4292244","432aff97","ab9423a7","fc93a039",
                    "655b59c3","8f0ccc92","ffeff47d","85845dd1",
                    "6fa87e4f","fe2ce6e0","a3014314","4e0811a1",
                    "f7537e82","bd3af235","2ad7d2bb","eb86d391");

    for($i = 0; $i < count($words)/16; $i++)
        {
            $a  = $A;
            $b  = $B;
            $c  = $C;
            $d  = $D;
            $n  = 0;

        for ($rot3=0;$rot3<4;$rot3++)
            {
            $minit=$moduls[$rot3*2];
        $madd=$moduls[$rot3*2+1];

            for ($rot2=0;$rot2<4;$rot2++)
                {
                for ($rot=0;$rot<4;$rot++)
                {
                $word=$words[$minit + ($i * 16)];
                $nit=$it[$rot+4*$rot3];

                FGHI (${"$torot[0]"}, ${"$torot[1]"}, ${"$torot[2]"}, ${"$torot[3]"}, $word, $nit, $acs[$n],$funcs[$rot3]);

                    array_unshift($torot,$torot[3]);
                    array_pop($torot);

                $minit=($minit+$madd)%16;
                ++$n;
                }
                 }
            }

            $A=AddUnsigned(hexdec2($A),hexdec2($a));
            $B=AddUnsigned(hexdec2($B),hexdec2($b));
            $C=AddUnsigned(hexdec2($C),hexdec2($c));
            $D=AddUnsigned(hexdec2($D),hexdec2($d));
            }
    return WordToHex($A).WordToHex($B).WordToHex($C).WordToHex($D);
    }
function WordToHex($lValue)
   {
    $WordToHexValue = "";
    for ($lCount = 0;$lCount<4;$lCount++)
        {
        $lByte = hexdec2($lValue)>>($lCount*8) & 255;
        $WordToHexValue.= sprintf("%02x",$lByte);
        }
    return $WordToHexValue;
    }
function FGHI(&$A, $B, $C, $D, $M, $s, $t, $func)
        {
        $Level1 = hexdec2(AddUnsigned(FGHI2($B, $C, $D, $func) , bindec($M) ));
        $level2 = hexdec2(AddUnsigned($Level1, hexdec2($t)));
        $A = hexdec2(AddUnsigned(hexdec2($A),$level2));
        $A = rotate($A, $s);
        $A = AddUnsigned($A , hexdec2($B)) ;
        }
function FGHI2($X, $Y, $Z,$func)
        {
        $X = hexdec2($X);
        $Y = hexdec2($Y);
        $Z = hexdec2($Z);

    switch ($func)
        {
        case "F":
                $calc = (($X & $Y) | ((~ $X) & $Z));break;
        case "G":
            $calc = (($X & $Z) | ($Y & (~ $Z)));break;
        case "H":
            $calc = ($X ^ $Y ^ $Z);break;
        case "I":
            $calc = ($Y ^ ($X | (~ $Z)));
        }
        return  $calc;
    }
function dectohex($res)
    {
        if($res < 0)
            return '-'.dechex(abs($res));
        return dechex($res);
    }

function hexdec2($hex)
    {
    if($hex[0] == "-")
        return doubleval('-'.hexdec(str_replace("-", "", $hex )));

    return hexdec($hex);
    }

function AddUnsigned($lX,$lY)
   {
    $lX8 = ($lX & 0x80000000);
    $lY8 = ($lY & 0x80000000);
    $lX4 = ($lX & 0x40000000);
    $lY4 = ($lY & 0x40000000);

    $lResult = ($lX & 0x3FFFFFFF)+($lY & 0x3FFFFFFF);

    $res=$lResult ^ $lX8 ^ $lY8;

    if ($lX4 & $lY4)                       return dectohex($res ^ 0x80000000);
    if ($lX4 | $lY4)
    {
        if ($lResult & 0x40000000)         return dectohex($res ^ 0xC0000000);
        else                               return dectohex($res ^ 0x40000000);
        }                                  return dectohex($res);
    }
function rotate ($decimal, $bits)
    {
    return  (($decimal << $bits) |  shiftright($decimal, (32 - $bits))  & 0xffffffff);
    }
function shiftright($decimal , $right)
    {
    $shift=$decimal >> $right;

    if($decimal >= 0) return $shift;
    return bindec(substr(decbin($shift),$right));
    }

function str2blks_MD5($str)
  {
  $nblk = ((strlen($str) + 8) >> 6) + 1;

  $blks = array($nblk * 16);

  for($i = 0; $i < $nblk * 16; $i++)
                $blks[$i] = 0;

  for($i = 0; $i < strlen($str); $i++)
            $blks[$i >> 2] |= ord($str[$i]) << (($i % 4) * 8);

  $blks[$i >> 2] |= 0x80 << (($i % 4) * 8);

  $blks[$nblk * 16 - 2] = strlen($str) * 8;

  for ($i=0; $i < $nblk * 16; $i++)
        $blks[$i] = decbin($blks[$i]);

  return $blks;
  }
$str='test';
echo md5($str); // 098f6bcd4621d373cade4e832627b4f6
echo'<br>';
echo MD($str); //  098f6bcd4621d373cade4e832627b4f6


来源: stackexchange

问:
legend ordering and factor ordering in ggplot2
I have produced the following code:

```<code>#library(tidyverse)
#library(ggplot2)
#library(forcats)

    temp<-tribble(
 ~kt, ~yes, ~'no', ~'NA',
 "Berne", 47,33, 0,
 "Basel", 60,45,0,
 "Geneva", 64,61,0,
 "Zurich", 19,107,3
)

temp2 <- gather(temp, ' ', val, -kt)
ggplot(temp2, aes(kt, val, fill = ` `)) +
  geom_col(position = 'fill', color='darkgrey') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+
  theme_bw()+
  labs(x='Jurisdiction', y='Percentage') +
  coord_flip()+ scale_fill_grey(start = 0.9, end = .5) +
  guides(fill=guide_legend(title="Witnesses heard"))
</code>```

Now I have the following difficulties and would appreciate it if someone could help me:

How can I change the ordering of the legend? The ordering should be just reversed (but the ordering of the barplot is fine).

Obviously the y-Axis (jurisdiction) seems to be ordered alphabetically, but I'd rather have this to be ordered manually (as in the tibble). Unfortunately I did not manage to get this fixed.

Thank you for any advices!

答:
Answering your two questions:

Add the argument reverse = T to your last line, changing it to: guides(fill = guide_legend(title = "Witnesses heard", reverse = T))

Since you already suggested forcats, you can use fct_relevel: temp2 <- temp2 %>% mutate(kt = fct_relevel(kt, "Berne")). Just specifying "Berne" will move it to the front. You could as well specify all levels, like fct_relevel(kt, "Berne", "Basel", "Geneva", "Zurich"), but this isn't necessary.

Full example

temp2 <- gather(temp, ' ', val, -kt) %>%
  mutate(kt = fct_relevel(kt, "Berne"))

# the following is just for convenience when plotting twice
layers <- list(
  geom_col(position = 'fill', color='darkgrey'),
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3),
  scale_y_continuous(labels = scales::percent_format()),
  theme_bw(),
  labs(x='Jurisdiction', y='Percentage'),
  coord_flip(),
  scale_fill_grey(start = 0.9, end = .5),
  guides(fill = guide_legend(title = "Witnesses heard", reverse = T))
)

ggplot(temp2, aes(kt, val, fill = ` `)) +
  layers
```

<p><img src="https://i.imgur.com/f4KwugW.png" alt=""></p>

<p>In addition, you could use <code>fct_rev</code> to reverse the placement on the y-axis:</p>

<pre class="lang-r prettyprint-override"><code>ggplot(temp2, aes(fct_rev(kt), val, fill = ` `)) +
  layers
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have produced the following code:

#library(tidyverse)
#library(ggplot2)
#library(forcats)

    temp<-tribble(
 ~kt, ~yes, ~'no', ~'NA',
 "Berne", 47,33, 0,
 "Basel", 60,45,0,
 "Geneva", 64,61,0,
 "Zurich", 19,107,3
)

temp2 <- gather(temp, ' ', val, -kt)
ggplot(temp2, aes(kt, val, fill = ` `)) +
  geom_col(position = 'fill', color='darkgrey') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+
  theme_bw()+
  labs(x='Jurisdiction', y='Percentage') +
  coord_flip()+ scale_fill_grey(start = 0.9, end = .5) +
  guides(fill=guide_legend(title="Witnesses heard"))

Now I have the following difficulties and would appreciate it if someone could help me:

How can I change the ordering of the legend? The ordering should be just reversed (but the ordering of the barplot is fine).

Obviously the y-Axis (jurisdiction) seems to be ordered alphabetically, but I'd rather have this to be ordered manually (as in the tibble). Unfortunately I did not manage to get this fixed.

Thank you for any advices!

Body:
Answering your two questions:

Add the argument reverse = T to your last line, changing it to: guides(fill = guide_legend(title = "Witnesses heard", reverse = T))

Since you already suggested forcats, you can use fct_relevel: temp2 <- temp2 %>% mutate(kt = fct_relevel(kt, "Berne")). Just specifying "Berne" will move it to the front. You could as well specify all levels, like fct_relevel(kt, "Berne", "Basel", "Geneva", "Zurich"), but this isn't necessary.

Full example

temp2 <- gather(temp, ' ', val, -kt) %>%
  mutate(kt = fct_relevel(kt, "Berne"))

# the following is just for convenience when plotting twice
layers <- list(
  geom_col(position = 'fill', color='darkgrey'),
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3),
  scale_y_continuous(labels = scales::percent_format()),
  theme_bw(),
  labs(x='Jurisdiction', y='Percentage'),
  coord_flip(),
  scale_fill_grey(start = 0.9, end = .5),
  guides(fill = guide_legend(title = "Witnesses heard", reverse = T))
)

ggplot(temp2, aes(kt, val, fill = ` `)) +
  layers

In addition, you could use fct_rev to reverse the placement on the y-axis:

ggplot(temp2, aes(fct_rev(kt), val, fill = ` `)) +
  layers


问:
Handling Back button in Parent Activity
I have my main activity which contains 2 fragments:

MainActivity

```<code>public class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            FragmentOne fragmentOne = new FragmentOne ();

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragmentOne ).commit();

        }

    }
</code>```

This activity initially display fragment one.

Fragment one has a button which listens and when clicked it will replace itself with fragment two. When the button is clicked the interface in fragment one gets

```<code>//Main acitivty has this method which is a a method the interface in fragment one requires
@Override
    public void goToFragmentTwo() {

        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //  setSupportActionBar(toolbar);

        // Create fragment and give it an argument specifying the article it should show
         FragmentTwo fragmentTwo = new FragmentTwo ();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, fragmentTwo );
        transaction.addToBackStack(FragmentTwo.BACKSTACK_TAG);

        // Commit the transaction
        transaction.commit();
    }
</code>```

If the android back button or the back button in the toolbar gets called the fragments need to have a confirm dialog which asks are you sure you want to leave. If Ok then I have a second activity called the HomeActivity (this activity is the parent activity of MainActivity) which it needs to go to, or if cancel it needs to just close the dialog and stay in the current fragment.

So in the MainActivity I have overrode the onBackPressed method which displays a :

@Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

```<code>    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
                finish();
        }
    });
    builder.show();
}
</code>```

I am experiencing two problems with this code:

1) Pressing the back button in the toolbar doesn't display a dialog
2) The dialog's OK and Cancel features are not working correctly.

Essentially what I am trying to accomplish is I have a HomeActivity which has a button to navigate to the MainActivity. When the MainActivity gets called I will start a workflow where each fragment is a section of that workflow. If the back button is pressed this workflow needs to be discarded and the user should be returned back to the HomeActivty.

答:
1) You should make your toolbar back button call onBackPressed() from your activity, so they both share the same functionality.

See onSupportNavegationUp() in the main activity.

2) Have your Main Activity control what happens with the fragment, but let the fragments handle any back press if they must.

I hope this is of use to you.

Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.johnurrutia.so_43172788">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.johnurrutia.so_43172788.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="0dp"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

    </android.support.v7.widget.Toolbar>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/toolBar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        tools:layout_editor_absoluteY="8dp">

    </FrameLayout>

</android.support.constraint.ConstraintLayout>
</code>```

fragment_one.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnGoFrag2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go To Fragment TWO" />
</LinearLayout>
</code>```

fragment_two.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/goToFragmentOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Go To Fragment One" />
</LinearLayout>
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity
        implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener {

    public static final int FRAGMENT_ONE = 0;
    public static final int FRAGMENT_TWO = 1;

    private Toolbar toolbar;
    private FragmentOne fragmentOne;
    private FragmentTwo fragmentTwo;

    private ArrayList<Fragment> fragments = new ArrayList<>();
    private int currentFragment = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            fragmentOne = new FragmentOne();
            fragmentTwo = new FragmentTwo();
            fragments.add(FRAGMENT_ONE, fragmentOne);
            fragments.add(FRAGMENT_TWO, fragmentTwo);

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragmentOne,"FRAGMENT_ONE")
                    .add(R.id.fragment_container, fragmentTwo, "FRAGMENT_TWO")
                    .hide(fragmentTwo)
                    .show(fragmentOne)
                    .commit();
        }

    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    public void onBackPressed() {
        boolean fragmentProcessedTheEvent = ( (BackButtonListener) fragments.get(currentFragment)).onBackPressed();
        if(!fragmentProcessedTheEvent) {
            //The event is for Main Activity to exit
            showActivityExitDialog();
        }
    }

    public void showActivityExitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Do you want to leave? ");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                finish();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void switchToFragment(int pos) {
        if (currentFragment != pos) {
            getSupportFragmentManager().beginTransaction()
                    .hide(fragments.get(currentFragment))
                    .show(fragments.get(pos))
                    .commit();
            currentFragment = pos;
        }
    }

    public void goToFragmentTwo(){
        switchToFragment(FRAGMENT_TWO);
    }

    public void goToFragmentOne(){
        switchToFragment(FRAGMENT_ONE);
    }
}
</code>```

FragmentOne.java

```<code>public class FragmentOne extends Fragment implements BackButtonListener{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_one, container, false);

        Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.btnGoFrag2);
        goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ( (OnFragmentOneInteractionListener) getActivity() ).goToFragmentTwo();
            }
        });

        return v;
    }

    public interface OnFragmentOneInteractionListener{
        public void goToFragmentTwo();
    }

    @Override
    public boolean onBackPressed() {
        /*
        *  if(fragment_has_any_use_for_back_press){
        *      process_it_here();
        *      return EVENT_PROCESSED;
        *  }
        *
        * */

        return EVENT_IGNORED;
    }
}
</code>```

FragmentTwo.java

```<code>public class FragmentTwo extends Fragment implements BackButtonListener{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_two, container, false);

        Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.goToFragmentOne);
        goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ( (FragmentTwo.OnFragmentTwoInteractionListener) getActivity() ).goToFragmentOne();
            }
        });

        return v;
    }

    @Override
    public boolean onBackPressed() {
        /*
        *  if(fragment_has_any_use_for_back_press){
        *      process_it_here();
        *      return EVENT_PROCESSED;
        *  }
        *
        * */

        return EVENT_IGNORED;
    }

    public interface OnFragmentTwoInteractionListener{
        public void goToFragmentOne();
    }
}
</code>```

BackButtonListener.java

```<code>public interface BackButtonListener {
    public static final boolean EVENT_PROCESSED = true;
    public static final boolean EVENT_IGNORED = false;
    public boolean onBackPressed();
}
</code>```

Title: Handling Back button in Parent Activity

Body:
I have my main activity which contains 2 fragments:

MainActivity

public class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            FragmentOne fragmentOne = new FragmentOne ();

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragmentOne ).commit();

        }

    }

This activity initially display fragment one.

Fragment one has a button which listens and when clicked it will replace itself with fragment two. When the button is clicked the interface in fragment one gets

//Main acitivty has this method which is a a method the interface in fragment one requires
@Override
    public void goToFragmentTwo() {

        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //  setSupportActionBar(toolbar);

        // Create fragment and give it an argument specifying the article it should show
         FragmentTwo fragmentTwo = new FragmentTwo ();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, fragmentTwo );
        transaction.addToBackStack(FragmentTwo.BACKSTACK_TAG);

        // Commit the transaction
        transaction.commit();
    }

If the android back button or the back button in the toolbar gets called the fragments need to have a confirm dialog which asks are you sure you want to leave. If Ok then I have a second activity called the HomeActivity (this activity is the parent activity of MainActivity) which it needs to go to, or if cancel it needs to just close the dialog and stay in the current fragment.

So in the MainActivity I have overrode the onBackPressed method which displays a :

@Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
                finish();
        }
    });
    builder.show();
}

I am experiencing two problems with this code:

1) Pressing the back button in the toolbar doesn't display a dialog
2) The dialog's OK and Cancel features are not working correctly.

Essentially what I am trying to accomplish is I have a HomeActivity which has a button to navigate to the MainActivity. When the MainActivity gets called I will start a workflow where each fragment is a section of that workflow. If the back button is pressed this workflow needs to be discarded and the user should be returned back to the HomeActivty.

Body:
1) You should make your toolbar back button call onBackPressed() from your activity, so they both share the same functionality.

See onSupportNavegationUp() in the main activity.

2) Have your Main Activity control what happens with the fragment, but let the fragments handle any back press if they must.

I hope this is of use to you.

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.johnurrutia.so_43172788">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.johnurrutia.so_43172788.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="0dp"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

    </android.support.v7.widget.Toolbar>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/toolBar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        tools:layout_editor_absoluteY="8dp">

    </FrameLayout>

</android.support.constraint.ConstraintLayout>

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnGoFrag2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go To Fragment TWO" />
</LinearLayout>

fragment_two.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/goToFragmentOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Go To Fragment One" />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener {

    public static final int FRAGMENT_ONE = 0;
    public static final int FRAGMENT_TWO = 1;

    private Toolbar toolbar;
    private FragmentOne fragmentOne;
    private FragmentTwo fragmentTwo;

    private ArrayList<Fragment> fragments = new ArrayList<>();
    private int currentFragment = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            fragmentOne = new FragmentOne();
            fragmentTwo = new FragmentTwo();
            fragments.add(FRAGMENT_ONE, fragmentOne);
            fragments.add(FRAGMENT_TWO, fragmentTwo);

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragmentOne,"FRAGMENT_ONE")
                    .add(R.id.fragment_container, fragmentTwo, "FRAGMENT_TWO")
                    .hide(fragmentTwo)
                    .show(fragmentOne)
                    .commit();
        }

    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    public void onBackPressed() {
        boolean fragmentProcessedTheEvent = ( (BackButtonListener) fragments.get(currentFragment)).onBackPressed();
        if(!fragmentProcessedTheEvent) {
            //The event is for Main Activity to exit
            showActivityExitDialog();
        }
    }

    public void showActivityExitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Do you want to leave? ");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                finish();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void switchToFragment(int pos) {
        if (currentFragment != pos) {
            getSupportFragmentManager().beginTransaction()
                    .hide(fragments.get(currentFragment))
                    .show(fragments.get(pos))
                    .commit();
            currentFragment = pos;
        }
    }

    public void goToFragmentTwo(){
        switchToFragment(FRAGMENT_TWO);
    }

    public void goToFragmentOne(){
        switchToFragment(FRAGMENT_ONE);
    }
}

FragmentOne.java

public class FragmentOne extends Fragment implements BackButtonListener{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_one, container, false);

        Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.btnGoFrag2);
        goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ( (OnFragmentOneInteractionListener) getActivity() ).goToFragmentTwo();
            }
        });

        return v;
    }

    public interface OnFragmentOneInteractionListener{
        public void goToFragmentTwo();
    }

    @Override
    public boolean onBackPressed() {
        /*
        *  if(fragment_has_any_use_for_back_press){
        *      process_it_here();
        *      return EVENT_PROCESSED;
        *  }
        *
        * */

        return EVENT_IGNORED;
    }
}

FragmentTwo.java

public class FragmentTwo extends Fragment implements BackButtonListener{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_two, container, false);

        Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.goToFragmentOne);
        goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ( (FragmentTwo.OnFragmentTwoInteractionListener) getActivity() ).goToFragmentOne();
            }
        });

        return v;
    }

    @Override
    public boolean onBackPressed() {
        /*
        *  if(fragment_has_any_use_for_back_press){
        *      process_it_here();
        *      return EVENT_PROCESSED;
        *  }
        *
        * */

        return EVENT_IGNORED;
    }

    public interface OnFragmentTwoInteractionListener{
        public void goToFragmentOne();
    }
}

BackButtonListener.java

public interface BackButtonListener {
    public static final boolean EVENT_PROCESSED = true;
    public static final boolean EVENT_IGNORED = false;
    public boolean onBackPressed();
}


问:
How to declare a variable in a template in Angular
I have the following template :

```<code><div>
  <span>{{aVariable}}</span>
</div>
</code>```

and would like to end up with :

```<code><div "let a = aVariable">
  <span>{{a}}</span>
</div>
</code>```

Is there a way to do it ?

答:
Update

We can just create directive like *ngIf and call it *ngVar

your answer was very handy, but here I've adapted it for typing to work too

ng-var.directive.ts

```<code>import {
  Directive,
  EmbeddedViewRef,
  Input,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';

@Directive({
  selector: '[ngVar]',
})
export class NgVar<T = unknown> {
  private _context: NgVarContext<T> = new NgVarContext<T>();
  private _viewRef: EmbeddedViewRef<NgVarContext<T>> | null = null;

  @Input()
  set ngVar(context: T) {
    this._context.$implicit = this._context.ngVar = context;

    if (!this._viewRef) {
      this._viewRef = this._viewContainer.createEmbeddedView(
        this._templateRef,
        this._context
      );
    }
  }

  // https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_if.ts

  /**
   * Assert the correct type of the expression bound to the `ngIf` input within the template.
   *
   * The presence of this static field is a signal to the Ivy template type check compiler that
   * when the `NgIf` structural directive renders its template, the type of the expression bound
   * to `ngIf` should be narrowed in some way. For `NgIf`, the binding expression itself is used to
   * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgIf`.
   */

  static ngTemplateGuard_ngVar: 'binding';

  /**
   * Asserts the correct type of the context for the template that `NgIf` will render.
   *
   * The presence of this method is a signal to the Ivy template type-check compiler that the
   * `NgIf` structural directive renders its template with a specific context type.
   */

  // Passing down variable Type
  static ngTemplateContextGuard<T>(
    dir: NgVar<T>,
    ctx: any
  ): ctx is NgVarContext<T> {
    return true;
  }

  constructor(
    private _viewContainer: ViewContainerRef,
    private _templateRef: TemplateRef<NgVarContext<T>>
  ) {}
}

export class NgVarContext<T = unknown> {
  public $implicit: T = null!;
  public ngVar: T = null!;
}
</code>```

with this *ngVar directive we can use the following

```<code><div *ngVar="false as variable">
      <span>{{variable | json}}</span>
</div>
</code>```

or

```<code><div *ngVar="false; let variable">
    <span>{{variable | json}}</span>
</div>
</code>```

or

```<code><div *ngVar="45 as variable">
    <span>{{variable | json}}</span>
</div>
</code>```

or

```<code><div *ngVar="{ x: 4 } as variable">
    <span>{{variable | json}}</span>
</div>
</code>```

Plunker Example Angular4 ngVar

See also

Where does Angular define "as local-var" behavior for *ngIf?

Original answer

Angular v4

div + ngIf + let

   {{variable.a}}
   {{variable.b}}

div + ngIf + as

view

```<code><div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</div>
</code>```

component.ts

```<code>export class AppComponent {
  x = 5;
}
</code>```

If you don't want to create wrapper like div you can use ng-container

view

```<code><ng-container *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</ng-container>
</code>```

As @Keith mentioned in comments

this will work in most cases but it is not a general solution since it
relies on variable being truthy

See update for another approach.

ContentLicense: CC BY-SA 4.0

Body:
I have the following template :

  {{aVariable}}

and would like to end up with :

  {{a}}

Is there a way to do it ?

Body:
Update

We can just create directive like *ngIf and call it *ngVar

your answer was very handy, but here I've adapted it for typing to work too

ng-var.directive.ts

import {
  Directive,
  EmbeddedViewRef,
  Input,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';

@Directive({
  selector: '[ngVar]',
})
export class NgVar<T = unknown> {
  private _context: NgVarContext<T> = new NgVarContext<T>();
  private _viewRef: EmbeddedViewRef<NgVarContext<T>> | null = null;

  @Input()
  set ngVar(context: T) {
    this._context.$implicit = this._context.ngVar = context;

    if (!this._viewRef) {
      this._viewRef = this._viewContainer.createEmbeddedView(
        this._templateRef,
        this._context
      );
    }
  }

  // https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_if.ts

  /**
   * Assert the correct type of the expression bound to the `ngIf` input within the template.
   *
   * The presence of this static field is a signal to the Ivy template type check compiler that
   * when the `NgIf` structural directive renders its template, the type of the expression bound
   * to `ngIf` should be narrowed in some way. For `NgIf`, the binding expression itself is used to
   * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgIf`.
   */

  static ngTemplateGuard_ngVar: 'binding';

  /**
   * Asserts the correct type of the context for the template that `NgIf` will render.
   *
   * The presence of this method is a signal to the Ivy template type-check compiler that the
   * `NgIf` structural directive renders its template with a specific context type.
   */

  // Passing down variable Type
  static ngTemplateContextGuard<T>(
    dir: NgVar<T>,
    ctx: any
  ): ctx is NgVarContext<T> {
    return true;
  }

  constructor(
    private _viewContainer: ViewContainerRef,
    private _templateRef: TemplateRef<NgVarContext<T>>
  ) {}
}

export class NgVarContext<T = unknown> {
  public $implicit: T = null!;
  public ngVar: T = null!;
}

with this *ngVar directive we can use the following

<div *ngVar="false as variable">
      <span>{{variable | json}}</span>
</div>

or

<div *ngVar="false; let variable">
    <span>{{variable | json}}</span>
</div>

or

<div *ngVar="45 as variable">
    <span>{{variable | json}}</span>
</div>

or

<div *ngVar="{ x: 4 } as variable">
    <span>{{variable | json}}</span>
</div>

Plunker Example Angular4 ngVar

See also

Where does Angular define "as local-var" behavior for *ngIf?

Original answer

Angular v4

div + ngIf + let

   {{variable.a}}
   {{variable.b}}

div + ngIf + as

view

<div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</div>

component.ts

export class AppComponent {
  x = 5;
}

If you don't want to create wrapper like div you can use ng-container

view

<ng-container *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</ng-container>

As @Keith mentioned in comments

this will work in most cases but it is not a general solution since it
relies on variable being truthy

See update for another approach.


问:
I need to return a new set that contains the elements of a and b in a union
I need to return a new set that contains the elements of a and b in a union

```<code>public static Set<Integer> union(Set<Integer> a, Set<Integer> b) {

    List<Integer> c = new ArrayList<Integer>(a.size() + b.size());

    private void add(List<Integer> toAddTo,List<Integer> iterateOver) {
        for(Integer num:iterateOver){
            if(toAddTo.indexOf(num) == -1) {
                toAddTo.add(num);
            }
        }
    }
</code>```

This is my attempt, Im not sure what to do from here

答:
Do not work on lists, if you need sets.

Do not modify input parameters... (another tip).

```<code>public static Set<Integer> union(Set<Integer> a, Set<Integer> b) {
    Set<Integer> toReturn = new HashSet<>(a.size() + b.size());
    toReturn.addAll(a);
    toReturn.addAll(b);
    return toReturn;
}
</code>```

Body:
I need to return a new set that contains the elements of a and b in a union

public static Set<Integer> union(Set<Integer> a, Set<Integer> b) {

    List<Integer> c = new ArrayList<Integer>(a.size() + b.size());

    private void add(List<Integer> toAddTo,List<Integer> iterateOver) {
        for(Integer num:iterateOver){
            if(toAddTo.indexOf(num) == -1) {
                toAddTo.add(num);
            }
        }
    }

This is my attempt, Im not sure what to do from here

Body:
Do not work on lists, if you need sets.

Do not modify input parameters... (another tip).

public static Set<Integer> union(Set<Integer> a, Set<Integer> b) {
    Set<Integer> toReturn = new HashSet<>(a.size() + b.size());
    toReturn.addAll(a);
    toReturn.addAll(b);
    return toReturn;
}


问:
datePickerDialog spinner instead od calendar java programatically api 24
I want to display datePicker as dialog after user click a button. I followed this tutorial : https://developer.android.com/guide/topics/ui/controls/pickers.html and it works fina but I get displayed calendar instead of spinner. I tried a lot of things e.g.
1) set theme the has mode spinner,
2) There was an api :

```<code>    DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
    dialog.getDatePicker().setCalendarViewShown(false)
    dialog.getDatePicker().setSpinnerShown(true)
</code>```

but those method are deprecated and has no effect.

The only thing that worked is that I decompiled DatePicker and there was a code :

```<code>   private static final int MODE_SPINNER = 1;
   private static final int MODE_CALENDAR = 2;

    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DatePicker,
            defStyleAttr, defStyleRes);
    final int mode = a.getInt(R.styleable.DatePicker_datePickerMode, MODE_SPINNER);
    final int firstDayOfWeek = a.getInt(R.styleable.DatePicker_firstDayOfWeek, 0);
    a.recycle();

    switch (mode) {
        case MODE_CALENDAR:
            mDelegate = createCalendarUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
        case MODE_SPINNER:
        default:
            mDelegate = createSpinnerUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
    }
</code>```

if I changed "mode" in debug mode to value = "1" spinner appeared. But how can I set this value ? How to set style R.styleable.DatePicker_datePickerMode to 1 ?

Additionally R is some kind internal - don't know what it is:

```<code>    import com.android.internal.R;
</code>```

答:
In this API it is an error.
I found a workaround https://gist.github.com/jeffdgr8/6bc5f990bf0c13a7334ce385d482af9f </p>

Body:
I want to display datePicker as dialog after user click a button. I followed this tutorial : https://developer.android.com/guide/topics/ui/controls/pickers.html and it works fina but I get displayed calendar instead of spinner. I tried a lot of things e.g.
1) set theme the has mode spinner,
2) There was an api :

    DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
    dialog.getDatePicker().setCalendarViewShown(false)
    dialog.getDatePicker().setSpinnerShown(true)

but those method are deprecated and has no effect.

The only thing that worked is that I decompiled DatePicker and there was a code :

   private static final int MODE_SPINNER = 1;
   private static final int MODE_CALENDAR = 2;

    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DatePicker,
            defStyleAttr, defStyleRes);
    final int mode = a.getInt(R.styleable.DatePicker_datePickerMode, MODE_SPINNER);
    final int firstDayOfWeek = a.getInt(R.styleable.DatePicker_firstDayOfWeek, 0);
    a.recycle();

    switch (mode) {
        case MODE_CALENDAR:
            mDelegate = createCalendarUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
        case MODE_SPINNER:
        default:
            mDelegate = createSpinnerUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
    }

if I changed "mode" in debug mode to value = "1" spinner appeared. But how can I set this value ? How to set style R.styleable.DatePicker_datePickerMode to 1 ?

Additionally R is some kind internal - don't know what it is:

    import com.android.internal.R;


问:
How to filter RDD relying on hash map?
I'm new to using spark and scala but I have to solve the following problem:
I have one ORC file containing rows which I have to check against a certain condition comming from a hash map.

I build the hash map (filename,timestamp) with 120,000 entries this way (getTimestamp returns an Option[Long] type):

```<code>val tgzFilesRDD = sc.textFile("...")
val fileNameTimestampRDD = tgzFilesRDD.map(itr => {
    (itr, getTimestamp(itr))
})
val fileNameTimestamp = fileNameTimestampRDD.collect.toMap
</code>```

And retrieve the RDD with 6 million entries like this:

```<code>val sessionDataDF = sqlContext.read.orc("...")
case class SessionEvent(archiveName: String, eventTimestamp: Long)
val sessionEventsRDD = sessionDataDF.as[SessionEvent].rdd
</code>```

And do the check:

```<code>val sessionEventsToReport = sessionEventsRDD.filter(se => {
    val timestampFromFile = fileNameTimestamp.getOrElse(se.archiveName, None)
    se.eventTimestamp < timestampFromFile.getOrElse[Long](Long.MaxValue)
})
</code>```

Is this the right and performant way to do it? Is there a caching recommended?
Will the Map fileNameTimestamp get shuffled to the clusters where the parititons where processed?

答:
fileNameTimestamp will get serialized for each task, and with 120,000 entries, it may be quite expensive.  You should broadcast large objects and reference the broadcast variables:

```<code>val fileNameTimestampBC = sc.broadcast(fileNameTimestampRDD.collect.toMap)
</code>```

Now only one of these object will be shipped to each worker.  There is also no need to drop down to the RDD API, as the Dataset API has a filter method:

```<code>val sessionEvents = sessionDataDF.as[SessionEvent]
val sessionEventsToReport = sessionEvents.filter(se => {
    val timestampFromFile = fileNameTimestampBC.value.getOrElse(se.archiveName, None)
    se.eventTimestamp < timestampFromFile.getOrElse[Long](Long.MaxValue)
})
</code>```

Title: How to filter RDD relying on hash map?

Body:
I'm new to using spark and scala but I have to solve the following problem:
I have one ORC file containing rows which I have to check against a certain condition comming from a hash map.

I build the hash map (filename,timestamp) with 120,000 entries this way (getTimestamp returns an Option[Long] type):

val tgzFilesRDD = sc.textFile("...")
val fileNameTimestampRDD = tgzFilesRDD.map(itr => {
    (itr, getTimestamp(itr))
})
val fileNameTimestamp = fileNameTimestampRDD.collect.toMap

And retrieve the RDD with 6 million entries like this:

val sessionDataDF = sqlContext.read.orc("...")
case class SessionEvent(archiveName: String, eventTimestamp: Long)
val sessionEventsRDD = sessionDataDF.as[SessionEvent].rdd

And do the check:

val sessionEventsToReport = sessionEventsRDD.filter(se => {
    val timestampFromFile = fileNameTimestamp.getOrElse(se.archiveName, None)
    se.eventTimestamp < timestampFromFile.getOrElse[Long](Long.MaxValue)
})

Is this the right and performant way to do it? Is there a caching recommended?
Will the Map fileNameTimestamp get shuffled to the clusters where the parititons where processed?

Body:
fileNameTimestamp will get serialized for each task, and with 120,000 entries, it may be quite expensive.  You should broadcast large objects and reference the broadcast variables:

val fileNameTimestampBC = sc.broadcast(fileNameTimestampRDD.collect.toMap)

Now only one of these object will be shipped to each worker.  There is also no need to drop down to the RDD API, as the Dataset API has a filter method:

val sessionEvents = sessionDataDF.as[SessionEvent]
val sessionEventsToReport = sessionEvents.filter(se => {
    val timestampFromFile = fileNameTimestampBC.value.getOrElse(se.archiveName, None)
    se.eventTimestamp < timestampFromFile.getOrElse[Long](Long.MaxValue)
})


问:
Windows 7 on a virtual machine
I know this question isn't "directly" programming related, but since I want to be able to be well-prepared on windows-programming when Windows 7 is released, I want to try it out now. But since I don't have two computers, I can't risk to install it as dual-boot in case it screws something up, my experience with dual-booting XP and Vista isn't the best, so dual-boot in a pre-beta-world is even more scary ;)

Anyway, my question is this: Does there exist any Virtualization-programs that handles Windows 7 now? And if there is several, which one is best? I don't really need any detailed descriptions on how to install it and such, that I have google for ;) And the install-DVD is in my hands as we speak, so that isn't a problem either.

答:
I'm using VMware Workstation (6.5.1) with the default "Windows Vista" settings.

Works great. Even the NIC works, despite of a few error reports found in google.

Edit: I installed the current beta of Windows 7 (Build 7000)

OwnerDisplayName: Espenhh

Title: Windows 7 on a virtual machine

LastEditorDisplayName: CesarB

ContentLicense: CC BY-SA 2.5


问:
If an R package's licence X is, do all the content in that package have to be licenced under X?
Hope the question above is clear.

Now my case: For my package, i'm using several libraries (jars). Each library has been licenced under one of these:  Apache v2, BSD or LPGL.

Edit [some clarification] I have my own java classes packed in a jar. These import classes (dynamic linking) from the libraries mentioned here [End Edit]

Question 1: Can i pack all these libraries in a single package?

Question 1a: If yes, under what licence Apache, BSD, LGPL or any other?

Question 1b: If yes, would it be enough to put all the library names in a NOTICE and to write under what licence is a library licenced together?

Question 2: Or do i have to create for each type of licence a separate package and put libraries in it according to their licence type?

答: You can't use a single license for your package.  Instead, in your DESCRIPTION put "License: file LICENSE" and describe the individual licenses in that file.


问:
Trying to sort a column from user input
So I'm trying to find the min and max from a particular column in a set of files and then putting those values in two text files. The column that I want my script to sort though is the number inputted from the user. This is my code and it works for the most part except it's giving me the min and max for each column. How do I fix this?

```<code>echo "Please enter a column you wish to change: "
read userinput
if [ ${userinput} -gt 10 ]; then
      echo "Error"
else
      sort -nk${userinput} Node{1..4}.txt | awk 'NR==1{print $userinput}' > result.txt
      sort -nk${userinput} Node{1..4}.txt | awk 'END{print $userinput}' > results.txt
fi
</code>```

The ${userinput} in the sort part is supposed to be the column the user specified, so for example if the user put in "10" then it would be sort -nk10. The script works for the most part except it's giving me the min and max of all the columns when it checks through all four of my text files that I specified. How do I fix it so that it is only giving me the min and max of the column specified by the user?

答:
You can not read the value of a shell variable in awk. Uste the -v option for setting an awk variable.

```<code>userinput=4
# This will not work
awk 'BEGIN {print "UserInput=" $userinput}'
# This works
awk -v colnr=$userinput 'BEGIN {print "UserInput=" colnr }'
</code>```

You can use this like

```<code>echo "A B C D E F" | awk -v colnr=$userinput '{print "Col " colnr "=" $colnr }'
</code>```

Title: Trying to sort a column from user input

Body:
So I'm trying to find the min and max from a particular column in a set of files and then putting those values in two text files. The column that I want my script to sort though is the number inputted from the user. This is my code and it works for the most part except it's giving me the min and max for each column. How do I fix this?

echo "Please enter a column you wish to change: "
read userinput
if [ ${userinput} -gt 10 ]; then
      echo "Error"
else
      sort -nk${userinput} Node{1..4}.txt | awk 'NR==1{print $userinput}' > result.txt
      sort -nk${userinput} Node{1..4}.txt | awk 'END{print $userinput}' > results.txt
fi

The ${userinput} in the sort part is supposed to be the column the user specified, so for example if the user put in "10" then it would be sort -nk10. The script works for the most part except it's giving me the min and max of all the columns when it checks through all four of my text files that I specified. How do I fix it so that it is only giving me the min and max of the column specified by the user?

Body:
You can not read the value of a shell variable in awk. Uste the -v option for setting an awk variable.

userinput=4
# This will not work
awk 'BEGIN {print "UserInput=" $userinput}'
# This works
awk -v colnr=$userinput 'BEGIN {print "UserInput=" colnr }'

You can use this like

echo "A B C D E F" | awk -v colnr=$userinput '{print "Col " colnr "=" $colnr }'


问:
Uploading image MEAN stack
I realise there's quite a few resources online about this, but none seem to use a method I like.

Currently, I have a form with a lot of inputs that gets sent to the server when a "Submit" button is clicked. This is all sent via a json request using the normal AngularJS controller/service, and eventually handled by my ExpressJS router to store it in a MongoDB.

I want to add an input to select an image file to upload. Everything I find online seems to do it in a way that as soon as the user selects a file, its immediately copied to the server. Not what I want. Does anyone know if I can somehow upload the file when the "Submit" button is clicked? If so, where can I find information on this?

Thanks

答:
Take a look at this npm package: https://www.npmjs.com/package/express-fileupload

I chose to save the file on the filesystem but you can easily change it to store it in mongo

The router

```<code>router.post(‘/foo’, function (req, res, next) {
 if (!req.files){
    res.redirect(‘/foo’);
 }
 let file = req.files.file;
 let fileName = req.files.file.name;
 if(sys.isJSFile(fileName)){
    //save to filesystem or mongodb
    let filePath = path.join(‘./images’, fileName);
    // Use the mv() method to place the file somewhere on your server
    file.mv(filePath, function(err) {
 if (err){
        logger.error("Could not upload file: " + err);
        res.redirect(‘/foo’);
    } else {
        res.redirect(‘/bar’);
    }
  }
});
</code>```

The view

```<code> <form class="form-horizontal" action=“/foo” method="post" encType="multipart/form-data">
     <div class="form-group">
         <input class="form-control" type="file" name="file" />
     </div>
     <div class="form-group">
         <input class="form-control" type="submit" value="Submit"/>
     </div>
 </form>
</code>```

Title: Uploading image MEAN stack

Body:
Take a look at this npm package: https://www.npmjs.com/package/express-fileupload

I chose to save the file on the filesystem but you can easily change it to store it in mongo

The router

router.post(‘/foo’, function (req, res, next) {
 if (!req.files){
    res.redirect(‘/foo’);
 }
 let file = req.files.file;
 let fileName = req.files.file.name;
 if(sys.isJSFile(fileName)){
    //save to filesystem or mongodb
    let filePath = path.join(‘./images’, fileName);
    // Use the mv() method to place the file somewhere on your server
    file.mv(filePath, function(err) {
 if (err){
        logger.error("Could not upload file: " + err);
        res.redirect(‘/foo’);
    } else {
        res.redirect(‘/bar’);
    }
  }
});

The view

 <form class="form-horizontal" action=“/foo” method="post" encType="multipart/form-data">
     <div class="form-group">
         <input class="form-control" type="file" name="file" />
     </div>
     <div class="form-group">
         <input class="form-control" type="submit" value="Submit"/>
     </div>
 </form>


问:
IndentationError: expected an indented block in an indented block
i have a problem in my code i have no idea how to fix
i even tried to put 5 indents in the same line yet it didnt help
if i am in the wrong here can someone rewrite my code please so it will work? i have sat for about 40m and still couldnt figure out the problem thanks!</p>

```<code>def grade_len(password):
    if(len(password) <= 4):
        return 0
    if(5 <= len(password) <= 7):
        return 5
    if(len(password) > 7):
        return 10

def grade_used(password):
    if(password[0:9] == 'password' or 'love' in password or 'qwerty' in password or 'abc' in password):
        return 0
    else:
        return 10

def grade_vari(password):
    if(re.search('[a-z]',password) == False):
        return 0
    if(password.isalpha()):
        return 3
    if(password.lower == password.lower and password.isalpha() == False):
        return 5
    if(re.search('[a-z]',password) and re.search('[A-Z]',password) and re.search('[0-9]',password)):
        return 7
    if(re.search('[0-9]',password) and re.search('[a-z]',password) and re.search('[A-Z]',password) and re.match("[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]", password)):
        return 10

def main():
    password = raw_input ("enter password:")
    test1 = grade_len(password)
    test2 = grade_used(password)
    test3 = grade_vari(password)
    test_num = 3
    test_average = (test1+test2+test3)/3
    if(test_average<4):
        print("Weak")
    if(4<=test_average<=6):
        print("Medium")
    if(7<=test_average<=8):
        print("Strong")
    if(9<=test_average<=10):
        print("Very strong")

main()
</code>```

答:
Its a silly mistake, you forgot to import re. this works</p>

```<code>import re
def grade_len(password):
    if(len(password) <= 4):
        return 0
    if(5 <= len(password) <= 7):
        return 5
    if(len(password) > 7):
        return 10

def grade_used(password):
    if(password[0:9] == 'password' or 'love' in password or 'qwerty' in password or 'abc' in password):
        return 0
    else:
        return 10

def grade_vari(password):
    if(re.search('[a-z]',password) == False):
        return 0
    if(password.isalpha()):
        return 3
    if(password.lower == password.lower and password.isalpha() == False):
        return 5
    if(re.search('[a-z]',password) and re.search('[A-Z]',password) and re.search('[0-9]',password)):
        return 7
    if(re.search('[0-9]',password) and re.search('[a-z]',password) and re.search('[A-Z]',password) and re.match("[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]", password)):
        return 10

def main():
    password = raw_input ("enter password:")
    test1 = grade_len(password)
    test2 = grade_used(password)
    test3 = grade_vari(password)
    test_num = 3
    test_average = (test1+test2+test3)/3
    if(test_average<4):
        print("Weak")
    if(4<=test_average<=6):
        print("Medium")
    if(7<=test_average<=8):
        print("Strong")
    if(9<=test_average<=10):
        print("Very strong")

main()
</code>```

Body:
i have a problem in my code i have no idea how to fix
i even tried to put 5 indents in the same line yet it didnt help
if i am in the wrong here can someone rewrite my code please so it will work? i have sat for about 40m and still couldnt figure out the problem thanks!

def grade_len(password):
    if(len(password) <= 4):
        return 0
    if(5 <= len(password) <= 7):
        return 5
    if(len(password) > 7):
        return 10

def grade_used(password):
    if(password[0:9] == 'password' or 'love' in password or 'qwerty' in password or 'abc' in password):
        return 0
    else:
        return 10

def grade_vari(password):
    if(re.search('[a-z]',password) == False):
        return 0
    if(password.isalpha()):
        return 3
    if(password.lower == password.lower and password.isalpha() == False):
        return 5
    if(re.search('[a-z]',password) and re.search('[A-Z]',password) and re.search('[0-9]',password)):
        return 7
    if(re.search('[0-9]',password) and re.search('[a-z]',password) and re.search('[A-Z]',password) and re.match("[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]", password)):
        return 10

def main():
    password = raw_input ("enter password:")
    test1 = grade_len(password)
    test2 = grade_used(password)
    test3 = grade_vari(password)
    test_num = 3
    test_average = (test1+test2+test3)/3
    if(test_average<4):
        print("Weak")
    if(4<=test_average<=6):
        print("Medium")
    if(7<=test_average<=8):
        print("Strong")
    if(9<=test_average<=10):
        print("Very strong")

main()

Body:
Its a silly mistake, you forgot to import re. this works

import re
def grade_len(password):
    if(len(password) <= 4):
        return 0
    if(5 <= len(password) <= 7):
        return 5
    if(len(password) > 7):
        return 10

def grade_used(password):
    if(password[0:9] == 'password' or 'love' in password or 'qwerty' in password or 'abc' in password):
        return 0
    else:
        return 10

def grade_vari(password):
    if(re.search('[a-z]',password) == False):
        return 0
    if(password.isalpha()):
        return 3
    if(password.lower == password.lower and password.isalpha() == False):
        return 5
    if(re.search('[a-z]',password) and re.search('[A-Z]',password) and re.search('[0-9]',password)):
        return 7
    if(re.search('[0-9]',password) and re.search('[a-z]',password) and re.search('[A-Z]',password) and re.match("[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]", password)):
        return 10

def main():
    password = raw_input ("enter password:")
    test1 = grade_len(password)
    test2 = grade_used(password)
    test3 = grade_vari(password)
    test_num = 3
    test_average = (test1+test2+test3)/3
    if(test_average<4):
        print("Weak")
    if(4<=test_average<=6):
        print("Medium")
    if(7<=test_average<=8):
        print("Strong")
    if(9<=test_average<=10):
        print("Very strong")

main()


问:
Safe and smart http connection disconnect
I have a few questions regarding the advised usage of OkHttp, in matters of connection disconnection and reuse. However the Android documentation on these issues is not so clear. So here they are:

Safe multi-thread disconnection:

(a) According to Android documentation: https://developer.android.com/reference/java/net/HttpURLConnection.html
HttpUrlConnection is not thread-safe.

However according to the author of OkHttp, the recommended way to terminate an active connection from a thread which is not the one actively using the connection, is by calling the HttpUrlConnection.disconnect() method: https://github.com/square/okhttp/issues/1842.

So can this API be safely called from a thread other than the one actively using the connection? Is it true for all OkHttp versions integrated into Android?

(b) After calling disconnect(), should we also manually close the InputStream as well by calling the close() API? or is this not required once disconnect was called?

Regarding socket reuse: what is the recommended way to make sure that a connection can be reused? Android documentation states the following:

Once the response body has been read, the HttpURLConnection should be
  closed by calling disconnect(). Disconnecting releases the resources
  held by a connection so they may be closed or reused.

This implies that in order for the socket to be reused, disconnect() should be called.

However this seems to contradict other references in which I read that in order for the connection to be reused, the only resource that needs to be closed is the InputStream, and in fact disconnect() should not be called. This is also implied here: https://github.com/square/okhttp/issues/702

答:
It’s safe to call disconnect() on any thread, even while the HttpURLConnection is being used by another thread. This cancels the call but doesn’t release its resources.

If you created the HttpURLConnection you are obligated to close it when you’re done with it. The best way to do this is by closing the input stream or error stream. Which of these you get depends on the status code of the response.


问:
The explicit keyword in MS Visual Studio 4.1
I am implementing a smart pointer class using generics and I wanted to force users of this class to properly construct the smart pointer using syntax such as

```<code> MyReference<TestCls>(mytest3))
</code>```

or

```<code>MyReference<TestCls> mytest4(new TestCls());
</code>```

so I have used the explicit keyword on the CTOR, to prevent this:

```<code>MyReference aRef = NULL;
</code>```

However due to unfortunate circumstances beyond my control, I am working on code that is compiled using the ancient MSVC++ 4.1 compiler. I get the following errors when I include the explicit keyword:

MyReference.h(49) : error C2501: 'explicit' : missing decl-specifiers

  MyReference.h(51) : error C2143: syntax error : missing ';' before ''

  MyReference.h(52) : error C2238: unexpected token(s) preceding ':'

  MyReference.h(52) : error C2059: syntax error : 'int constant'

When I add a #define explicit those errors disappear.
This was a hack on my part, just to get the compiler to ignore the keyword. I'm guessing that this means that explicit is not supported by yon olde compiler.
Can someone confirm this and is there anyone out there with knowledge of a workaround solution for this?

Merci Beaucoups,
Dennis.

答:
This site has a workaround for this, namely:

Unfortunately, older compilers may not
  support the use of "explicit", which
  could be a headache. If you're stuck
  working with an out-of-date compiler
  and can't get one that has better
  support for the C++ standard, your
  best solution may be to take advantage
  of the fact that only a single
  implicit conversion will take place
  for a given value. You can exploit
  this by using an intermediate class
  that implicitly creates an object of
  each type, and then have your main
  class implicitly create objects from
  that class:

```<code>class proxy
{
    public:
    proxy(int x) : x(x) {} ;
    getValue() { return x; }

    private:
    int x;

};

class String
{
    // this will be equivalent of explicit
    String(proxy x) { /* create a string using x.getValue(); */ }
}
</code>```

Body:
I am implementing a smart pointer class using generics and I wanted to force users of this class to properly construct the smart pointer using syntax such as

 MyReference<TestCls>(mytest3))

or

MyReference<TestCls> mytest4(new TestCls());

so I have used the explicit keyword on the CTOR, to prevent this:

MyReference aRef = NULL;

However due to unfortunate circumstances beyond my control, I am working on code that is compiled using the ancient MSVC++ 4.1 compiler. I get the following errors when I include the explicit keyword:

MyReference.h(49) : error C2501: 'explicit' : missing decl-specifiers

  MyReference.h(51) : error C2143: syntax error : missing ';' before ''

  MyReference.h(52) : error C2238: unexpected token(s) preceding ':'

  MyReference.h(52) : error C2059: syntax error : 'int constant'

When I add a #define explicit those errors disappear.
This was a hack on my part, just to get the compiler to ignore the keyword. I'm guessing that this means that explicit is not supported by yon olde compiler.
Can someone confirm this and is there anyone out there with knowledge of a workaround solution for this?

Merci Beaucoups,
Dennis.

Body:
This site has a workaround for this, namely:

Unfortunately, older compilers may not
  support the use of "explicit", which
  could be a headache. If you're stuck
  working with an out-of-date compiler
  and can't get one that has better
  support for the C++ standard, your
  best solution may be to take advantage
  of the fact that only a single
  implicit conversion will take place
  for a given value. You can exploit
  this by using an intermediate class
  that implicitly creates an object of
  each type, and then have your main
  class implicitly create objects from
  that class:

class proxy
{
    public:
    proxy(int x) : x(x) {} ;
    getValue() { return x; }

    private:
    int x;

};

class String
{
    // this will be equivalent of explicit
    String(proxy x) { /* create a string using x.getValue(); */ }
}


问:
Responsive Bootstrap 4 grid for Angular 2 ngFor
I wonder if there's a way to render responsively elements created by *ngFor in Angular 2?

I use Bootstrap 4 grid system based on flex property. And I've got this code in my Angular2 app:

```<code><div class="outlet container">
<div class="row itemsBlock">
   <div *ngFor="let item of items" class="itemRender">
        <img class="itemImage" src="{{item.image}}" />
        <span class=itemitle">{{item.title}}</span>
   </div>
</div>
</code>```

What I want is to get my items rendered responsively, say

3 divs in the row on large and middle-sized displays

2 divs in the row on small ones

1 div in the row on x-small displays

答:
You can't really relate that stuff with looping over items collection. You could take use xl, lg,md & sm class with col-size-number(like col-xs-12) class on same row. Bootstrap will take care about to applying a class over element based on screen resolution.

Markup

```<code><div class="row itemsBlock">
   <div *ngFor="let item of items" class="col-md-4 col-sm-6 col-12">
        <img class="itemImage" src="{{item.image}}" />
        <span class=itemitle">{{item.title}}</span>
   </div>
</div>
</code>```

Note: The Bootstrap v4 grid system has five tiers of classes: xs
  (extra small), sm (small), md (medium), lg (large), and xl (extra
  large). You can use nearly any combination of these classes to create
  more dynamic and flexible layouts.

Body:
I wonder if there's a way to render responsively elements created by *ngFor in Angular 2?

I use Bootstrap 4 grid system based on flex property. And I've got this code in my Angular2 app:

        {{item.title}}

What I want is to get my items rendered responsively, say

3 divs in the row on large and middle-sized displays

2 divs in the row on small ones

1 div in the row on x-small displays

Body:
You can't really relate that stuff with looping over items collection. You could take use xl, lg,md & sm class with col-size-number(like col-xs-12) class on same row. Bootstrap will take care about to applying a class over element based on screen resolution.

Markup

<div class="row itemsBlock">
   <div *ngFor="let item of items" class="col-md-4 col-sm-6 col-12">
        <img class="itemImage" src="{{item.image}}" />
        <span class=itemitle">{{item.title}}</span>
   </div>
</div>

Note: The Bootstrap v4 grid system has five tiers of classes: xs
  (extra small), sm (small), md (medium), lg (large), and xl (extra
  large). You can use nearly any combination of these classes to create
  more dynamic and flexible layouts.


问:
Matlab submatrix multiplication poor performance
Multiplications of submatricies in matlab seems to be materially slower than multiplication of the matrix they are drawn from.

```<code>>> m = rand(1e7, 40);
>> tic; m' * m; toc % (1)
Elapsed time is 0.245803 seconds.
>> tic; m(1:2.5e6, :)' * m(1:2.5e6, :); toc % (2)
Elapsed time is 1.810981 seconds.
>> tic; t = m(1:2.5e6, :); t' * t; toc % (3)
Elapsed time is 0.885764 seconds.
</code>```

I had hoped that there would be some fast builtin methods for this, since the data is already in memory, but it seems there's no way to prevent matlab from making intermediate copies. (3) is faster but garuntees that we make a copy.

Is there any technique in matlab to make operations (e.g. multiplcation, transpose) as quick on the subset of a matrix as they are the whole?

Is the only fast way to achieve this to with mex?

Edit: Using column major data speeds things up across the board (as expected), but is still much slower when multiplying the submatricies.

```<code>>> m = rand(40,1e7);
>> tic; m * m'; toc
Elapsed time is 0.251958 seconds.
>> tic; m(:, 1:2.5e6) * m(:, 1:2.5e6)'; toc
Elapsed time is 1.461321 seconds.
>> tic; s=m(:, 1:2.5e6); s * s'; toc
Elapsed time is 0.555667 seconds.
</code>```

Clearly matlab is taking copies when indexing, but is there any way to prevent this (it's clear such a multiplication algorithm can exist without copying the data, I just want to know if it's expressible in matlab).

答:
MATLAB does copy-on-write, meaning that copying a matrix doesn't really copy the data, at least until you try to change one of the two matrices that point to the same data. However, when you copy a part of a matrix, the data is always copied. That is, a matrix never points to a subset of values of a different matrix. MATLAB always stores data consecutively in memory (column-major ordering), and so it would rarely be the case that the part of the matrix that you index is consecutive in memory. One way to try this out is to use format debug and look at data pointers:

```<code>>> format debug
>> q=rand(10,100)
q =
Structure address = 127e64560
m = 10
n = 100
pr = 7f9f5c835420
pi = 0
  Columns 1 through 9
    0.8147    0.1576    0.6557    0.7060    0.4387    0.2760    0.7513    0.8407    0.3517
    ...

>> q(:,1:2)
ans =
Structure address = 11dadd750
m = 10
n = 2
pr = 7f9f5b792700
pi = 0
  0.8147    0.1576
  ..
</code>```

Note how the pr value (pointer to the real-valued portion of the data) changes. This shows that the data is copied.

If you cannot use vectorized code (i.e. apply the operation on the matrix as a whole), your best bet for speeding up computation is a MEX-file.

Body:
Multiplications of submatricies in matlab seems to be materially slower than multiplication of the matrix they are drawn from.

>> m = rand(1e7, 40);
>> tic; m' * m; toc % (1)
Elapsed time is 0.245803 seconds.
>> tic; m(1:2.5e6, :)' * m(1:2.5e6, :); toc % (2)
Elapsed time is 1.810981 seconds.
>> tic; t = m(1:2.5e6, :); t' * t; toc % (3)
Elapsed time is 0.885764 seconds.

I had hoped that there would be some fast builtin methods for this, since the data is already in memory, but it seems there's no way to prevent matlab from making intermediate copies. (3) is faster but garuntees that we make a copy.

Is there any technique in matlab to make operations (e.g. multiplcation, transpose) as quick on the subset of a matrix as they are the whole?

Is the only fast way to achieve this to with mex?

Edit: Using column major data speeds things up across the board (as expected), but is still much slower when multiplying the submatricies.

>> m = rand(40,1e7);
>> tic; m * m'; toc
Elapsed time is 0.251958 seconds.
>> tic; m(:, 1:2.5e6) * m(:, 1:2.5e6)'; toc
Elapsed time is 1.461321 seconds.
>> tic; s=m(:, 1:2.5e6); s * s'; toc
Elapsed time is 0.555667 seconds.

Clearly matlab is taking copies when indexing, but is there any way to prevent this (it's clear such a multiplication algorithm can exist without copying the data, I just want to know if it's expressible in matlab).

Body:
MATLAB does copy-on-write, meaning that copying a matrix doesn't really copy the data, at least until you try to change one of the two matrices that point to the same data. However, when you copy a part of a matrix, the data is always copied. That is, a matrix never points to a subset of values of a different matrix. MATLAB always stores data consecutively in memory (column-major ordering), and so it would rarely be the case that the part of the matrix that you index is consecutive in memory. One way to try this out is to use format debug and look at data pointers:

>> format debug
>> q=rand(10,100)
q =
Structure address = 127e64560
m = 10
n = 100
pr = 7f9f5c835420
pi = 0
  Columns 1 through 9
    0.8147    0.1576    0.6557    0.7060    0.4387    0.2760    0.7513    0.8407    0.3517
    ...

>> q(:,1:2)
ans =
Structure address = 11dadd750
m = 10
n = 2
pr = 7f9f5b792700
pi = 0
  0.8147    0.1576
  ..

Note how the pr value (pointer to the real-valued portion of the data) changes. This shows that the data is copied.

If you cannot use vectorized code (i.e. apply the operation on the matrix as a whole), your best bet for speeding up computation is a MEX-file.


问:
Php how to verify is string is certain function for security verification
I an using the eval() function in an ajax file that will allow me to call functions from Javascript (similar to Securely calling PHP code from JavaScript);

I have around 20 functions that I want to be able to use. I do not want malicious code passed in. How can I verify that the string passed in is one of my functions, and nothing more?

答:
You can use the @Hyder B is method for that. personally I think that's the best option if you just want to call a function. Also if you're worried about someone getting access to your ajax files (other than viewing then through the browser's source reader); they can access the function file also so that something you'll need to improve on the server. You can however stop people from trying to load the functions file directly by adding this:

<?php
if (count(get_required_files()) <= 1) {
  header("location: ./index.php");
}
?>```

That will redirect the user if the file is accessed directly.

Body:
You can use the @Hyder B is method for that. personally I think that's the best option if you just want to call a function. Also if you're worried about someone getting access to your ajax files (other than viewing then through the browser's source reader); they can access the function file also so that something you'll need to improve on the server. You can however stop people from trying to load the functions file directly by adding this:

<?php
if (count(get_required_files()) <= 1) {
  header("location: ./index.php");
}
?>

That will redirect the user if the file is accessed directly.


问:
initialized imageview in onCreate but still null
I want to achieve the following: Once user click a button, change current layout(main) to the other and the other layout has an image loaded. But I keep getting error message say "virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference". The following is my mainactivity.java and 'the other layout'.xml

```<code>public class MainActivity extends AppCompatActivity {

    private Button mybtn;
    private ImageView myimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init(){

        myimage = (ImageView) findViewById(R.id.imgview);
        mybtn = (Button) findViewById(R.id.btn);
        mybtn.setOnClickListener(new MyListener());
    }

    public class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v){
            switch (v.getId()){

                case R.id.btn:
                    setContentView(R.layout.the_other_layout);
                    initMap();
            }
        }
    }

    public void initMap(){

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bmp = null;
        bmp = BitmapFactory.decodeResource(getResources(),R.drawable.somepngfile,options);
        myimage.setImageBitmap(bmp);
    }
}
</code>```

The follwoing is the_other_layout xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        />

</LinearLayout>
</code>```

EDIT:

Please check the answer below if you have the similar problem

答:
Problem is here:

```<code>case R.id.btn:
          setContentView(R.layout.the_other_layout);
          initMap();
</code>```

Remove this:

```<code>setContentView(R.layout.the_other_layout);
</code>```

you can not set two layout in an Activity.

Edit

For a fullscreen imageView:

```<code> public void initMap(){
       myimage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
       myimage.setImageDrawable(R.drawable.your_image);
       myimage.setScaleType(ImageView.ScaleType.FIT_XY);
   }
</code>```

Body:
I want to achieve the following: Once user click a button, change current layout(main) to the other and the other layout has an image loaded. But I keep getting error message say "virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference". The following is my mainactivity.java and 'the other layout'.xml

public class MainActivity extends AppCompatActivity {

    private Button mybtn;
    private ImageView myimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init(){

        myimage = (ImageView) findViewById(R.id.imgview);
        mybtn = (Button) findViewById(R.id.btn);
        mybtn.setOnClickListener(new MyListener());
    }

    public class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v){
            switch (v.getId()){

                case R.id.btn:
                    setContentView(R.layout.the_other_layout);
                    initMap();
            }
        }
    }

    public void initMap(){

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bmp = null;
        bmp = BitmapFactory.decodeResource(getResources(),R.drawable.somepngfile,options);
        myimage.setImageBitmap(bmp);
    }
}

The follwoing is the_other_layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        />

</LinearLayout>

EDIT:

Please check the answer below if you have the similar problem

Body:
Problem is here:

case R.id.btn:
          setContentView(R.layout.the_other_layout);
          initMap();

Remove this:

setContentView(R.layout.the_other_layout);

you can not set two layout in an Activity.

Edit

For a fullscreen imageView:

 public void initMap(){
       myimage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
       myimage.setImageDrawable(R.drawable.your_image);
       myimage.setScaleType(ImageView.ScaleType.FIT_XY);
   }


问:
Joomla Template Not able to see newly installed template
I am pretty new to joomla . I have a server http://www.newsnowis.com which was having an old installation and old data. I installed http://demo4.ltheme.com/joomla/lt-news/ template and set this template as default.

Now i open http://www.newsnowis.com/ what happens is it just redirects to http://www.newsnowis.com/english/ with a blank screen.

My expectation is it should open the template with sample data. Can anyone sugggest which configuration is wrong and missing? This server is running in godaddy would it be misconfiguration of Cpanel? Any help is appreciated...

答: The more likely explanation for the blank screen when you set template is that the version of Joomla is too old for the template you have installed. Otherwise, you have installed a version of the template that isn't compatible with the version of Joomla you have installed.</p>


问:
Django filter by min value
Right now I have this:

```<code>status = request.GET.get('status')
persons = Person.objects.filter(vip_status= status)
</code>```

How do I select all persons with vip_status > status? I tried this:

```<code>persons = Person.objects.filter(vip_status >  status)
</code>```

But it didn't work.

答:
You must write like this:</p>

```<code>persons = Person.objects.filter(vip_status__gt=status)
</code>```

Title: Django filter by min value

Body:
Right now I have this:

status = request.GET.get('status')
persons = Person.objects.filter(vip_status= status)

How do I select all persons with vip_status > status? I tried this:

persons = Person.objects.filter(vip_status >  status)

But it didn't work.

Body:
You must write like this:

persons = Person.objects.filter(vip_status__gt=status)