问:
Failed to avoid entering password multiple times using scp, and looping not working
I've written the below script that looping through names in a csv file and copy specific files to remote computer:

```<code>list_filepath=/home/bella/lists
destination_path=/home/pome/Documents/newfiles
NS_samples_source_path=/home/bella/final/acs/pa/1_ns
th_samples_source_path=/home/bella/final/acs/pa/4_th
ad_samples_source_path=/home/bella/final/new2018/ad

cat $list_filepath/new_list.csv | while read line
do

  if [[ $line == AD* ]]
     then
     echo $line
     ssh pome@203.177.32.11 mkdir -p $destination_path/$line
     cd $ad_samples_source_path/$line
     find $ad_samples_source_path/$line/ -regex '.*\.\(csv\|xml\|gz\)$' -exec scp {} pome@203.177.32.11:$destination_path/$line \;

  elif [[ $line == NS* ]]
     then
     echo $line
     ssh pome@203.177.32.11 "mkdir -p $destination_path/$line"
     cd $NS_samples_source/$line
     find $NS_samples_source/$line/ -regex '.*\.\(csv\|xml\|gz\)$' -exec scp {} pome@203.177.32.11:$destination_path/$line \;

  else
     echo $line
     ssh pome@203.177.32.11 "mkdir -p $destination_path/$line"
     cd $th_samples_source_path/$line
     find $th_samples_source_path/$line/ -regex '.*\.\(csv\|xml\|gz\)$' -exec scp {} pome@203.177.32.11:$destination_path/$line \;

  fi

done
</code>```

I have 2 main problems:

I have to enter multiple times the password for the remote, even though I'v set a password-less key as below:

```<code>ssh-keygen
ssh-copy-id -i pome@203.177.32.11
</code>```

it still asks for the password for each file it copies.

The scripts ends after creating one directory with the copied files, it seems to fail to move to the next line in the csv file.

Ideas anybody how to address those issues?

Thanks!

答:
Point 1 is because there is no SSH agent on your local host or the remote host is not configured to accept keys, and point 2 is because SSH will swallow the standard input that you were expecting to send to read. Relevant FAQ entries:

I want to automate an ssh (or scp, or sftp) connection, but I don't know how to send the password....

I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed!

Body:
I've written the below script that looping through names in a csv file and copy specific files to remote computer:

list_filepath=/home/bella/lists
destination_path=/home/pome/Documents/newfiles
NS_samples_source_path=/home/bella/final/acs/pa/1_ns
th_samples_source_path=/home/bella/final/acs/pa/4_th
ad_samples_source_path=/home/bella/final/new2018/ad

cat $list_filepath/new_list.csv | while read line
do

  if [[ $line == AD* ]]
     then
     echo $line
     ssh pome@203.177.32.11 mkdir -p $destination_path/$line
     cd $ad_samples_source_path/$line
     find $ad_samples_source_path/$line/ -regex '.*\.\(csv\|xml\|gz\)$' -exec scp {} pome@203.177.32.11:$destination_path/$line \;

  elif [[ $line == NS* ]]
     then
     echo $line
     ssh pome@203.177.32.11 "mkdir -p $destination_path/$line"
     cd $NS_samples_source/$line
     find $NS_samples_source/$line/ -regex '.*\.\(csv\|xml\|gz\)$' -exec scp {} pome@203.177.32.11:$destination_path/$line \;

  else
     echo $line
     ssh pome@203.177.32.11 "mkdir -p $destination_path/$line"
     cd $th_samples_source_path/$line
     find $th_samples_source_path/$line/ -regex '.*\.\(csv\|xml\|gz\)$' -exec scp {} pome@203.177.32.11:$destination_path/$line \;

  fi

done

I have 2 main problems:

I have to enter multiple times the password for the remote, even though I'v set a password-less key as below:

ssh-keygen
ssh-copy-id -i pome@203.177.32.11

it still asks for the password for each file it copies.

The scripts ends after creating one directory with the copied files, it seems to fail to move to the next line in the csv file.

Ideas anybody how to address those issues?

Thanks!


来源: stackexchange

问:
Javascript AJAX responseText problem in IE
I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:

(AJAX)

```<code>function getMessages(messengerid, repeat)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("messages").innerHTML=xmlhttp.responseText;
    document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
    }
  }
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
    setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
</code>```

(PHP/MySql)

```<code><?php
$key = "abcIUETH85i236t246jerst3487Jh";

if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {

    include_once("../config.php");
    include_once("../class/system.class.php");

    $sys = new system($template_name);

    if(!$sys->connect($db)) {
        exit();
    }

    $messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
    $messenger    = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");

    $user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
    $user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");

    $displaynames[$user1[0]['id']] = $user1[0]['displayname'];
    $displaynames[$user2[0]['id']] = $user2[0]['displayname'];

    foreach($messages AS $key => $message) {

    if(is_numeric($key)) {
    ?>
    <div class="message">
        <b><?=$displaynames[$message['account_id']];?>  (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
        <?=nl2br($message['message_content']);?>
    </div>
    <?php
    }
    }

}

?>
</code>```

Any help would be much appreciated!
Thanks in advance.

Best Regards,
Skyfe.

答: Your response is being cached. One way to fix this is to append a unique parameter in your request URL, such as the current timestamp.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:

(AJAX)

function getMessages(messengerid, repeat)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("messages").innerHTML=xmlhttp.responseText;
    document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
    }
  }
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
    setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}

(PHP/MySql)

<?php
$key = "abcIUETH85i236t246jerst3487Jh";

if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {

    include_once("../config.php");
    include_once("../class/system.class.php");

    $sys = new system($template_name);

    if(!$sys->connect($db)) {
        exit();
    }

    $messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
    $messenger    = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");

    $user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
    $user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");

    $displaynames[$user1[0]['id']] = $user1[0]['displayname'];
    $displaynames[$user2[0]['id']] = $user2[0]['displayname'];

    foreach($messages AS $key => $message) {

    if(is_numeric($key)) {
    ?>

        <?=$displaynames[$message['account_id']];?>  (<?=date("h:m:s", $message['timestamp']);?>) says:

        <?=nl2br($message['message_content']);?>

    <?php
    }
    }

}

?>

Any help would be much appreciated!
Thanks in advance.

Best Regards,
Skyfe.


问:
white space between images in owl carousel 2
I am trying simple slider in owl carousel but there's space between images. How to remove space between images in owl- carousel 2? I tried to increase items but it removes the arrow button.
In mobile view, space is even more between two images. Please help.
Thank you

main.js

```<code>$(document).ready(function(){
    $('.owl-carousel').owlCarousel({
        autoWidth:false,
        items:3,
        loop:true,
        margin:10,
        autoplay:true,
        autoplayTimeout:2000,
        autoplayHoverPause:true,
        dots: false,
        stagePadding:40,
        nav:true,
        navText: ['<i class="fas fa-chevron-left" aria-hidden="true"></i>','<i class="fas fa-chevron-right" aria-hidden="true"></i>'],
        responsive:{
            0:{
                items:2
            },
            600:{
                items:2
            },
            1000:{
                items:5
            }
        }
    })
  });
</code>```

style.css

```<code>  .owl-carousel .item img{
    height:120px;
    width:120px;
}

.owl-item .active{
    height:120px;
    width:120px;
}
.owl-carousel .item{
    text-align: center;
}

/* owl nav */
.owl-prev i, .owl-next i {
    color: #000000;
}

.owl-prev, .owl-next {
    position:absolute;
    top: 0;
    height:30%;
    -webkit-border-radius: 40px;
    -moz-border-radius: 40px;
    border-radius: 30px;
    background: #869791;

}

.owl-prev {
    left:0;
    top: 42px;
}

.owl-next {
    right:0;
    top: 42px;
}
/* removing blue outline from buttons */
.owl-next:focus, .owl-prev:focus
 {
     outline: none;
}

.caroussel-theme{
    background-color: aquamarine
}
.container-fluid {
    max-width: 1230px;
}
.text-content{
    color:#000000;
    font-size:16px;
    font-family: 'Georgia, 'Times New Roman', Times, serif';
}
div.owl-item > div {
    display:table-cell;
    vertical-align:middle;
}
.owl-stage{
    width:150px;
}
</code>```

Image:
image that shows space between two images

答:
It would be helpful to us, if you create a fiddle. Anyways ...

```<code>$(document).ready(function(){
    $('.owl-carousel').owlCarousel({
        autoWidth:false,
        items:3,
        loop:true,
        margin:0,
        autoplay:true,
        autoplayTimeout:2000,
        autoplayHoverPause:true,
        dots: false,
        stagePadding:40,
        nav:true,
        navText: ['<i class="fas fa-chevron-left" aria-hidden="true"></i>','<i class="fas fa-chevron-right" aria-hidden="true"></i>'],
        responsive:{
            0:{
                items:2
            },
            600:{
                items:2
            },
            1000:{
                items:5
            }
        }
    })
  });
</code>```

Try this solution.

ContentLicense: CC BY-SA 4.0

Body:
I am trying simple slider in owl carousel but there's space between images. How to remove space between images in owl- carousel 2? I tried to increase items but it removes the arrow button.
In mobile view, space is even more between two images. Please help.
Thank you

main.js

$(document).ready(function(){
    $('.owl-carousel').owlCarousel({
        autoWidth:false,
        items:3,
        loop:true,
        margin:10,
        autoplay:true,
        autoplayTimeout:2000,
        autoplayHoverPause:true,
        dots: false,
        stagePadding:40,
        nav:true,
        navText: ['',''],
        responsive:{
            0:{
                items:2
            },
            600:{
                items:2
            },
            1000:{
                items:5
            }
        }
    })
  });

style.css

  .owl-carousel .item img{
    height:120px;
    width:120px;
}

.owl-item .active{
    height:120px;
    width:120px;
}
.owl-carousel .item{
    text-align: center;
}

/* owl nav */
.owl-prev i, .owl-next i {
    color: #000000;
}

.owl-prev, .owl-next {
    position:absolute;
    top: 0;
    height:30%;
    -webkit-border-radius: 40px;
    -moz-border-radius: 40px;
    border-radius: 30px;
    background: #869791;

}

.owl-prev {
    left:0;
    top: 42px;
}

.owl-next {
    right:0;
    top: 42px;
}
/* removing blue outline from buttons */
.owl-next:focus, .owl-prev:focus
 {
     outline: none;
}

.caroussel-theme{
    background-color: aquamarine
}
.container-fluid {
    max-width: 1230px;
}
.text-content{
    color:#000000;
    font-size:16px;
    font-family: 'Georgia, 'Times New Roman', Times, serif';
}
div.owl-item > div {
    display:table-cell;
    vertical-align:middle;
}
.owl-stage{
    width:150px;
}

Image:
image that shows space between two images

Body:
It would be helpful to us, if you create a fiddle. Anyways ...

$(document).ready(function(){
    $('.owl-carousel').owlCarousel({
        autoWidth:false,
        items:3,
        loop:true,
        margin:0,
        autoplay:true,
        autoplayTimeout:2000,
        autoplayHoverPause:true,
        dots: false,
        stagePadding:40,
        nav:true,
        navText: ['<i class="fas fa-chevron-left" aria-hidden="true"></i>','<i class="fas fa-chevron-right" aria-hidden="true"></i>'],
        responsive:{
            0:{
                items:2
            },
            600:{
                items:2
            },
            1000:{
                items:5
            }
        }
    })
  });

Try this solution.


问:
How to add new field in array of arrays in angular5
I am getting response from my database is like this

```<code>content:Array
0:Object
title:"title1"
content:"content1"
illustrations:Array
0:Object
title:"someTitle"
imagePath:"1.jpg"
</code>```

Here I want to add one randomId in illustrations array. like this

```<code>illustrations:Array
    0:Object
    title:"someTitle"
    imagePath:"1.jpg"
    randomId:54321
</code>```

I tried like this

```<code>var randid=Math.random()*900000
            var rand=Math.round(randid)
this.illustrations[i]=Object.assign({},this.illustrations[i],{randid:rand})
and also
this.illustrations[i]=Object.assign(this.illustrations[i],{randid:rand})
</code>```

But not working.
Can any one please help.

答:
You can do it like this:</p>

```<code>this.illustrations[i].randid = rand;
</code>```

Body:
I am getting response from my database is like this

content:Array
0:Object
title:"title1"
content:"content1"
illustrations:Array
0:Object
title:"someTitle"
imagePath:"1.jpg"

Here I want to add one randomId in illustrations array. like this

illustrations:Array
    0:Object
    title:"someTitle"
    imagePath:"1.jpg"
    randomId:54321

I tried like this

var randid=Math.random()*900000
            var rand=Math.round(randid)
this.illustrations[i]=Object.assign({},this.illustrations[i],{randid:rand})
and also
this.illustrations[i]=Object.assign(this.illustrations[i],{randid:rand})

But not working.
Can any one please help.

Body:
You can do it like this:

this.illustrations[i].randid = rand;


问:
I want my ttk.treeview to have alternating colours
I want my ttl.treeview table to have an alternating pattern of colours and I tried to add tags and make the background of each odd row distinct by using the tag_configure method, but I haven't been able.

Every row is a row taken from a db table that I want to show.

I also tried to do so in a little and separate program, but it hasn't been effective either.

```<code>def show(self, row, column, rowspan):
    self.row = row
    self.column = column
    self.rowspan = rowspan
    global FondoBase

    self.Tabla = ttk.Treeview(FondoBase, columns=self.Columnas[1:], height=40)

    self.Tabla.heading("#0", text=self.Columnas[0])
    for i in self.Columnas[1:]:
        self.Tabla.heading("{}".format(i), text="{}".format(i))

    self.Tabla.grid(row=row, column=column, rowspan=rowspan, sticky="e", pady=30)
    scrol = Scrollbar(FondoBase, command=self.Tabla.yview)

    self.Tabla.config(yscrollcommand=scrol.set)

    scrol.grid(row=row, column=column+1, sticky="wns", rowspan=rowspan, pady=30)

    Conexion = connect('{}'.format(Directorio))

    with Conexion:

        Seleccion = Conexion.cursor()

        Seleccion.execute("""SELECT * FROM {}""".format(self.nombre))

        resultado = Seleccion.fetchall()

    for i in range(len(resultado)):
        if i%2 == 0:
        self.Tabla.insert("", i, text="{}".format(resultado[i][0]), values=(resultado[i][1:]), tags=("par"))
            self.Tabla.tag_configure("par", background="#00ffff")

        else:
            self.Tabla.insert("", i, text="{}".format(resultado[i][0]), values=(resultado[i][1:]), tags=("impar"))
</code>```

I don't really know what's going on.

答:
-what version of python are you using (python -V) in cmd</p>

<p>-the last version(3.7) of python seems like it has bugs to color tags </p>

<p>-if your using the last version just install python 3.6 </p>

<p>-one of your tags doesn't have a color </p>

```<code>self.Tabla.tag_configure("impar", background="#ff008c")
</code>```

Body:
I want my ttl.treeview table to have an alternating pattern of colours and I tried to add tags and make the background of each odd row distinct by using the tag_configure method, but I haven't been able.

Every row is a row taken from a db table that I want to show.

I also tried to do so in a little and separate program, but it hasn't been effective either.

def show(self, row, column, rowspan):
    self.row = row
    self.column = column
    self.rowspan = rowspan
    global FondoBase

    self.Tabla = ttk.Treeview(FondoBase, columns=self.Columnas[1:], height=40)

    self.Tabla.heading("#0", text=self.Columnas[0])
    for i in self.Columnas[1:]:
        self.Tabla.heading("{}".format(i), text="{}".format(i))

    self.Tabla.grid(row=row, column=column, rowspan=rowspan, sticky="e", pady=30)
    scrol = Scrollbar(FondoBase, command=self.Tabla.yview)

    self.Tabla.config(yscrollcommand=scrol.set)

    scrol.grid(row=row, column=column+1, sticky="wns", rowspan=rowspan, pady=30)

    Conexion = connect('{}'.format(Directorio))

    with Conexion:

        Seleccion = Conexion.cursor()

        Seleccion.execute("""SELECT * FROM {}""".format(self.nombre))

        resultado = Seleccion.fetchall()

    for i in range(len(resultado)):
        if i%2 == 0:
        self.Tabla.insert("", i, text="{}".format(resultado[i][0]), values=(resultado[i][1:]), tags=("par"))
            self.Tabla.tag_configure("par", background="#00ffff")

        else:
            self.Tabla.insert("", i, text="{}".format(resultado[i][0]), values=(resultado[i][1:]), tags=("impar"))

I don't really know what's going on.

Body:
-what version of python are you using (python -V) in cmd

-the last version(3.7) of python seems like it has bugs to color tags

-if your using the last version just install python 3.6

-one of your tags doesn't have a color

self.Tabla.tag_configure("impar", background="#ff008c")


问:
JSON to POJO conversion error
I am trying to pass a JSON request to my server where the controller encounters an error while converting the JSON to POJO.

JSON Request

```<code>{
   "request":[
      {"name":"mac"},
      {"name":"rosy"}
   ]
}
</code>```

My controller function

```<code>@RequestMapping(value = "/namelist",
            method = RequestMethod.POST,
            consumes = { "application/json" },
            produces = {"application/json"})
public ... postNameList(@RequestBody NameList names) {}

Public Class NameList extends ArrayList<Name> {}
Public Class Name { private name; ...}
</code>```

Error

message: "Could not read JSON: Can not deserialize instance of
  com.abc.xyz.mypackage.NameList out of START_OBJECT token at [Source:
  org.eclipse.jetty.server.HttpConnection$Input@79aac24b{HttpChannelOverHttp@1d109942{r=1,a=DISPATCHED,uri=/namelist},HttpConnection@2cbdcaf6{FILLING},g=HttpGenerator{s=START},p=HttpParser{s=END,137
  of 137}}; line: 1, column: 1]

I am not sure what's wrong with the code. I am fairly new to Spring so any help is appreciated.

答:
I faced similar situation and then created utility to convert JSON objects into Java Objects. Hope this helps.

Here sample.json is the file you want to a Java Object

```<code>import com.sun.codemodel.JCodeModel;
import org.jsonschema2pojo.*;
import org.jsonschema2pojo.rules.RuleFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

/**
 * Created by Pratik Ambani
 */
class JsonToPojo {

    public static void main(String[] args) {
        String packageName = "com.practise";
        File inputJson = null;
        try {
            inputJson = ResourceUtils.getFile("classpath:sample.json");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File outputPojoDirectory = new File("." + File.separator + "Generated Pojo");
        outputPojoDirectory.mkdirs();

        try {
            new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
        } catch (IOException e) {
            System.err.println("Encountered issue while converting to pojo: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException {
        JCodeModel codeModel = new JCodeModel();
        GenerationConfig config = new DefaultGenerationConfig() {
            @Override
            public boolean isGenerateBuilders() { // set config option by overriding method
                return true;
            }

            @Override
            public SourceType getSourceType() {
                return SourceType.JSON;
            }
        };
        SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
        mapper.generate(codeModel, className, packageName, inputJson);
        codeModel.build(outputPojoDirectory);
    }
}
</code>```

Title: JSON to POJO conversion error

Body:
I am trying to pass a JSON request to my server where the controller encounters an error while converting the JSON to POJO.

JSON Request

{
   "request":[
      {"name":"mac"},
      {"name":"rosy"}
   ]
}

My controller function

@RequestMapping(value = "/namelist",
            method = RequestMethod.POST,
            consumes = { "application/json" },
            produces = {"application/json"})
public ... postNameList(@RequestBody NameList names) {}

Public Class NameList extends ArrayList<Name> {}
Public Class Name { private name; ...}

Error

message: "Could not read JSON: Can not deserialize instance of
  com.abc.xyz.mypackage.NameList out of START_OBJECT token at [Source:
  org.eclipse.jetty.server.HttpConnection$Input@79aac24b{HttpChannelOverHttp@1d109942{r=1,a=DISPATCHED,uri=/namelist},HttpConnection@2cbdcaf6{FILLING},g=HttpGenerator{s=START},p=HttpParser{s=END,137
  of 137}}; line: 1, column: 1]

I am not sure what's wrong with the code. I am fairly new to Spring so any help is appreciated.

Body:
I faced similar situation and then created utility to convert JSON objects into Java Objects. Hope this helps.

Here sample.json is the file you want to a Java Object

import com.sun.codemodel.JCodeModel;
import org.jsonschema2pojo.*;
import org.jsonschema2pojo.rules.RuleFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

/**
 * Created by Pratik Ambani
 */
class JsonToPojo {

    public static void main(String[] args) {
        String packageName = "com.practise";
        File inputJson = null;
        try {
            inputJson = ResourceUtils.getFile("classpath:sample.json");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File outputPojoDirectory = new File("." + File.separator + "Generated Pojo");
        outputPojoDirectory.mkdirs();

        try {
            new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
        } catch (IOException e) {
            System.err.println("Encountered issue while converting to pojo: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException {
        JCodeModel codeModel = new JCodeModel();
        GenerationConfig config = new DefaultGenerationConfig() {
            @Override
            public boolean isGenerateBuilders() { // set config option by overriding method
                return true;
            }

            @Override
            public SourceType getSourceType() {
                return SourceType.JSON;
            }
        };
        SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
        mapper.generate(codeModel, className, packageName, inputJson);
        codeModel.build(outputPojoDirectory);
    }
}


问:
Is there a Firefox keyboard shortcut to clear the cache?
With the Firefox web developer toolbar I can select "Miscellaneous → Clear private data → Cache".  Is there a way to do the same with a keyboard shortcut?

Edit: I am also using vimperator to drive Firefox with the keyboard; just found out that it's possible using: :emenu Extra.Web Developer.Miscellaneous.Clear Private Data.Cache.

答:
In Firefox is

CTRL + SHIFT + R

Source

OwnerDisplayName: sotto

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Roger Pate

Body:
In Firefox is

CTRL + SHIFT + R

Source


问:
Images stretched in flex container but cannot use align-self-center
I have the following markup (Bootstrap 4):

```<code><div class="col-3 d-flex flex-column">
    <img class="align-self-center" src="#"/>
</div>
</code>```

Since the container is flexed, the images are stretching. I'm aware align-self-center will resolve the issue, however, I don't want the image to be centered. I want the image to be align-self-left (left aligned rather than centered), but this stretched the image again.

Any way around this?

答: Instead of using   use . This should solve your problem (Basically it means that you image will be aligned to the start of your column)

Body:
I have the following markup (Bootstrap 4):

Since the container is flexed, the images are stretching. I'm aware align-self-center will resolve the issue, however, I don't want the image to be centered. I want the image to be align-self-left (left aligned rather than centered), but this stretched the image again.

Any way around this?

Body: Instead of using  <img class="align-self-center" src="#"/> use <img class="align-self-start" src="#"/>. This should solve your problem (Basically it means that you image will be aligned to the start of your column)


问:
What am I doing wrong? It shows me that the list index is out of range
I have a given list and I want to add all elements of that list with an odd index to the new list. Here is my code :

```<code>def odd_indices(lst):
  new_lst = [ lst[i] for i in lst if (i + 2) % 2 != 0 ]
  return new_lst
</code>```

What am I doing wrong?

答:
You might want to take the index instead of the value itself. The list lst contains values and not indices. enumerate helps generating indices. Do like below.

```<code>def odd_indices(lst):
  new_lst = [ v for i, v in enumerate(lst) if i% 2 != 0 ]
  return new_lst

print(odd_indices([1, 2, 4, 5]))
</code>```

Body:
I have a given list and I want to add all elements of that list with an odd index to the new list. Here is my code :

def odd_indices(lst):
  new_lst = [ lst[i] for i in lst if (i + 2) % 2 != 0 ]
  return new_lst

What am I doing wrong?

Body:
You might want to take the index instead of the value itself. The list lst contains values and not indices. enumerate helps generating indices. Do like below.

def odd_indices(lst):
  new_lst = [ v for i, v in enumerate(lst) if i% 2 != 0 ]
  return new_lst

print(odd_indices([1, 2, 4, 5]))


问:
Is there a way to trap the MouseLeftButtonDown event on a transparent background in WPF?
I build a WPF UserControl.  This control has a transparent background.  I want to trap the MouseLeftButtonDown event, even when this event happens on the transparent background.  If I change the background to "White", or another color, the event is trapped as expected.

Is there a way to tell the control to listen for the event, even if it happens over a transparent area?

Thanks.

答:
There is a difference in specifying no Background and specifying a transparent background:
{x:Null} vs. Transparent?</p>


问:
keyboard Overlap On login screen -Xamarin .forms
I have a xamarin forms app with a login screen.The problem I am facing is keyboard overlap when user enter details.The Username and password entering field is inside frame.

What I am getting

What I want

My Xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             BackgroundColor="#173F5F"
             x:Class="app.Login">
    <ScrollView>
        <RelativeLayout>
            <Image Source="backgrnd.png" Aspect="Fill"
                RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
                RelativeLayout.HeightConstraint=     "{ConstraintExpression Type=RelativeToParent, Property=Height}"/>
            <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"  RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
             RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height}">
                <StackLayout Orientation="Vertical"  VerticalOptions="StartAndExpand" Margin="15,30,15,0">
                    <Image Source="logo.png" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="150" WidthRequest="150"></Image>
                    <Image Source="backlogo.png" HorizontalOptions="Center" VerticalOptions="Center" ></Image>
                </StackLayout>
                <StackLayout VerticalOptions="End"  Margin="15,0,15,50"  >
                    <Frame  BackgroundColor="Snow" OutlineColor="Snow" HasShadow="True"  HorizontalOptions="FillAndExpand"  Padding="10,10,10,10"
                            CornerRadius="5"
                                Margin="15,10,15,0">
                        <StackLayout VerticalOptions="End" >
                            <StackLayout Orientation="Horizontal">
                                <Image Source="userlogo.png" HorizontalOptions="Start" HeightRequest="30" WidthRequest="30"></Image>
                                <Entry TextColor="Black"
                        x:Name="userName"
                        PlaceholderColor="Gray"
                        ReturnType="Next"
                        BackgroundColor="Snow"
                        Placeholder="User ID"
                        VerticalOptions="Center"
                        HorizontalOptions="FillAndExpand"/>
                            </StackLayout>
                            <StackLayout Orientation="Horizontal">
                                <Image Source="locklogo.png" HorizontalOptions="Start" HeightRequest="30" WidthRequest="30"></Image>
                                <Entry TextColor="Black"
                         PlaceholderColor="Gray"
                        x:Name="password"
                        BackgroundColor="Snow"
                        VerticalOptions="Center"
                        Placeholder="Password"
                        IsPassword="true"
                        HorizontalOptions="FillAndExpand"/>
                            </StackLayout>
                            <Grid>
                                <Button x:Name="LoginButton" BackgroundColor="#4080a6" TextColor="White" Text="Sign In" Clicked="Login_Clicked"  BorderRadius="7" BorderColor="#4080a6" BorderWidth = "2" HorizontalOptions="FillAndExpand" />
                            </Grid>
                        </StackLayout>
                    </Frame>
                </StackLayout>
            </StackLayout>
        </RelativeLayout>
    </ScrollView>
</ContentPage>
</code>```

I tried Xam.Plugins.Forms.KeyboardOverlap but it doesnt solved my problem.Any help is appreciated.

答:
Take a look at the answer here
I tried option 2 on Android and it works fine.

For your case,
try to add this Code to your page class

```<code>  protected override void OnAppearing()
    {
        base.OnAppearing();
        userName.Focused += InputFocused;
        password.Focused += InputFocused;
        userName.Unfocused += InputUnfocused;
        password.Unfocused += InputUnfocused;
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        userName.Focused -= InputFocused;
        password.Focused -= InputFocused;
        userName.Unfocused -= InputUnfocused;
        password.Unfocused -= InputUnfocused;
    }
    void InputFocused(object sender, EventArgs args)
    {
        Content.LayoutTo(new Rectangle(0, -270, Content.Bounds.Width, Content.Bounds.Height));
    }

    void InputUnfocused(object sender, EventArgs args)
    {
        Content.LayoutTo(new Rectangle(0, 0, Content.Bounds.Width, Content.Bounds.Height));
    }
</code>```

Update

this code should be working on both Android and IOS

Body:
I have a xamarin forms app with a login screen.The problem I am facing is keyboard overlap when user enter details.The Username and password entering field is inside frame.

What I am getting

What I want

My Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             BackgroundColor="#173F5F"
             x:Class="app.Login">
    <ScrollView>
        <RelativeLayout>
            <Image Source="backgrnd.png" Aspect="Fill"
                RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
                RelativeLayout.HeightConstraint=     "{ConstraintExpression Type=RelativeToParent, Property=Height}"/>
            <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"  RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
             RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height}">
                <StackLayout Orientation="Vertical"  VerticalOptions="StartAndExpand" Margin="15,30,15,0">
                    <Image Source="logo.png" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="150" WidthRequest="150"></Image>
                    <Image Source="backlogo.png" HorizontalOptions="Center" VerticalOptions="Center" ></Image>
                </StackLayout>
                <StackLayout VerticalOptions="End"  Margin="15,0,15,50"  >
                    <Frame  BackgroundColor="Snow" OutlineColor="Snow" HasShadow="True"  HorizontalOptions="FillAndExpand"  Padding="10,10,10,10"
                            CornerRadius="5"
                                Margin="15,10,15,0">
                        <StackLayout VerticalOptions="End" >
                            <StackLayout Orientation="Horizontal">
                                <Image Source="userlogo.png" HorizontalOptions="Start" HeightRequest="30" WidthRequest="30"></Image>
                                <Entry TextColor="Black"
                        x:Name="userName"
                        PlaceholderColor="Gray"
                        ReturnType="Next"
                        BackgroundColor="Snow"
                        Placeholder="User ID"
                        VerticalOptions="Center"
                        HorizontalOptions="FillAndExpand"/>
                            </StackLayout>
                            <StackLayout Orientation="Horizontal">
                                <Image Source="locklogo.png" HorizontalOptions="Start" HeightRequest="30" WidthRequest="30"></Image>
                                <Entry TextColor="Black"
                         PlaceholderColor="Gray"
                        x:Name="password"
                        BackgroundColor="Snow"
                        VerticalOptions="Center"
                        Placeholder="Password"
                        IsPassword="true"
                        HorizontalOptions="FillAndExpand"/>
                            </StackLayout>
                            <Grid>
                                <Button x:Name="LoginButton" BackgroundColor="#4080a6" TextColor="White" Text="Sign In" Clicked="Login_Clicked"  BorderRadius="7" BorderColor="#4080a6" BorderWidth = "2" HorizontalOptions="FillAndExpand" />
                            </Grid>
                        </StackLayout>
                    </Frame>
                </StackLayout>
            </StackLayout>
        </RelativeLayout>
    </ScrollView>
</ContentPage>

I tried Xam.Plugins.Forms.KeyboardOverlap but it doesnt solved my problem.Any help is appreciated.

Body:
Take a look at the answer here
I tried option 2 on Android and it works fine.

For your case,
try to add this Code to your page class

  protected override void OnAppearing()
    {
        base.OnAppearing();
        userName.Focused += InputFocused;
        password.Focused += InputFocused;
        userName.Unfocused += InputUnfocused;
        password.Unfocused += InputUnfocused;
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        userName.Focused -= InputFocused;
        password.Focused -= InputFocused;
        userName.Unfocused -= InputUnfocused;
        password.Unfocused -= InputUnfocused;
    }
    void InputFocused(object sender, EventArgs args)
    {
        Content.LayoutTo(new Rectangle(0, -270, Content.Bounds.Width, Content.Bounds.Height));
    }

    void InputUnfocused(object sender, EventArgs args)
    {
        Content.LayoutTo(new Rectangle(0, 0, Content.Bounds.Width, Content.Bounds.Height));
    }

Update

this code should be working on both Android and IOS


答:
If as you said in the comments, you want always the common columns from the bottom table. You can do a simple join losing common cloums from df1 before the join.

```<code>joined_df = df1.drop("some_common_columns").join(df2,Seq("uid"))
</code>```

This will leave you with joined data with only the common cloums from df1 and the uncommon of both dfs in the new joined_df

Title: Spark Join dataframes and conditionally update columns

Body:
Hi I have 2 spark dataframes.

The first one:

+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+
|cluster_socio_6|cluster_socio_7|country|latitude|longitude|last_update|         uid|segment_comp_11|cluster_comp_170|
+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+
|              2|              2|     IT|  41.884|  13.5204| 2019-04-15|d@rNdBkkN-p3|             10|               3|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|Ie2Bbs9PUR8h|             15|               4|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|Jk2Bbs9PUR8h|             15|               4|
+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+

and second one:

+---------------+---------------+-------+--------+---------+-----------+------------+
|cluster_socio_6|cluster_socio_7|country|latitude|longitude|last_update|         uid|
+---------------+---------------+-------+--------+---------+-----------+------------+
|              4|             17|     IT| 40.8413|  14.2008| 2019-04-16|ASBuzjKa6nIB|
|              2|              2|     IT|  41.884|  15.5204| 2019-04-16|d@rNdBkkN-p3|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-16|Ie2Bbs9PUR8h|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|xyzBbs9PUR8h|
+---------------+---------------+-------+--------+---------+-----------+------------+

apart country,latitude,longitude,last_update and uid, the bottom Df could have different columns added.

The idea is to make a full join by uid, update the common columns and keep the uncommon columns.

How could I accomplish this task?
Thanks.

Body:
If as you said in the comments, you want always the common columns from the bottom table. You can do a simple join losing common cloums from df1 before the join.

joined_df = df1.drop("some_common_columns").join(df2,Seq("uid"))

This will leave you with joined data with only the common cloums from df1 and the uncommon of both dfs in the new joined_df


问:
Achieve pixel perfect on Canvas?
I want to make exact 1-pixel thick line without distortions. (means not appeared as 2-pixel lines or 1.5-pixel lines, etc) Because it seems like the Canvas just can't stand Pixel Perfect at times.</p>

答:
It is also depends on CanvasScaler setting, make sure that screen/canvas output is exactly at scale 1x.

Confirm that canvas final scale is all 1x

Also confirm that your displaying game window has 1x scale so that 1 pixel show up nicely too!

(View full unscaled image in another window if sprite in above image appear jagged)

For canvas scaler setting, if you use it in other mode such as "Scale with screen size", and its reference resolution did not match current game window, it will result in non 1x scaling.

If scale is non uniform, jagged or blurry line will start to appear on canvas.
Notice the middle sword sprite.

Canvas' pixel perfect tick box helped nothing so far.

Title: Achieve pixel perfect on Canvas?


问:
JavaScript: Traversing and Reversing Singly-Linked Lists and Converting Between SLLs and Numbers
INTRO
Today, while doing a mock interview with a Facebook JavaScript problem, I blanked out on how to handle singly-linked lists.  The code I had so far is simply a function that takes 2 linked lists and returns another linked list.  My plan is below.

QUESTION
You are given two non-empty linked lists of arbitrary length representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:
  342 + 465 = 807.

PLAN

Copy each number from the first linked list into an array in order.

Reverse the array.

Convert the array to a string then to an integer and store this in a variable.

Repeat this for the second linked list.

Sum the two numbers and store this value in a variable.

Convert this sum into a string.

Use Array.from on this string to convert it into an array then reverse the array.

?

Return the new linked list.

```<code>/*
 * Definition for singly-linked list.
 * function ListNode(val)
 * {
 *  this.val = val;
 *  this.next = null;
 * }
 */

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

var addTwoNumbers = function(l1, l2)
{

};

</code>```

答:
When dealing with linked lists, you can easily take a recursive approach. It tends to keep the code simple. For adding two linked lists together all you need to do is the following:

Take a node

Add the two values together

Keep that value in a new node.

Move over to the next node and repeat from step 1.

This is the general outline. There are few edgecases to keep track of

the sum of both numbers is greater than 10 - in that case, you have to carry the extra over to the next sum operation. So, for a sum of 12 you need to only keep 2 and carry 1 over.

One list is exhausted, but the other still has values - just treat is as having a value of 0 - that will not effect the result. If you try to sum 1 and 0 you'd get 1, which is the correct thing to have.

Both lists are exhausted but there is a value carried over - same as above. If you summed lists that were 9 and 3, then you'd get 2 and the next iteration would have no more lists but a carryover of 1.

/*
 * Definition for singly-linked list.
 */
function ListNode(val)
{
  this.val = val;
  this.next = null;
}

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2)
{
  return recursivelyAddLists(l1, l2, 0);
};

/*
 * Recursively add two lists together producing a new list for each digit
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @param {number} carryover
 * @return {ListNode}
 */
function recursivelyAddLists(l1, l2, carryover)
{
  //you can also safely assume that the carryover is always present.
  //But adding a default is a good practice
  carryover = carryover || 0;

  //if there is nothing to add, we are finished
  if (l1 == null && l2 == null && carryover === 0) return null;

  //provide fallback in case at least one or both lists are exhausted
  l1 = l1 || new ListNode(0);
  l2 = l2 || new ListNode(0);

  //calculate the sum of both nodes with any potential leftover from previous sums
  var sum = l1.val + l2.val + carryover;

  //clamp to only single digit numbers
  var newVal = sum % 10

  //the amount to move add with the next nodes
  var newCarryover = Math.floor(sum / 10);

  //create the result node
  var newList = new ListNode(newVal);

  //recursively determine what the next node is
  newList.next = recursivelyAddLists(l1.next, l2.next, newCarryover);

  //finish
  return newList
}

//use the sample data for a test
var input1 = new ListNode(2);
input1.next = new ListNode(4);
input1.next.next = new ListNode(3);

var input2 = new ListNode(5);
input2.next = new ListNode(6);
input2.next.next = new ListNode(4);

console.log(debugPrintList(addTwoNumbers(input1, input2)))

//simple function to recursively collect the content of the list to a string
function debugPrintList(list) {
  if (list.next == null) return list.val;
  return list.val + " -> " + debugPrintList(list.next);
}```
</div>
</div>
</p>

<p>I have created a new function to do the recursive addition in order to preserve the interface of the first one. The only difference is the <code>carryover</code> parameter. However, it's possible to just add the parameter and default it to zero and the thing will still work. However, given it's an interview, they might penalise you for this change. Still, for completeness sake, here is what this would look like:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*
 * Definition for singly-linked list.
 */
function ListNode(val)
{
  this.val = val;
  this.next = null;
}

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2, carryover) //<- adding the parameter
{
  carryover = carryover || 0;

  if (l1 == null && l2 == null && carryover === 0) return null;

  l1 = l1 || new ListNode(0);
  l2 = l2 || new ListNode(0);

  var sum = l1.val + l2.val + carryover;

  var newVal = sum % 10
  var newCarryover = Math.floor(sum / 10);

  var newList = new ListNode(newVal);

  //recursively calling this same function
  newList.next = addTwoNumbers(l1.next, l2.next, newCarryover);

  return newList
};

//use the sample data for a test
var input1 = new ListNode(2);
input1.next = new ListNode(4);
input1.next.next = new ListNode(3);

var input2 = new ListNode(5);
input2.next = new ListNode(6);
input2.next.next = new ListNode(4);

console.log(debugPrintList(addTwoNumbers(input1, input2)))

//simple function to recursively collect the content of the list to a string
function debugPrintList(list) {
  if (list.next == null) return list.val;
  return list.val + " -> " + debugPrintList(list.next);
}</code>```

One last note - this solution is using ES5 features only. I've based that on the code given. ES6 will not really have a big impact but the most prominent change would be that you don't need to manually give a default to carryover - instead you can simply have recursivelyAddLists(l1, l2, carryover = 0). The other ES6 changes are minor at best - using let and const instead of var and possibly using destructuring to get the value of the node and the next node, so you could do something like

const {val: value1 = 0, next: next1 = null} = l1 || {}
const {val: value2 = 0, next: next2 = null} = l2 || {}
```

However, I personally find that less readable.

Body:
INTRO
Today, while doing a mock interview with a Facebook JavaScript problem, I blanked out on how to handle singly-linked lists.  The code I had so far is simply a function that takes 2 linked lists and returns another linked list.  My plan is below.

QUESTION
You are given two non-empty linked lists of arbitrary length representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:
  342 + 465 = 807.

PLAN

Copy each number from the first linked list into an array in order.

Reverse the array.

Convert the array to a string then to an integer and store this in a variable.

Repeat this for the second linked list.

Sum the two numbers and store this value in a variable.

Convert this sum into a string.

Use Array.from on this string to convert it into an array then reverse the array.

?

Return the new linked list.

/*
 * Definition for singly-linked list.
 * function ListNode(val)
 * {
 *  this.val = val;
 *  this.next = null;
 * }
 */

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

var addTwoNumbers = function(l1, l2)
{

};

Body:
When dealing with linked lists, you can easily take a recursive approach. It tends to keep the code simple. For adding two linked lists together all you need to do is the following:

Take a node

Add the two values together

Keep that value in a new node.

Move over to the next node and repeat from step 1.

This is the general outline. There are few edgecases to keep track of

the sum of both numbers is greater than 10 - in that case, you have to carry the extra over to the next sum operation. So, for a sum of 12 you need to only keep 2 and carry 1 over.

One list is exhausted, but the other still has values - just treat is as having a value of 0 - that will not effect the result. If you try to sum 1 and 0 you'd get 1, which is the correct thing to have.

Both lists are exhausted but there is a value carried over - same as above. If you summed lists that were 9 and 3, then you'd get 2 and the next iteration would have no more lists but a carryover of 1.

/*
 * Definition for singly-linked list.
 */
function ListNode(val)
{
  this.val = val;
  this.next = null;
}

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2)
{
  return recursivelyAddLists(l1, l2, 0);
};

/*
 * Recursively add two lists together producing a new list for each digit
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @param {number} carryover
 * @return {ListNode}
 */
function recursivelyAddLists(l1, l2, carryover)
{
  //you can also safely assume that the carryover is always present.
  //But adding a default is a good practice
  carryover = carryover || 0;

  //if there is nothing to add, we are finished
  if (l1 == null && l2 == null && carryover === 0) return null;

  //provide fallback in case at least one or both lists are exhausted
  l1 = l1 || new ListNode(0);
  l2 = l2 || new ListNode(0);

  //calculate the sum of both nodes with any potential leftover from previous sums
  var sum = l1.val + l2.val + carryover;

  //clamp to only single digit numbers
  var newVal = sum % 10

  //the amount to move add with the next nodes
  var newCarryover = Math.floor(sum / 10);

  //create the result node
  var newList = new ListNode(newVal);

  //recursively determine what the next node is
  newList.next = recursivelyAddLists(l1.next, l2.next, newCarryover);

  //finish
  return newList
}

//use the sample data for a test
var input1 = new ListNode(2);
input1.next = new ListNode(4);
input1.next.next = new ListNode(3);

var input2 = new ListNode(5);
input2.next = new ListNode(6);
input2.next.next = new ListNode(4);

console.log(debugPrintList(addTwoNumbers(input1, input2)))

//simple function to recursively collect the content of the list to a string
function debugPrintList(list) {
  if (list.next == null) return list.val;
  return list.val + " -> " + debugPrintList(list.next);
}

I have created a new function to do the recursive addition in order to preserve the interface of the first one. The only difference is the carryover parameter. However, it's possible to just add the parameter and default it to zero and the thing will still work. However, given it's an interview, they might penalise you for this change. Still, for completeness sake, here is what this would look like:

/*
 * Definition for singly-linked list.
 */
function ListNode(val)
{
  this.val = val;
  this.next = null;
}

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2, carryover) //<- adding the parameter
{
  carryover = carryover || 0;

  if (l1 == null && l2 == null && carryover === 0) return null;

  l1 = l1 || new ListNode(0);
  l2 = l2 || new ListNode(0);

  var sum = l1.val + l2.val + carryover;

  var newVal = sum % 10
  var newCarryover = Math.floor(sum / 10);

  var newList = new ListNode(newVal);

  //recursively calling this same function
  newList.next = addTwoNumbers(l1.next, l2.next, newCarryover);

  return newList
};

//use the sample data for a test
var input1 = new ListNode(2);
input1.next = new ListNode(4);
input1.next.next = new ListNode(3);

var input2 = new ListNode(5);
input2.next = new ListNode(6);
input2.next.next = new ListNode(4);

console.log(debugPrintList(addTwoNumbers(input1, input2)))

//simple function to recursively collect the content of the list to a string
function debugPrintList(list) {
  if (list.next == null) return list.val;
  return list.val + " -> " + debugPrintList(list.next);
}

One last note - this solution is using ES5 features only. I've based that on the code given. ES6 will not really have a big impact but the most prominent change would be that you don't need to manually give a default to carryover - instead you can simply have recursivelyAddLists(l1, l2, carryover = 0). The other ES6 changes are minor at best - using let and const instead of var and possibly using destructuring to get the value of the node and the next node, so you could do something like

const {val: value1 = 0, next: next1 = null} = l1 || {}
const {val: value2 = 0, next: next2 = null} = l2 || {}

However, I personally find that less readable.


问:
How to convert the column in US million dollars in pandas?
I have a column called collection as follow

collection : $5,345,677, 46836214, $533,316,061, " ", 29200000

Column values have both in US dollar and without dollars. Also, it has NAN. I want to change into US Dollar in million

I used to convert as follow but not successful

```<code>df['Boxoffice in US$ (mil)'] = (df2['collection'].astype(float)/1000000).round(2).astype(str)
</code>```

Getting this error: could not convert string to float: '$5,345,677'

Please advise

答:
You can refer to the following step:

1.Fill NAN or blank value (white space). You said it has Nan, but i saw " ".

```<code>[in ]: df['collection']
[out]: collection
  0    $5,345,677
  1    46836214
  2    $533,316,061
  3
  4    29200000
[in ]: # if you have Nan, just use method `fillna` instead
       # like df['collection'].fillna('0')
[in ]: df['collection'].replace(r'^\s*$', '0', regex=True)
[out]: collection
  0    $5,345,677
  1    46836214
  2    $533,316,061
  3    0
  4    29200000
</code>```

2.Then covert number to 'US Dollar in million'.

```<code>[in ]: df['collection'].apply(lambda x: ''.join(('$', format(int(x), ','))) if not '$' in x else x)
[out]: collection
  0    $5,345,677
  1    $46,836,214
  2    $533,316,061
  3    $0
  4    $29,200,000
</code>```

I do hope this can help!

Body:
I have a column called collection as follow

collection : $5,345,677, 46836214, $533,316,061, " ", 29200000

Column values have both in US dollar and without dollars. Also, it has NAN. I want to change into US Dollar in million

I used to convert as follow but not successful

df['Boxoffice in US$ (mil)'] = (df2['collection'].astype(float)/1000000).round(2).astype(str)

Getting this error: could not convert string to float: '$5,345,677'

Please advise

Body:
You can refer to the following step:

1.Fill NAN or blank value (white space). You said it has Nan, but i saw " ".

[in ]: df['collection']
[out]: collection
  0    $5,345,677
  1    46836214
  2    $533,316,061
  3
  4    29200000
[in ]: # if you have Nan, just use method `fillna` instead
       # like df['collection'].fillna('0')
[in ]: df['collection'].replace(r'^\s*$', '0', regex=True)
[out]: collection
  0    $5,345,677
  1    46836214
  2    $533,316,061
  3    0
  4    29200000

2.Then covert number to 'US Dollar in million'.

[in ]: df['collection'].apply(lambda x: ''.join(('$', format(int(x), ','))) if not '$' in x else x)
[out]: collection
  0    $5,345,677
  1    $46,836,214
  2    $533,316,061
  3    $0
  4    $29,200,000

I do hope this can help!


问:
Toggle class with delay on hover
I am opening my submenu with adding the class reveal to it's parent. What I want to achieve is when I hover over a parent, if no "active" hover is going on, to open the submenu immediately, but if a submenu is already shown, then wait 1 second before it opens a new one. I want this because of "bad" mouse movement for it to wait in case the mouse leaves the submenu/parent to see if it re-enters in 1 second.

I know there are a bunch of similar threads, but I already did my attempt and can't see right now what I'm doing wrong:

$('.menu > li').hover(function() {
  var ele = $(this);
  if ($('.menu li.reveal').length > 0) {
    var t = setTimeout(function() {
      if (ele.hover()) {
        $('.menu li.reveal').removeClass('reveal');
        ele.addClass('reveal');
      }
    }, 1000);
  } else {
    ele.addClass('reveal');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
  <li>
    Link lv1
    <ul class="submenu">
      <li>Link lv2</li>
      <li>Link lv2</li>
      <li>Link lv2</li>
    </ul>
  </li>
  <li>
    Link lv1
    <ul class="submenu">
      <li>Link lv2</li>
      <li>Link lv2</li>
      <li>Link lv2</li>
    </ul>
  </li>
  <li>
    Link lv1
    <ul class="submenu">
      <li>Link lv2</li>
      <li>Link lv2</li>
      <li>Link lv2</li>
    </ul>
  </li>
</ul></code>```

答:
let timers = [], open = false;

$('.menu > li').hover(function() {
  if (this.dataset.timer) {
    timers.forEach(t => clearTimeout(t));
    clearTimeout(parseInt(this.dataset.timer));
    delete this.dataset.timer;
    open = false;
  } else if ($(this).hasClass('reveal')) {
    this.dataset.timer = setTimeout(() => {
      $(this).removeClass('reveal');
      delete this.dataset.timer;
      open = false;
    }, 1000);
    open = true;
  } else if (open) {
    timers.push(setTimeout(() => {
      $('.menu > li').removeClass('reveal');
      $(this).addClass('reveal');
    }, 1000));
  } else {
    $('.menu > li').removeClass('reveal');
    $(this).addClass('reveal');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.submenu {
  display: none;
}

.menu > li.reveal ul {
  display: block;
}</code>```

    Link lv1

Link lv2

Link lv2

Link lv2

    Link lv1

Link lv2

Link lv2

Link lv2

    Link lv1

Link lv2

Link lv2

Link lv2

```
</div>
</div>
</p>

<p>A more styled version:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let timers = [], open = false;

$('.nav-item').hover(function() {
  if (this.dataset.timer) {
    timers.forEach(t => clearTimeout(t));
    clearTimeout(parseInt(this.dataset.timer));
    delete this.dataset.timer;
    open = false;
  } else if ($(this).hasClass('reveal')) {
    this.dataset.timer = setTimeout(() => {
      $(this).removeClass('reveal');
      delete this.dataset.timer;
      open = false;
    }, 1000);
    open = true;
  } else if (open) {
    timers.push(setTimeout(() => {
      $('.nav-item').removeClass('reveal');
      $(this).addClass('reveal');
    }, 1000));
  } else {
    $('.nav-item').removeClass('reveal');
    $(this).addClass('reveal');
  }
});</code>```

a {
  font-family: sans-serif;
  text-decoration: none;
  color: black;
}

a:hover {
  opacity: 0.5;
}

nav {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  text-align: center;
}

.nav-item {
  display: inline-block;
  list-style: none;
}

.submenu {
  display: none;
  list-style: none;
}

.nav-item ul:focus-within {
  display: block;
}

.nav-item.reveal ul {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div class="nav-item">
    Link lv1
    <ul class="submenu">
      <li>Link lv2</li>
      <li>Link lv2</li>
      <li>Link lv2</li>
    </ul>
  </div>
  <div class="nav-item">
    Link lv1
    <ul class="submenu">
      <li>Link lv2</li>
      <li>Link lv2</li>
      <li>Link lv2</li>
    </ul>
  </div>
  <div class="nav-item">
    Link lv1
    <ul class="submenu">
      <li>Link lv2</li>
      <li>Link lv2</li>
      <li>Link lv2</li>
    </ul>
  </div>
</nav></code>```

Title: Toggle class with delay on hover

Body:
I am opening my submenu with adding the class reveal to it's parent. What I want to achieve is when I hover over a parent, if no "active" hover is going on, to open the submenu immediately, but if a submenu is already shown, then wait 1 second before it opens a new one. I want this because of "bad" mouse movement for it to wait in case the mouse leaves the submenu/parent to see if it re-enters in 1 second.

I know there are a bunch of similar threads, but I already did my attempt and can't see right now what I'm doing wrong:

$('.menu > li').hover(function() {
  var ele = $(this);
  if ($('.menu li.reveal').length > 0) {
    var t = setTimeout(function() {
      if (ele.hover()) {
        $('.menu li.reveal').removeClass('reveal');
        ele.addClass('reveal');
      }
    }, 1000);
  } else {
    ele.addClass('reveal');
  }
});

    Link lv1

Link lv2

Link lv2

Link lv2

    Link lv1

Link lv2

Link lv2

Link lv2

    Link lv1

Link lv2

Link lv2

Link lv2

Body:
let timers = [], open = false;

$('.menu > li').hover(function() {
  if (this.dataset.timer) {
    timers.forEach(t => clearTimeout(t));
    clearTimeout(parseInt(this.dataset.timer));
    delete this.dataset.timer;
    open = false;
  } else if ($(this).hasClass('reveal')) {
    this.dataset.timer = setTimeout(() => {
      $(this).removeClass('reveal');
      delete this.dataset.timer;
      open = false;
    }, 1000);
    open = true;
  } else if (open) {
    timers.push(setTimeout(() => {
      $('.menu > li').removeClass('reveal');
      $(this).addClass('reveal');
    }, 1000));
  } else {
    $('.menu > li').removeClass('reveal');
    $(this).addClass('reveal');
  }
});

.submenu {
  display: none;
}

.menu > li.reveal ul {
  display: block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
  <li>
    <a href="#">Link lv1</a>
    <ul class="submenu">
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Link lv1</a>
    <ul class="submenu">
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Link lv1</a>
    <ul class="submenu">
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
    </ul>
  </li>
</ul>

A more styled version:

let timers = [], open = false;

$('.nav-item').hover(function() {
  if (this.dataset.timer) {
    timers.forEach(t => clearTimeout(t));
    clearTimeout(parseInt(this.dataset.timer));
    delete this.dataset.timer;
    open = false;
  } else if ($(this).hasClass('reveal')) {
    this.dataset.timer = setTimeout(() => {
      $(this).removeClass('reveal');
      delete this.dataset.timer;
      open = false;
    }, 1000);
    open = true;
  } else if (open) {
    timers.push(setTimeout(() => {
      $('.nav-item').removeClass('reveal');
      $(this).addClass('reveal');
    }, 1000));
  } else {
    $('.nav-item').removeClass('reveal');
    $(this).addClass('reveal');
  }
});

a {
  font-family: sans-serif;
  text-decoration: none;
  color: black;
}

a:hover {
  opacity: 0.5;
}

nav {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  text-align: center;
}

.nav-item {
  display: inline-block;
  list-style: none;
}

.submenu {
  display: none;
  list-style: none;
}

.nav-item ul:focus-within {
  display: block;
}

.nav-item.reveal ul {
  display: block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div class="nav-item">
    <a href="#">Link lv1</a>
    <ul class="submenu">
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
    </ul>
  </div>
  <div class="nav-item">
    <a href="#">Link lv1</a>
    <ul class="submenu">
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
    </ul>
  </div>
  <div class="nav-item">
    <a href="#">Link lv1</a>
    <ul class="submenu">
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
      <li><a href="#">Link lv2</a></li>
    </ul>
  </div>
</nav>


答:
Here you go!

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

```

Title: Images stretched in flex container but cannot use align-self-center

Body:
Here you go!

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="col-3 d-flex flex-column">
    <img class="align-self-start" src="https://dummyimage.com/600x400/000/fff"/>
</div>


问:
Loading the WCF configuration from different files on the client side
A common problem in WCF that many people face is the impossibility of loading the client configuration from different configuration files.

This is a common scenario  when the developer wants to deploy some binaries with along with an independent configuration file (Which may be in a resource file also or another configuration file) to avoid modifying the main configuration file.

I have found two references:

http://weblogs.asp.net/cibrax/archive/2007/10/19/loading-the-wcf-configuration-from-different-files-on-the-client-side.aspx

http://social.msdn.microsoft.com/forums/en-US/wcf/thread/f33e620a-e332-4fd4-ae21-88c750437355/

which is the best solution about it ??

any suggestions for a the best solution ? I use VS 2008 and .NET 3.5.

答: The first link (blog post) is more relevant to your situation. Your only other option would be to use WCF Discovery to discover your endpoint and configuration at runtime, but that approach is certainly more work and can get complicated in managed mode.</p>


答:
Use enumerate to work on index

```<code>>>> lst = [0,1,2,3,4,5,6,7,8,9,10]
>>> [value for index, value in enumerate(lst) if index%2 != 0]
[1, 3, 5, 7, 9] # output odd index values
</code>```

What is the mistake you have done?

Iterating through list.

In each iteration you will get the element of that list.

you are using that element as the index of the list.

EX:

```<code>lst = [1,2,3,4,5,6,7,8,9,10]
</code>```

In above lst, the last element is 10.

```<code>lst[10] ---> which does not exists. # Throws out of index range error
</code>```

Title: What am I doing wrong? It shows me that the list index is out of range

Body:
Use enumerate to work on index

>>> lst = [0,1,2,3,4,5,6,7,8,9,10]
>>> [value for index, value in enumerate(lst) if index%2 != 0]
[1, 3, 5, 7, 9] # output odd index values

What is the mistake you have done?

Iterating through list.

In each iteration you will get the element of that list.

you are using that element as the index of the list.

EX:

lst = [1,2,3,4,5,6,7,8,9,10]

In above lst, the last element is 10.

lst[10] ---> which does not exists. # Throws out of index range error


问:
Mock css-modules in Jest snapshot
I have a problem with creating snapshot test for my component. I followed many anwsers like:

Mocking css modules in jest

https://github.com/facebook/jest/issues/1347

https://jestjs.io/docs/en/webpack

But none of the solutions work for me (maybe it is because my files are in TypeScript not JS but I have no idea).
My component is UploadFile.tsx :

```<code>import * as React from 'react';
import css from './UploadFile.scss';

interface Props {
  uploadFile(data: FormData): void;
  resetUploadedCsv(): void;
}

export class UploadFile extends React.Component<Props> {
  public handleUploadFile = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.props.resetUploadedCsv();
    const data = new FormData();
    const file = event.target.files[0];
    data.append('file', file);
    this.props.uploadFile(data);
  }

  public render() {
    return (
      <div>
        <label className={css.uploadButton}>
          Upload
          <input
            id='Upload'
            type='file'
            accept='.csv'
            onChange={this.handleUploadFile}
          />
        </label>
      </div>
    );
  }
}
</code>```

And my test is:

```<code>import * as React from 'react';
import * as renderer from 'react-test-renderer';
import { UploadFile} from '../UploadFile';

it('renders correctly', () => {
  const fakeProps = {
    uploadFile: (data: FormData) => console.log(data),
    resetUploadedCsv: () => console.log('reset'),
  };
  const tree = renderer.create(<UploadFile{...fakeProps} />).toJSON();
  expect(tree).toMatchSnapshot();
});
</code>```

I get an error:

TypeError: Cannot read property 'uploadButton' of undefined

I tried to use jest-css-modules library and then in package.json:
      "\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/jest-css-modules"

I tried to use identity-obj-proxy as well as many combinations in moduleNameMapper. None of the solutions from the links above work for me...

答:
As you are using TypeScript your import is wrong, should be:</p>

```<code>import * as css from './UploadFile.scss';
</code>```

Title: Mock css-modules in Jest snapshot

Body:
I have a problem with creating snapshot test for my component. I followed many anwsers like:

Mocking css modules in jest

https://github.com/facebook/jest/issues/1347

https://jestjs.io/docs/en/webpack

But none of the solutions work for me (maybe it is because my files are in TypeScript not JS but I have no idea).
My component is UploadFile.tsx :

import * as React from 'react';
import css from './UploadFile.scss';

interface Props {
  uploadFile(data: FormData): void;
  resetUploadedCsv(): void;
}

export class UploadFile extends React.Component<Props> {
  public handleUploadFile = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.props.resetUploadedCsv();
    const data = new FormData();
    const file = event.target.files[0];
    data.append('file', file);
    this.props.uploadFile(data);
  }

  public render() {
    return (

          Upload
          <input
            id='Upload'
            type='file'
            accept='.csv'
            onChange={this.handleUploadFile}
          />

    );
  }
}

And my test is:

import * as React from 'react';
import * as renderer from 'react-test-renderer';
import { UploadFile} from '../UploadFile';

it('renders correctly', () => {
  const fakeProps = {
    uploadFile: (data: FormData) => console.log(data),
    resetUploadedCsv: () => console.log('reset'),
  };
  const tree = renderer.create(<UploadFile{...fakeProps} />).toJSON();
  expect(tree).toMatchSnapshot();
});

I get an error:

TypeError: Cannot read property 'uploadButton' of undefined

I tried to use jest-css-modules library and then in package.json:
      "\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/jest-css-modules"

I tried to use identity-obj-proxy as well as many combinations in moduleNameMapper. None of the solutions from the links above work for me...

Body:
As you are using TypeScript your import is wrong, should be:

import * as css from './UploadFile.scss';


问:
Getting wrong when i use x:bind in uwp: invalid binding path err
I try to use x:bind function to display String which using String.Concat() to connect two string. I follow the instruction from this website: https://learn.microsoft.com/en-us/windows/uwp/data-binding/function-bindings

Since this is the first ask question on Stack Overflow, if the way i ask was wrong, please point it out. thanks (≧∀≦)ゞ

I tried using System.Contact() in the function i created in another namespace and its look good.

xmlns:sys="using:System"
xmlns:local="using:uwpppp.Scenes.ReciteF">

...

<TextBlock Text="{x:Bind sys:String.Concat('hello','123')}"/>

<TextBlock Text="{x:Bind local:Showdetail.GetString('hello','hello2')}"/>
```

<pre class="lang-cs prettyprint-override"><code>public static String GetString(string a, string b)
{
    return String.Concat(a, b);
}
</code>```

Invalid binding path 'sys:String.Concat('hello','123')' : Function parameter '1' is invalid or mismatched

答:
According to the documentation, I think the problem lies in this point:

Overloading is based on the number of arguments, not type, and it will try to match to the first overload with that many arguments

String.Concat has many different overloads and the x:Bind mechanism most likely first finds the (object,object) overload and that causes the error you are seeing:

```<code>Invalid or missmatched parameter at position '1'.
</code>```

In case of your custom method, you have only one overload so it can clearly use the (string, string) parameters.

Body:
I try to use x:bind function to display String which using String.Concat() to connect two string. I follow the instruction from this website: https://learn.microsoft.com/en-us/windows/uwp/data-binding/function-bindings

Since this is the first ask question on Stack Overflow, if the way i ask was wrong, please point it out. thanks (≧∀≦)ゞ

I tried using System.Contact() in the function i created in another namespace and its look good.

xmlns:sys="using:System"
xmlns:local="using:uwpppp.Scenes.ReciteF">

...

<TextBlock Text="{x:Bind sys:String.Concat('hello','123')}"/>

<TextBlock Text="{x:Bind local:Showdetail.GetString('hello','hello2')}"/>

public static String GetString(string a, string b)
{
    return String.Concat(a, b);
}

Invalid binding path 'sys:String.Concat('hello','123')' : Function parameter '1' is invalid or mismatched

Body:
According to the documentation, I think the problem lies in this point:

Overloading is based on the number of arguments, not type, and it will try to match to the first overload with that many arguments

String.Concat has many different overloads and the x:Bind mechanism most likely first finds the (object,object) overload and that causes the error you are seeing:

Invalid or missmatched parameter at position '1'.

In case of your custom method, you have only one overload so it can clearly use the (string, string) parameters.


问:
Adding CSS file in ADF JSF page
I have created jsf page

```<code><f:view>

 <af:document id="d1">
   <f:facet name="metaContainer">
   <af:resource type="css">
     af|inputText :: content
     {
     color:Red;
     }
</af:resource>
  </f:facet>

 <af:form id="f1">
  <af:panelHeader text="Customer" id="ph1">

    <af:selectOneRadio label="Gender"
                       requiredMessageDetail="Must Provide Gender"
                       id="sor1" layout="horizontal"
                       value="#{CustomerBean.gender}" autoSubmit="true">
      <af:selectItem label="Female" value="F" id="si1"/>
      <af:selectItem label="Male" value="M" id="si2"/>
    </af:selectOneRadio>
  </af:panelHeader>
  <af:inputText label="FirstName" id="it1" value="#{CustomerBean.first}"/>
  <af:inputText label="LastName" id="it2" value="#{CustomerBean.last}"/>
  <af:outputText id="ot1"
                 partialTriggers="sor1" value="#{CustomerBean.gender}"/>
</af:form>
</code>```

I want to apply Red color to all the inputText I am using. We can perform it using CSS. But I am not able to get any output from it. I have also tried

```<code> <f:facet name="metaContainer">
  <af:resource type="css">
     .text-label
     {
     color:Red;
     }
  </af:resource>
  </f:facet>
</code>```

Another way I tried is :

```<code> <f:facet name="metaContainer">
     <af:resource type="css">
      [id=form\:inputText]{
       color: Red;
      }
     </af:resource>
</code>```

But it's not working. Please suggest me the proper way to use CSS code in JSF page in ADF.

答:
You can easily use inlineStyle tag in the adf faces such as panelbox.

For example
inlineStyle="margin-left: 25px;"

Title: Adding CSS file in ADF JSF page

Body:
I have created jsf page

<f:view>

 <af:document id="d1">
   <f:facet name="metaContainer">
   <af:resource type="css">
     af|inputText :: content
     {
     color:Red;
     }
</af:resource>
  </f:facet>

 <af:form id="f1">
  <af:panelHeader text="Customer" id="ph1">

    <af:selectOneRadio label="Gender"
                       requiredMessageDetail="Must Provide Gender"
                       id="sor1" layout="horizontal"
                       value="#{CustomerBean.gender}" autoSubmit="true">
      <af:selectItem label="Female" value="F" id="si1"/>
      <af:selectItem label="Male" value="M" id="si2"/>
    </af:selectOneRadio>
  </af:panelHeader>
  <af:inputText label="FirstName" id="it1" value="#{CustomerBean.first}"/>
  <af:inputText label="LastName" id="it2" value="#{CustomerBean.last}"/>
  <af:outputText id="ot1"
                 partialTriggers="sor1" value="#{CustomerBean.gender}"/>
</af:form>

I want to apply Red color to all the inputText I am using. We can perform it using CSS. But I am not able to get any output from it. I have also tried

 <f:facet name="metaContainer">
  <af:resource type="css">
     .text-label
     {
     color:Red;
     }
  </af:resource>
  </f:facet>

Another way I tried is :

 <f:facet name="metaContainer">
     <af:resource type="css">
      [id=form\:inputText]{
       color: Red;
      }
     </af:resource>

But it's not working. Please suggest me the proper way to use CSS code in JSF page in ADF.


问:
Git alias appending parameters to end
I'm using Git Bash v1.8.1, with a few aliases (for testing):

```<code>[alias]
    ekko = !echo $1 && echo $1
    ekko2 = !sh -c 'echo $1 && echo $1'
</code>```

But when I run them, I see:

```<code>> git ekko master
master
master master
</code>```

And:

```<code>> git ekko2 master
(blank line)
(blank line)
</code>```

My intended behavior is:

```<code>> git ekko master
master
master
</code>```

I'm fairly new to aliases - I'm looking for a way to ensure that my arguments are consumed entirely, and not appended to the end of the alias. Some sleuthing indicates this behavior changed somewhere around Git v1.7.x, and I haven't yet determined exactly how to accomplish this:

Git Alias - Multiple Commands and Parameters

答:
On a Windows 10 machine using the standard command line the character # needs to be appended to the end of the alias and the whole alias wrapped in " characters. Eg.

```<code>[alias]
    ekko = "!echo $1 && echo $1 #"
</code>```

Title: Git alias appending parameters to end

Body:
I'm using Git Bash v1.8.1, with a few aliases (for testing):

[alias]
    ekko = !echo $1 && echo $1
    ekko2 = !sh -c 'echo $1 && echo $1'

But when I run them, I see:

> git ekko master
master
master master

And:

> git ekko2 master
(blank line)
(blank line)

My intended behavior is:

> git ekko master
master
master

I'm fairly new to aliases - I'm looking for a way to ensure that my arguments are consumed entirely, and not appended to the end of the alias. Some sleuthing indicates this behavior changed somewhere around Git v1.7.x, and I haven't yet determined exactly how to accomplish this:

Git Alias - Multiple Commands and Parameters

Body:
On a Windows 10 machine using the standard command line the character # needs to be appended to the end of the alias and the whole alias wrapped in " characters. Eg.

[alias]
    ekko = "!echo $1 && echo $1 #"


问:
Enabling Ajax on Sharepoint
What I have?

I have installed Windows SharePoint Services 3.0 on my PC to work on it locally. I deployed an external Web Part which loads RSS feeds and shows the posts' titles, links and descriptions (RSS Advanced Reader Web Part for SharePoint).

What problem am I facing?

On my machine with WSS 3.0, the Web Part does not work where I had an error message "Ajax is not currently enabled."

Has anyone faced problems like this and found any solutions?

答: Web.Config entries for enabling AJAX for SharePoint 2007</p>

Title: Enabling Ajax on Sharepoint


问:
How to compress multiple files in a folder into the one compressed folder?
I try to automate a repetitive scenario by Powershell script:

I have a compressed (.zip) folder with multiple files (.XML) in it.

My scenario is to:

uncompressed this folder located in: C:\Users\*\Downloads

changed value inside a specific  in each file

compress all the file into a folder with a specific name (format: AppName.Version.zip) that will be located in the same path: C:\Users\*\Downloads.

Questions:

How do I compress the folder again so that by clicking on the compress folder I'll see immediately the files (zipped folder>files) and not a folder then the files (zipped folder>files)

Compress and Expand commands are yelling about the folder name format of and therefore those commands are failed to their job. How do I get over it?

```<code>     $languageString = Read-Host ...
     $replaceString = '<value>' + $languageString
     $file = Get-Childitem "c:\users\*\Downloads\app.version.zip" -Recurse
     $originalFileName = $file.Name
     $absoluteFilePath = $file.FullName
     $rename-item -path $absoluteFilePath -newname translate.zip
     $file = Get-Childitem "c:\users\*\Downloads\translate.zip" -Recurse
     $absoluteFilePath = $file.FullName
     $unzipFilePath = $absoluteFilePath.Substring(0, $absoluteFilePath.LastIndexOf('.'))
     expand-archive -path $absoluteFilePath -destinationpath $unzipFilePath
     $files = @(Get-Childitem "c:\users\*\Downloads\*.xml)
     foreach ($file in $files)
     {
        (Get-Content -path $file.FullName -Raw) -replace '<value>' , $replaceString | Set-Content -Path $file.FullName

    #this line makes problems...

     Compress-Archive -path $unzipFilePath -Destinationpath $unzipFilePath -Force
</code>```

答:
I see it in three steps:
1. unzip in a temporary clean location.
2. change your files there
3. zip that location back.

the code would have the functions:

```<code>function Unzip_archive ($ArchiveFullPath, $Temp_Work_Fld) {
    try {
        #unzip
        Add-Type -assembly 'system.io.compression.filesystem'
        [io.compression.zipfile]::ExtractToDirectory($ArchiveFullPath, $Temp_Work_Fld)
    }
    catch {
        throw "Failed to unzip the artifact"
    }
    Remove-Item $ArchiveFullPath -Force #only if you want to delete the archive
}

function CreateZipArchive($FolderToArchive, $ZipArchiveFullName){
    $source = Get-ChildItem * -Directory | Where-Object {$_.FullName -match "$FolderToArchive"}
    write-host "`nArchiving: $source ........."
    Add-Type -Assembly system.IO.compression.filesystem
    $compressionlevel = [System.IO.Compression.CompressionLevel]::Optimal
    [io.compression.zipfile]::CreateFromDirectory($source, $ZipArchiveFullName, $compressionlevel, $true)
    write-host "nDone !"
}
</code>```

then just call the functions before and after doing your changes in the temporary folder

Body:
I try to automate a repetitive scenario by Powershell script:

I have a compressed (.zip) folder with multiple files (.XML) in it.

My scenario is to:

uncompressed this folder located in: C:\Users\*\Downloads

changed value inside a specific  in each file

compress all the file into a folder with a specific name (format: AppName.Version.zip) that will be located in the same path: C:\Users\*\Downloads.

Questions:

How do I compress the folder again so that by clicking on the compress folder I'll see immediately the files (zipped folder>files) and not a folder then the files (zipped folder>files)

Compress and Expand commands are yelling about the folder name format of and therefore those commands are failed to their job. How do I get over it?

     $languageString = Read-Host ...
     $replaceString = '<value>' + $languageString
     $file = Get-Childitem "c:\users\*\Downloads\app.version.zip" -Recurse
     $originalFileName = $file.Name
     $absoluteFilePath = $file.FullName
     $rename-item -path $absoluteFilePath -newname translate.zip
     $file = Get-Childitem "c:\users\*\Downloads\translate.zip" -Recurse
     $absoluteFilePath = $file.FullName
     $unzipFilePath = $absoluteFilePath.Substring(0, $absoluteFilePath.LastIndexOf('.'))
     expand-archive -path $absoluteFilePath -destinationpath $unzipFilePath
     $files = @(Get-Childitem "c:\users\*\Downloads\*.xml)
     foreach ($file in $files)
     {
        (Get-Content -path $file.FullName -Raw) -replace '<value>' , $replaceString | Set-Content -Path $file.FullName

    #this line makes problems...

     Compress-Archive -path $unzipFilePath -Destinationpath $unzipFilePath -Force

Body:
I see it in three steps:
1. unzip in a temporary clean location.
2. change your files there
3. zip that location back.

the code would have the functions:

function Unzip_archive ($ArchiveFullPath, $Temp_Work_Fld) {
    try {
        #unzip
        Add-Type -assembly 'system.io.compression.filesystem'
        [io.compression.zipfile]::ExtractToDirectory($ArchiveFullPath, $Temp_Work_Fld)
    }
    catch {
        throw "Failed to unzip the artifact"
    }
    Remove-Item $ArchiveFullPath -Force #only if you want to delete the archive
}

function CreateZipArchive($FolderToArchive, $ZipArchiveFullName){
    $source = Get-ChildItem * -Directory | Where-Object {$_.FullName -match "$FolderToArchive"}
    write-host "`nArchiving: $source ........."
    Add-Type -Assembly system.IO.compression.filesystem
    $compressionlevel = [System.IO.Compression.CompressionLevel]::Optimal
    [io.compression.zipfile]::CreateFromDirectory($source, $ZipArchiveFullName, $compressionlevel, $true)
    write-host "nDone !"
}

then just call the functions before and after doing your changes in the temporary folder


问:
Comparing nested list of list with a list
I am trying out to compare list of list values with another list and return if matched.I am looking it in scala however i am new into scala and it difficult to do if any suggestions please pass on

```<code>val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))

val l2 = List(1,2,3,12)
</code>```

so here trying to compare l1([1,2,3]) with l2 [1,2,3,12] and l1 [11,12,13] with l2 [1,2,3,12] and return if not matched any elements from l1 to l2.

here we are looking for of l1 any value matched with l2 then 0 else 1

Tricky but is it doable in scala?Any suggestions

答:
From the initial set of requirements that you have provided, the following solution will solve your problem

```<code>val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))

val l2 = List(11,12,13)

l1.flatten.filter(_.isInstanceOf[List[Int]]).map(x =>
  if(x == l2) 0 else 1)
</code>```

This gives you a result whether the list l2 matches inner list of l1 or not.

```<code>res1: List[Int] = List(1, 0)
</code>```

Body:
I am trying out to compare list of list values with another list and return if matched.I am looking it in scala however i am new into scala and it difficult to do if any suggestions please pass on

val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))

val l2 = List(1,2,3,12)

so here trying to compare l1([1,2,3]) with l2 [1,2,3,12] and l1 [11,12,13] with l2 [1,2,3,12] and return if not matched any elements from l1 to l2.

here we are looking for of l1 any value matched with l2 then 0 else 1

Tricky but is it doable in scala?Any suggestions

Body:
From the initial set of requirements that you have provided, the following solution will solve your problem

val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))

val l2 = List(11,12,13)

l1.flatten.filter(_.isInstanceOf[List[Int]]).map(x =>
  if(x == l2) 0 else 1)

This gives you a result whether the list l2 matches inner list of l1 or not.

res1: List[Int] = List(1, 0)


问:
Error registering: NoCredentialProviders: no valid providers in chain ECS agent error
Im trying to use EC2 Container service. Im using terraform for creating it.
I have defined a ecs cluster, autoscaling group, launch configuration. All seems to work. Except one thing. The ec2 instances are creating, but they are not register in the cluster, cluster just says no instances available.

In ecs agent log on created instance i found logs flooded with one error:

Error registering: NoCredentialProviders: no valid providers in chain

The ec2 instances are created with a proper role  ecs_role. This role has two policies, one of them is following, like docs required:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecs:CreateCluster",
        "ecs:DeregisterContainerInstance",
        "ecs:DiscoverPollEndpoint",
        "ecs:Poll",
        "ecs:RegisterContainerInstance",
        "ecs:StartTelemetrySession",
        "ecs:Submit*",
        "ecs:StartTask"
      ],
      "Resource": "*"
    }
  ]
}
```

Im using ami ami-6ff4bd05. Latest terraform.

答: You might want to add AmazonEC2RoleforSSM (or AmazonSSMFullAccess) to your EC2's role. </p>

Body:
Im trying to use EC2 Container service. Im using terraform for creating it.
I have defined a ecs cluster, autoscaling group, launch configuration. All seems to work. Except one thing. The ec2 instances are creating, but they are not register in the cluster, cluster just says no instances available.

In ecs agent log on created instance i found logs flooded with one error:

Error registering: NoCredentialProviders: no valid providers in chain

The ec2 instances are created with a proper role  ecs_role. This role has two policies, one of them is following, like docs required:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecs:CreateCluster",
        "ecs:DeregisterContainerInstance",
        "ecs:DiscoverPollEndpoint",
        "ecs:Poll",
        "ecs:RegisterContainerInstance",
        "ecs:StartTelemetrySession",
        "ecs:Submit*",
        "ecs:StartTask"
      ],
      "Resource": "*"
    }
  ]
}

Im using ami ami-6ff4bd05. Latest terraform.