问:
"No such file or directory" but it's there. Shell script looping through array of folders
I'm trying to automate the download of a subdirectories in a directory. However, when executing the script, the last one or two directories cannot be found by the script - "No such file or directory". All others do fine and can be downloaded. This occurs for all directories I've tried this on which is strange to me. Why would it always not find the last two directories?
Can anyone help with this? Is it due to the loop? I've tried changing it to loop over the last ones only and this doesn't help. Or maybe it's due to the conversion of array=($l)?

Here's my script:

```<code>dirServer=/dir/to/location/in/server
dirLocal=/dir/to/location/in/local/pc

l=`ssh -t username@server 'ls' ${dirServer}`

#array of folders that should be copied to local machine
array=($l)

for folder in ${array[@]}
do
  echo ${folder}

  #if directory doesn't exist, creat it
  mkdir -p ${dirLocal}${folder}
  scp -r username@server:${dirServer}${folder}/analysis/ ${dirLocal}${folder}
done
</code>```

答:
Try change the following line including this "-o LogLevel=QUIET"

```<code>l=`ssh -o LogLevel=QUIET -t username@server 'ls' ${dirServer}`
</code>```

Explanation:

That is coming from SSH. You see it because you gave the -t switch, which forces SSH to allocate a pseudo-terminal for the connection. Traditionally, SSH displays that message to make it clear that you are no longer interacting with the shell on the remote host, which is normally only a question when SSH has a pseudo-terminal allocated.

Body:
I'm trying to automate the download of a subdirectories in a directory. However, when executing the script, the last one or two directories cannot be found by the script - "No such file or directory". All others do fine and can be downloaded. This occurs for all directories I've tried this on which is strange to me. Why would it always not find the last two directories?
Can anyone help with this? Is it due to the loop? I've tried changing it to loop over the last ones only and this doesn't help. Or maybe it's due to the conversion of array=($l)?

Here's my script:

dirServer=/dir/to/location/in/server
dirLocal=/dir/to/location/in/local/pc

l=`ssh -t username@server 'ls' ${dirServer}`

#array of folders that should be copied to local machine
array=($l)

for folder in ${array[@]}
do
  echo ${folder}

  #if directory doesn't exist, creat it
  mkdir -p ${dirLocal}${folder}
  scp -r username@server:${dirServer}${folder}/analysis/ ${dirLocal}${folder}
done

Body:
Try change the following line including this "-o LogLevel=QUIET"

l=`ssh -o LogLevel=QUIET -t username@server 'ls' ${dirServer}`

Explanation:

That is coming from SSH. You see it because you gave the -t switch, which forces SSH to allocate a pseudo-terminal for the connection. Traditionally, SSH displays that message to make it clear that you are no longer interacting with the shell on the remote host, which is normally only a question when SSH has a pseudo-terminal allocated.


来源: stackexchange

问:
Show another div when image is hovered over
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>

  <div class="castcontainer">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div class="castcontainer">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article></code>```

答:
article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

article:hover .cast {
  display: none;
}

article:hover .cast2 {
  display: block;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>

  <div id="one" class="castcontainer cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
  </div>

  <div id="two"class="castcontainer cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
  </div>

</article></code>```

The inner div seems to be unnecessary where class="cast" and class="cast2". Remove the div's and add the class to its parent.

ContentLicense: CC BY-SA 3.0

Body:
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}

Ryan Reynalds

Wade Wilson

Body:
article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

article:hover .cast {
  display: none;
}

article:hover .cast2 {
  display: block;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}

<article>

  <div id="one" class="castcontainer cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
  </div>

  <div id="two"class="castcontainer cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
  </div>

</article>

The inner div seems to be unnecessary where class="cast" and class="cast2". Remove the div's and add the class to its parent.


问:
save screenshot of page into folder using php
I wants to develop a project in which user has to enter url and then it will take screenshot of that application and then save the screenshot to a folder.
I am able to take screenshot but it is not saving into folder. i am getting error:

```<code>Notice: Undefined index: extension in C:\xampp\htdocs\curlproject.php on line 20

Warning: fopen(images-folder/Z.): failed to open stream: Permission denied in C:\xampp\htdocs\curlproject.php on line 21
</code>```

Here is code:

```<code><?php
$websiteURL = $_POST["website"];
$api_response =
file_get_contents("https://www.googleapis.com/pagespeedonline/
v2/runPagespeed?url=$websiteURL&screenshot=true");

$result = json_decode($api_response, true);
//screenshot data
$screenshot = $result['screenshot']['data'];
$screenshot = str_replace(array('_','-'),array('/','+'),$screenshot);
//display screenshot image
echo "<img src=\"data:image/jpeg;base64,".$screenshot."\" />";

$split_image = pathinfo($screenshot);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $screenshot);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C
Safari/525.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response= curl_exec ($ch);
curl_close($ch);
$file_name = "images-
folder/".$split_image['filename'].".".$split_image['extension'];
$file = fopen($file_name , 'w') or die("X_x");
fwrite($file, $response);
fclose($file);
?>
</code>```

答:
The beauty of error logging is it tells you exactly where to look for the problem.

```<code>Notice: Undefined index: extension in C:\xampp\htdocs\curlproject.php on line 20
</code>```

On line 20 you have:

```<code>$file_name = "images-folder/".$split_image['filename'].".".$split_image['extension'];
</code>```

So whatever should be setting $split_image['extension'] obviously isn't doing anything.

Next up its:

```<code>Warning: fopen(images-folder/Z.): failed to open stream: Permission denied in C:\xampp\htdocs\curlproject.php on line 21
</code>```

Line 21 uses the filename constructed in line 20 and attempts to open a file:

```<code>$file = fopen($file_name , 'w') or die("X_x");
</code>```

You need to fix your first issue first to get a valid file name, then you should use an absolute path to specify the directory and finally ensure the user account which your webserver is running as has write permissions in the directory.

Body:
I wants to develop a project in which user has to enter url and then it will take screenshot of that application and then save the screenshot to a folder.
I am able to take screenshot but it is not saving into folder. i am getting error:

Notice: Undefined index: extension in C:\xampp\htdocs\curlproject.php on line 20

Warning: fopen(images-folder/Z.): failed to open stream: Permission denied in C:\xampp\htdocs\curlproject.php on line 21

Here is code:

<?php
$websiteURL = $_POST["website"];
$api_response =
file_get_contents("https://www.googleapis.com/pagespeedonline/
v2/runPagespeed?url=$websiteURL&screenshot=true");

$result = json_decode($api_response, true);
//screenshot data
$screenshot = $result['screenshot']['data'];
$screenshot = str_replace(array('_','-'),array('/','+'),$screenshot);
//display screenshot image
echo "";

$split_image = pathinfo($screenshot);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $screenshot);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C
Safari/525.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response= curl_exec ($ch);
curl_close($ch);
$file_name = "images-
folder/".$split_image['filename'].".".$split_image['extension'];
$file = fopen($file_name , 'w') or die("X_x");
fwrite($file, $response);
fclose($file);
?>

Body:
The beauty of error logging is it tells you exactly where to look for the problem.

Notice: Undefined index: extension in C:\xampp\htdocs\curlproject.php on line 20

On line 20 you have:

$file_name = "images-folder/".$split_image['filename'].".".$split_image['extension'];

So whatever should be setting $split_image['extension'] obviously isn't doing anything.

Next up its:

Warning: fopen(images-folder/Z.): failed to open stream: Permission denied in C:\xampp\htdocs\curlproject.php on line 21

Line 21 uses the filename constructed in line 20 and attempts to open a file:

$file = fopen($file_name , 'w') or die("X_x");

You need to fix your first issue first to get a valid file name, then you should use an absolute path to specify the directory and finally ensure the user account which your webserver is running as has write permissions in the directory.


问:
Converting Java sendEmail method to Groovy
I have a Java method to send a file attachment via e-mail. I'm trying to port it to Groovy as part of a Grails application. I'm having issue with the format of the FileDataSource declaration. The offending code is marked with an asterisk. What's the proper way to do that part in Groovy? I can't seem to find anything on the web.

```<code>public static void sendEmail(String sendFile)
    {
    //
    // Send the log file via email.
    //
    final String username = "myname@mydomain.com"
    final String password = "mypassword"

    // Strings that contain from, to, subject, body and file path to the attachment
    String from = username;
    String subject = "Test Results"
    String body = "Body of Test Results email."
    String filename = sendFile

    // Set smtp properties
    Properties properties = new Properties()
    properties.put("mail.smtp.starttls.enable", "true")
    properties.put("mail.smtp.auth", "true")
    properties.put("mail.smtp.host", "smtp.gmail.com")
    properties.put("mail.smtp.port", "587")

    Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username,password)
        }
    });

    try
    {
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(from))
        // For debug uncomment the line below and enter your email address.
        //message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("peter.cook@studentuniverse.com"));
        // For debug comment the line below out.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("cccm@studentuniverse.com,WebsiteOperations@studentuniverse.com,peter.cook@studentuniverse.com"))
        message.setSubject(subject)
        message.setSentDate(new Date())

        // Set the email body
        MimeBodyPart messagePart = new MimeBodyPart()
        messagePart.setText(body)

        // Set the email attachment file
        MimeBodyPart attachmentPart = new MimeBodyPart()
        *FileDataSource fileDataSource = new FileDataSource(filename)
        *{
        *    @Override
        *    public String getContentType()
        *    {
        *        return "application/octet-stream"
        *    }
        * }
        attachmentPart.setDataHandler(new DataHandler(fileDataSource))
        attachmentPart.setFileName(fileDataSource.getName())

        // Add all parts of the email to Multipart object
        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messagePart)
        multipart.addBodyPart(attachmentPart)
        message.setContent(multipart)

        // Send email
        Transport.send(message)
        System.out.println("Mail sent!")
    }
    catch (MessagingException e)
    {
        e.printStackTrace()
    }
}
</code>```

答:
The code you point out is an anonymous inner class overriding a single method (getContentType) and groovy is probably having a little trouble dealing with it due to the fact that it looks like a "new object" with a closure after it.

If you want to stick with the java-ish look I'd recommend changing it from an anonymous inner class to a separate class.  Something like this outside of your other code in this class (It can be in the same file if it's not a public class):

```<code>    class ForceOctetStreamFileDataSource extends FileDataSource
    {
        public ForceOctetStreamFileDataSource(String filename) {
            super(filename);
        }

        @Override
        public String getContentType()
        {
            return "application/octet-stream"
        }
    }
</code>```

then in your class replace it with just new ForceOctetStreamFileDataSource(filename)

This should be explicit enough not to confuse groovy.  There is probably a much shorter "Groovy" way involving closures that I don't want to guess at right now.

Body:
I have a Java method to send a file attachment via e-mail. I'm trying to port it to Groovy as part of a Grails application. I'm having issue with the format of the FileDataSource declaration. The offending code is marked with an asterisk. What's the proper way to do that part in Groovy? I can't seem to find anything on the web.

public static void sendEmail(String sendFile)
    {
    //
    // Send the log file via email.
    //
    final String username = "myname@mydomain.com"
    final String password = "mypassword"

    // Strings that contain from, to, subject, body and file path to the attachment
    String from = username;
    String subject = "Test Results"
    String body = "Body of Test Results email."
    String filename = sendFile

    // Set smtp properties
    Properties properties = new Properties()
    properties.put("mail.smtp.starttls.enable", "true")
    properties.put("mail.smtp.auth", "true")
    properties.put("mail.smtp.host", "smtp.gmail.com")
    properties.put("mail.smtp.port", "587")

    Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username,password)
        }
    });

    try
    {
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(from))
        // For debug uncomment the line below and enter your email address.
        //message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("peter.cook@studentuniverse.com"));
        // For debug comment the line below out.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("cccm@studentuniverse.com,WebsiteOperations@studentuniverse.com,peter.cook@studentuniverse.com"))
        message.setSubject(subject)
        message.setSentDate(new Date())

        // Set the email body
        MimeBodyPart messagePart = new MimeBodyPart()
        messagePart.setText(body)

        // Set the email attachment file
        MimeBodyPart attachmentPart = new MimeBodyPart()
        *FileDataSource fileDataSource = new FileDataSource(filename)
        *{
        *    @Override
        *    public String getContentType()
        *    {
        *        return "application/octet-stream"
        *    }
        * }
        attachmentPart.setDataHandler(new DataHandler(fileDataSource))
        attachmentPart.setFileName(fileDataSource.getName())

        // Add all parts of the email to Multipart object
        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messagePart)
        multipart.addBodyPart(attachmentPart)
        message.setContent(multipart)

        // Send email
        Transport.send(message)
        System.out.println("Mail sent!")
    }
    catch (MessagingException e)
    {
        e.printStackTrace()
    }
}

Body:
The code you point out is an anonymous inner class overriding a single method (getContentType) and groovy is probably having a little trouble dealing with it due to the fact that it looks like a "new object" with a closure after it.

If you want to stick with the java-ish look I'd recommend changing it from an anonymous inner class to a separate class.  Something like this outside of your other code in this class (It can be in the same file if it's not a public class):

    class ForceOctetStreamFileDataSource extends FileDataSource
    {
        public ForceOctetStreamFileDataSource(String filename) {
            super(filename);
        }

        @Override
        public String getContentType()
        {
            return "application/octet-stream"
        }
    }

then in your class replace it with just new ForceOctetStreamFileDataSource(filename)

This should be explicit enough not to confuse groovy.  There is probably a much shorter "Groovy" way involving closures that I don't want to guess at right now.


问:
Cockroachdb Admin UI Not Reachable
I'm trying to deploy a CockroachDB cluster on Digital Ocean. I followed the steps listed in the tutorial here https://www.digitalocean.com/community/tutorials/how-to-deploy-cockroachdb-on-a-three-node-cluster-on-ubuntu-16-04

I can see cockroachdb running on the host but I'm unable to access the Web Admin UI.

I'm having the same issue when accessing it through an application.

This is the start command and response.
Note: I enable Private Networking when creating the droplets, could this be because of that?

roach@cockroach-01:~$ cockroach start --insecure --background --advertise-host=10.132.10.114
*
* WARNING: RUNNING IN INSECURE MODE!
*
* - Your cluster is open for any client that can access <all your IP addresses>.
* - Any user, even root, can log in without providing a password.
* - Any user, connecting as root, can read or write any data in your cluster.
* - There is no network encryption nor authentication, and thus no confidentiality.
*
* Check out how to secure your cluster: https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html
*
CockroachDB node starting at 2017-11-10 22:59:07.153981296 +0000 UTC (took 0.4s)
build:      CCL v1.1.2 @ 2017/11/02 19:32:03 (go1.8.3)
admin:      http://cockroach-01:8080
sql:        postgresql://root@10.132.10.114:26257?application_name=cockroach&sslmode=disable
logs:       /home/roach/cockroach-data/logs
store[0]:   path=/home/roach/cockroach-data
status:     initialized new cluster
clusterID:  77dea0f4-d2c1-49c3-bfe9-8686a6084603
nodeID:     1

答: I had this same thing happen to me on DigitalOcean. Try setting the -http-host flag when you start up the node to the public IP address for your DigitalOcean instance.</p>

Title: Cockroachdb Admin UI Not Reachable


问:
Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0' - However binary exists in bin folder
I am trying to do something pretty simple here, and I've been stuck on it for several hours. I feel like I've exhausted almost every option.

All I am trying to do is:
JsonConvert.SerializeObject(model)

However, the resulting error is:

Exception thrown: 'System.IO.FileLoadException' in mscorlib.dll

Additional information: Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=982hs0cm1kd' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

However, in my project, I am referencing version 10.0.0.0. More Specifically, 10.0.2.0. When I checked my bin folder for the project, I can verify that the 10.0.2.0 dll is there. In packages.config, I have <package id="Newtonsoft.Json" version="10.0.2" targetFramework="net452" />

Things I have tried:

Manually deleteing the bin/obj folders from the project and rebuilding

Manually Modifying the Web.Config file to ensure the right version in the binding redirect.

Updating the Reference Property 'Specific Version' to False

Manually delete all of the files in C:/WINDOWS/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root

I am really stuck here, and I can see this is a common problem as I found a lot of different approaches to fix it, however none have worked so far.

Any ideas?

答:
In package manager console execute: Update-Package –reinstall Newtonsoft.Json.

source


问:
RabbitTemplate not ending the spring boot + spring batch job app
I have a batch job that would read from a RabbitMQ queue. I used the AmqpItemReader as the reader. The problem I face is that, when the batch job completes, the app does not terminate by itself. I am not sure if I configured my RabbitTemplate properly. It would be great if someone could help me figure out why my app is not terminating properly.

RabbitConfig class:

```<code>@Configuration
@ConfigurationProperties("service.product.config.rabbitmq")
public class RabbitConfig {

  @Setter
  private String host;
  @Setter
  private Integer port;
  @Setter
  private String username;
  @Setter
  private String password;
  @Setter
  private String exchangeName;
  @Setter
  private String queueName;

  @Bean
  ConnectionFactory rabbitConnectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
    connectionFactory.setPort(port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    return connectionFactory;
  }

  @Bean
  RabbitTemplate rabbitTemplate(ConnectionFactory rabbitConnectionFactory) {

    RabbitTemplate rabbitTemplate = new RabbitTemplate(rabbitConnectionFactory);
    rabbitTemplate.setQueue(queueName);
    rabbitTemplate.setExchange(exchangeName);

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

Job class:

```<code>@Configuration
@EnableBatchProcessing
public class ImportJobConfig {

  private final Logger logger = LoggerFactory.getLogger(ImportJobConfig.class);

  @Autowired
  JobBuilderFactory jobBuilderFactory;
  @Autowired
  StepBuilderFactory stepBuilderFactory;
  @Autowired
  RabbitTemplate rabbitTemplate;

  @Bean
  public Job importJob() {
    return jobBuilderFactory.get("importJob")
        .listener(new JobExecutionListener() {
          @Override
          public void beforeJob(JobExecution jobExecution) {
            logger.info("Ready to start the job");
          }

          @Override
          public void afterJob(JobExecution jobExecution) {
            logger.info("Job successfully executed.");
          }
        })
        .incrementer(new RunIdIncrementer())
        .flow(stepBuilderFactory.get("importStep")
            .<String, String>chunk(2)
            .reader(new AmqpItemReader<>(rabbitTemplate))
            .listener(new QueueListener<>())
            .processor(new CustomItemProcessor())
            .writer(new CustomItemWriter())
            .build())
        .end()
        .build();
  }
}
</code>```

EDIT:
My main method class:

```<code>@SpringBootApplication
public class BulkImportProductApplication {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(BulkImportProductApplication.class);
    app.setWebEnvironment(false);
    app.run(args);
  }

}
</code>```

EDIT END

Dependencies I use:

```<code>spring-boot-starter-amqp
spring-boot-starter-batch
com.h2database:h2
spring-batch-test
spring-boot-starter-test
</code>```

Let me know if you need any thing else that could help you find why my job doesn't terminate after the job is completed.

答:
Where's your main() method? How do you create the application context?

You need to close() the application context when the job completes; you can use a JobExecutionListener to detect when the job completes.

Closing the context will call destroy() on the connection factory (which is probably what's keeping your JVM running).

Body:
I have a batch job that would read from a RabbitMQ queue. I used the AmqpItemReader as the reader. The problem I face is that, when the batch job completes, the app does not terminate by itself. I am not sure if I configured my RabbitTemplate properly. It would be great if someone could help me figure out why my app is not terminating properly.

RabbitConfig class:

@Configuration
@ConfigurationProperties("service.product.config.rabbitmq")
public class RabbitConfig {

  @Setter
  private String host;
  @Setter
  private Integer port;
  @Setter
  private String username;
  @Setter
  private String password;
  @Setter
  private String exchangeName;
  @Setter
  private String queueName;

  @Bean
  ConnectionFactory rabbitConnectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
    connectionFactory.setPort(port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    return connectionFactory;
  }

  @Bean
  RabbitTemplate rabbitTemplate(ConnectionFactory rabbitConnectionFactory) {

    RabbitTemplate rabbitTemplate = new RabbitTemplate(rabbitConnectionFactory);
    rabbitTemplate.setQueue(queueName);
    rabbitTemplate.setExchange(exchangeName);

    return rabbitTemplate;
  }
}

Job class:

@Configuration
@EnableBatchProcessing
public class ImportJobConfig {

  private final Logger logger = LoggerFactory.getLogger(ImportJobConfig.class);

  @Autowired
  JobBuilderFactory jobBuilderFactory;
  @Autowired
  StepBuilderFactory stepBuilderFactory;
  @Autowired
  RabbitTemplate rabbitTemplate;

  @Bean
  public Job importJob() {
    return jobBuilderFactory.get("importJob")
        .listener(new JobExecutionListener() {
          @Override
          public void beforeJob(JobExecution jobExecution) {
            logger.info("Ready to start the job");
          }

          @Override
          public void afterJob(JobExecution jobExecution) {
            logger.info("Job successfully executed.");
          }
        })
        .incrementer(new RunIdIncrementer())
        .flow(stepBuilderFactory.get("importStep")
            .<String, String>chunk(2)
            .reader(new AmqpItemReader<>(rabbitTemplate))
            .listener(new QueueListener<>())
            .processor(new CustomItemProcessor())
            .writer(new CustomItemWriter())
            .build())
        .end()
        .build();
  }
}

EDIT:
My main method class:

@SpringBootApplication
public class BulkImportProductApplication {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(BulkImportProductApplication.class);
    app.setWebEnvironment(false);
    app.run(args);
  }

}

EDIT END

Dependencies I use:

spring-boot-starter-amqp
spring-boot-starter-batch
com.h2database:h2
spring-batch-test
spring-boot-starter-test

Let me know if you need any thing else that could help you find why my job doesn't terminate after the job is completed.


问:
Primefaces filedownload in Datatable celleditor not working
I have a Datatable in Primefaces with a celleditor to upload and download files.
The file upload is working.
The file download doesn't work, it only reloads the page.
When I put the download Button direct under the p:column, the download is working. (So the download button is visible in edit mode)

What is wrong, any ideas?

Here is my code (simplified):

```<code><p:column headerText="Header">
  <!-- Download Button at this position works -->
  <p:cellEditor>
    <f:facet name="output">
      <p:commandButton id="download" value="Download" ajax="false">
        <p:fileDownload value="#{bean.downloadFile}" />
      </p:commandButton>
    </f:facet>
    <f:facet name="input">
      <p:fileUpload fileUploadListener="#{bean.uploadFile}" label="upload" mode="advanced" auto="true" process="@this" />
    </f:facet>
  </p:cellEditor>
</p:column>
</code>```

And the managed bean:

```<code>import java.io.InputStream;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

public StreamedContent getDownloadFile() {
    final InputStream stream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/images/test.png");
    return new DefaultStreamedContent(stream, "image/png", "test.png");
}
</code>```

答: Not really a fix, but I had the same issue in my app and solved it by removing the cell Editor component, and styling the remaining components to appear side by side (display: inline-block) to provide something that looks nice.</p>

Body:
I have a Datatable in Primefaces with a celleditor to upload and download files.
The file upload is working.
The file download doesn't work, it only reloads the page.
When I put the download Button direct under the p:column, the download is working. (So the download button is visible in edit mode)

What is wrong, any ideas?

Here is my code (simplified):

    <f:facet name="output">

    </f:facet>
    <f:facet name="input">

    </f:facet>

And the managed bean:

import java.io.InputStream;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

public StreamedContent getDownloadFile() {
    final InputStream stream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/images/test.png");
    return new DefaultStreamedContent(stream, "image/png", "test.png");
}


问:
VssConnection to VSTS always prompts for credentials
I am using the Visual Studio client tools for calling the VSTS REST APIs in a command line utility. This utility can be run several times for different commands (Copy, Delete, applying policies, etc.)

I'm creating the VssConnection like such

```<code>public static VssConnection CreateConnection(Uri url, VssCredentials credentials = null)
{
    credentials = credentials ?? new VssClientCredentials();

    credentials.Storage = new VssClientCredentialStorage();

    var connection = new VssConnection(url, credentials);

    connection.ConnectAsync().SyncResult();

    return connection;
}
</code>```

According to the docs, this should be caching the credentials so that you won't get prompted again when running my command line tool. But I get prompted every time I run my command line utility and the VssConnection tries to connect.

Is there anyway to cache the credentials so that the user won't be prompted every time they run the command line?

Should be noted that if I don't dispose the VssConnection, it will not prompt the next time I run it.

UPDATE
To be clear, the issue isn't caching the VssClientCredentials instance once the connection is created as that object is attached to the VssConnection object. The issue is caching the user token between execution of the program, i.e.   on the local machine so that the next time the utility is executed from the command line the user doesn't have to once again type in their credentials. Similar to how you don't have to always log into Visual Studio each time you fire it up.

答:
So I found a working solution that seems to be exactly what I wanted. If there is a better solution, please feel free to post.

Solution: Since VssClientCredentials.Storage property is expecting a class that implements IVssCredentialStorage, I created a class that implements that interface by deriving from the stock VssClientCredentialStorage class.

It then overrides the methods around retrieving and removing tokens to manage them based on an expiration lease which is stored with the token in the registry.

If the token is retrieved and has an expired lease, the token is removed from the storage and null is returned and the VssConnection class display a UI forcing the user to enter their credentials. If the token isn't expired, the user is not prompted and the cached credential is used.

So now I can do the following:

Call my utility from the command line for the first time

Supply credentials to the VSTS client prompt

Run the utility again from the command line without being prompted!

Now I've built into my utility a standard lease expiration but the user can alter it with a command line option. Also the user can clear the cached credentials as well.

The key is in the RemoveToken override. The call to the base class is what removes it from the registry, so if you bypass that (in my case if the lease hasn't expired) then the registry entry will remain. This allows the VssConnection to use the cached credentials and not prompt the user each time the program is executed!

Example of the calling code:

```<code>    public static VssConnection CreateConnection(Uri url, VssCredentials credentials = null, double tokenLeaseInSeconds = VssClientCredentialCachingStorage.DefaultTokenLeaseInSeconds)
    {
        credentials = credentials ?? new VssClientCredentials();

        credentials.Storage = GetVssClientCredentialStorage(tokenLeaseInSeconds);

        var connection = new VssConnection(url, credentials);

        connection.ConnectAsync().SyncResult();

        return connection;
    }

    private static VssClientCredentialCachingStorage GetVssClientCredentialStorage(double tokenLeaseInSeconds)
    {
        return new VssClientCredentialCachingStorage("YourApp", "YourNamespace", tokenLeaseInSeconds);
    }
</code>```

The derived storage class:

```<code>    /// <summary>
    /// Class to alter the credential storage behavior to allow the token to be cached between sessions.
    /// </summary>
    /// <seealso cref="Microsoft.VisualStudio.Services.Common.IVssCredentialStorage" />
    public class VssClientCredentialCachingStorage : VssClientCredentialStorage
    {
        #region [Private]

        private const string __tokenExpirationKey = "ExpirationDateTime";
        private double _tokenLeaseInSeconds;

        #endregion [Private]

        /// <summary>
        /// The default token lease in seconds
        /// </summary>
        public const double DefaultTokenLeaseInSeconds = 86400;// one day

        /// <summary>
        /// Initializes a new instance of the <see cref="VssClientCredentialCachingStorage"/> class.
        /// </summary>
        /// <param name="storageKind">Kind of the storage.</param>
        /// <param name="storageNamespace">The storage namespace.</param>
        /// <param name="tokenLeaseInSeconds">The token lease in seconds.</param>
        public VssClientCredentialCachingStorage(string storageKind = "VssApp", string storageNamespace = "VisualStudio", double tokenLeaseInSeconds = DefaultTokenLeaseInSeconds)
            : base(storageKind, storageNamespace)
        {
            this._tokenLeaseInSeconds = tokenLeaseInSeconds;
        }

        /// <summary>
        /// Removes the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="token">The token.</param>
        public override void RemoveToken(Uri serverUrl, IssuedToken token)
        {
            this.RemoveToken(serverUrl, token, false);
        }

        /// <summary>
        /// Removes the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="token">The token.</param>
        /// <param name="force">if set to <c>true</c> force the removal of the token.</param>
        public void RemoveToken(Uri serverUrl, IssuedToken token, bool force)
        {
            //////////////////////////////////////////////////////////
            // Bypassing this allows the token to be stored in local
            // cache. Token is removed if lease is expired.

            if (force || token != null && this.IsTokenExpired(token))
                base.RemoveToken(serverUrl, token);

            //////////////////////////////////////////////////////////
        }

        /// <summary>
        /// Retrieves the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="credentialsType">Type of the credentials.</param>
        /// <returns>The <see cref="IssuedToken"/></returns>
        public override IssuedToken RetrieveToken(Uri serverUrl, VssCredentialsType credentialsType)
        {
            var token = base.RetrieveToken(serverUrl, credentialsType);

            if (token != null)
            {
                bool expireToken = this.IsTokenExpired(token);
                if (expireToken)
                {
                    base.RemoveToken(serverUrl, token);
                    token = null;
                }
                else
                {
                    // if retrieving the token before it is expired,
                    // refresh the lease period.
                    this.RefreshLeaseAndStoreToken(serverUrl, token);
                    token = base.RetrieveToken(serverUrl, credentialsType);
                }
            }

            return token;
        }

        /// <summary>
        /// Stores the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="token">The token.</param>
        public override void StoreToken(Uri serverUrl, IssuedToken token)
        {
            this.RefreshLeaseAndStoreToken(serverUrl, token);
        }

        /// <summary>
        /// Clears all tokens.
        /// </summary>
        /// <param name="url">The URL.</param>
        public void ClearAllTokens(Uri url = null)
        {
            IEnumerable<VssToken> tokens = this.TokenStorage.RetrieveAll(base.TokenKind).ToList();

            if (url != default(Uri))
                tokens = tokens.Where(t => StringComparer.InvariantCultureIgnoreCase.Compare(t.Resource, url.ToString().TrimEnd('/')) == 0);

            foreach(var token in tokens)
                this.TokenStorage.Remove(token);
        }

        private void RefreshLeaseAndStoreToken(Uri serverUrl, IssuedToken token)
        {
            if (token.Properties == null)
                token.Properties = new Dictionary<string, string>();

            token.Properties[__tokenExpirationKey] = JsonSerializer.SerializeObject(this.GetNewExpirationDateTime());

            base.StoreToken(serverUrl, token);
        }

        private DateTime GetNewExpirationDateTime()
        {
            var now = DateTime.Now;

            // Ensure we don't overflow the max DateTime value
            var lease = Math.Min((DateTime.MaxValue - now.Add(TimeSpan.FromSeconds(1))).TotalSeconds, this._tokenLeaseInSeconds);

            // ensure we don't have negative leases
            lease = Math.Max(lease, 0);

            return now.AddSeconds(lease);
        }

        private bool IsTokenExpired(IssuedToken token)
        {
            bool expireToken = true;

            if (token != null && token.Properties.ContainsKey(__tokenExpirationKey))
            {
                string expirationDateTimeJson = token.Properties[__tokenExpirationKey];

                try
                {
                    DateTime expiration = JsonSerializer.DeserializeObject<DateTime>(expirationDateTimeJson);

                    expireToken = DateTime.Compare(DateTime.Now, expiration) >= 0;
                }
                catch { }
            }

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

Body:
I am using the Visual Studio client tools for calling the VSTS REST APIs in a command line utility. This utility can be run several times for different commands (Copy, Delete, applying policies, etc.)

I'm creating the VssConnection like such

public static VssConnection CreateConnection(Uri url, VssCredentials credentials = null)
{
    credentials = credentials ?? new VssClientCredentials();

    credentials.Storage = new VssClientCredentialStorage();

    var connection = new VssConnection(url, credentials);

    connection.ConnectAsync().SyncResult();

    return connection;
}

According to the docs, this should be caching the credentials so that you won't get prompted again when running my command line tool. But I get prompted every time I run my command line utility and the VssConnection tries to connect.

Is there anyway to cache the credentials so that the user won't be prompted every time they run the command line?

Should be noted that if I don't dispose the VssConnection, it will not prompt the next time I run it.

UPDATE
To be clear, the issue isn't caching the VssClientCredentials instance once the connection is created as that object is attached to the VssConnection object. The issue is caching the user token between execution of the program, i.e.   on the local machine so that the next time the utility is executed from the command line the user doesn't have to once again type in their credentials. Similar to how you don't have to always log into Visual Studio each time you fire it up.

Body:
So I found a working solution that seems to be exactly what I wanted. If there is a better solution, please feel free to post.

Solution: Since VssClientCredentials.Storage property is expecting a class that implements IVssCredentialStorage, I created a class that implements that interface by deriving from the stock VssClientCredentialStorage class.

It then overrides the methods around retrieving and removing tokens to manage them based on an expiration lease which is stored with the token in the registry.

If the token is retrieved and has an expired lease, the token is removed from the storage and null is returned and the VssConnection class display a UI forcing the user to enter their credentials. If the token isn't expired, the user is not prompted and the cached credential is used.

So now I can do the following:

Call my utility from the command line for the first time

Supply credentials to the VSTS client prompt

Run the utility again from the command line without being prompted!

Now I've built into my utility a standard lease expiration but the user can alter it with a command line option. Also the user can clear the cached credentials as well.

The key is in the RemoveToken override. The call to the base class is what removes it from the registry, so if you bypass that (in my case if the lease hasn't expired) then the registry entry will remain. This allows the VssConnection to use the cached credentials and not prompt the user each time the program is executed!

Example of the calling code:

    public static VssConnection CreateConnection(Uri url, VssCredentials credentials = null, double tokenLeaseInSeconds = VssClientCredentialCachingStorage.DefaultTokenLeaseInSeconds)
    {
        credentials = credentials ?? new VssClientCredentials();

        credentials.Storage = GetVssClientCredentialStorage(tokenLeaseInSeconds);

        var connection = new VssConnection(url, credentials);

        connection.ConnectAsync().SyncResult();

        return connection;
    }

    private static VssClientCredentialCachingStorage GetVssClientCredentialStorage(double tokenLeaseInSeconds)
    {
        return new VssClientCredentialCachingStorage("YourApp", "YourNamespace", tokenLeaseInSeconds);
    }

The derived storage class:

    /// <summary>
    /// Class to alter the credential storage behavior to allow the token to be cached between sessions.
    /// </summary>
    /// <seealso cref="Microsoft.VisualStudio.Services.Common.IVssCredentialStorage" />
    public class VssClientCredentialCachingStorage : VssClientCredentialStorage
    {
        #region [Private]

        private const string __tokenExpirationKey = "ExpirationDateTime";
        private double _tokenLeaseInSeconds;

        #endregion [Private]

        /// <summary>
        /// The default token lease in seconds
        /// </summary>
        public const double DefaultTokenLeaseInSeconds = 86400;// one day

        /// <summary>
        /// Initializes a new instance of the <see cref="VssClientCredentialCachingStorage"/> class.
        /// </summary>
        /// <param name="storageKind">Kind of the storage.</param>
        /// <param name="storageNamespace">The storage namespace.</param>
        /// <param name="tokenLeaseInSeconds">The token lease in seconds.</param>
        public VssClientCredentialCachingStorage(string storageKind = "VssApp", string storageNamespace = "VisualStudio", double tokenLeaseInSeconds = DefaultTokenLeaseInSeconds)
            : base(storageKind, storageNamespace)
        {
            this._tokenLeaseInSeconds = tokenLeaseInSeconds;
        }

        /// <summary>
        /// Removes the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="token">The token.</param>
        public override void RemoveToken(Uri serverUrl, IssuedToken token)
        {
            this.RemoveToken(serverUrl, token, false);
        }

        /// <summary>
        /// Removes the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="token">The token.</param>
        /// <param name="force">if set to <c>true</c> force the removal of the token.</param>
        public void RemoveToken(Uri serverUrl, IssuedToken token, bool force)
        {
            //////////////////////////////////////////////////////////
            // Bypassing this allows the token to be stored in local
            // cache. Token is removed if lease is expired.

            if (force || token != null && this.IsTokenExpired(token))
                base.RemoveToken(serverUrl, token);

            //////////////////////////////////////////////////////////
        }

        /// <summary>
        /// Retrieves the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="credentialsType">Type of the credentials.</param>
        /// <returns>The <see cref="IssuedToken"/></returns>
        public override IssuedToken RetrieveToken(Uri serverUrl, VssCredentialsType credentialsType)
        {
            var token = base.RetrieveToken(serverUrl, credentialsType);

            if (token != null)
            {
                bool expireToken = this.IsTokenExpired(token);
                if (expireToken)
                {
                    base.RemoveToken(serverUrl, token);
                    token = null;
                }
                else
                {
                    // if retrieving the token before it is expired,
                    // refresh the lease period.
                    this.RefreshLeaseAndStoreToken(serverUrl, token);
                    token = base.RetrieveToken(serverUrl, credentialsType);
                }
            }

            return token;
        }

        /// <summary>
        /// Stores the token.
        /// </summary>
        /// <param name="serverUrl">The server URL.</param>
        /// <param name="token">The token.</param>
        public override void StoreToken(Uri serverUrl, IssuedToken token)
        {
            this.RefreshLeaseAndStoreToken(serverUrl, token);
        }

        /// <summary>
        /// Clears all tokens.
        /// </summary>
        /// <param name="url">The URL.</param>
        public void ClearAllTokens(Uri url = null)
        {
            IEnumerable<VssToken> tokens = this.TokenStorage.RetrieveAll(base.TokenKind).ToList();

            if (url != default(Uri))
                tokens = tokens.Where(t => StringComparer.InvariantCultureIgnoreCase.Compare(t.Resource, url.ToString().TrimEnd('/')) == 0);

            foreach(var token in tokens)
                this.TokenStorage.Remove(token);
        }

        private void RefreshLeaseAndStoreToken(Uri serverUrl, IssuedToken token)
        {
            if (token.Properties == null)
                token.Properties = new Dictionary<string, string>();

            token.Properties[__tokenExpirationKey] = JsonSerializer.SerializeObject(this.GetNewExpirationDateTime());

            base.StoreToken(serverUrl, token);
        }

        private DateTime GetNewExpirationDateTime()
        {
            var now = DateTime.Now;

            // Ensure we don't overflow the max DateTime value
            var lease = Math.Min((DateTime.MaxValue - now.Add(TimeSpan.FromSeconds(1))).TotalSeconds, this._tokenLeaseInSeconds);

            // ensure we don't have negative leases
            lease = Math.Max(lease, 0);

            return now.AddSeconds(lease);
        }

        private bool IsTokenExpired(IssuedToken token)
        {
            bool expireToken = true;

            if (token != null && token.Properties.ContainsKey(__tokenExpirationKey))
            {
                string expirationDateTimeJson = token.Properties[__tokenExpirationKey];

                try
                {
                    DateTime expiration = JsonSerializer.DeserializeObject<DateTime>(expirationDateTimeJson);

                    expireToken = DateTime.Compare(DateTime.Now, expiration) >= 0;
                }
                catch { }
            }

            return expireToken;
        }
    }


问:
can I customize in odoo apps after deploying to google cloud
I'm new to google Cloud and Odoo ERP,I need to customize in 2 odoo apps Fleet and CRM, Can I customize after deploying odoo via Bitnami Lunchpad to Google Cloud, or I need to customize in local virtual machine, and Can I upload local virtual machine to google cloud or only can deploy odoo to Google via Bitnami Lunchpad.

Can Google endpoints access postgreSQL of odoo server

Any help is welcome, Thank you.

答:
For Google Cloud Endpoints, it sits in front of your app. You can get the general architecture idea from these links depending on what platform you are choosing to use:
https://cloud.google.com/endpoints/docs/openapi/architecture-overview
https://cloud.google.com/endpoints/docs/frameworks/about-cloud-endpoints-frameworks

Since Google Cloud Endpoints sits in front of your app and forwards requests to your app, your app is still responsible for handling the requests. This would include things like accessing PostreSQL. Therefore, as long as your app can access PostgreSql, using Google Cloud Endpoints should not restrict your usage.


答:
Install the mail plugin by adding compile 'org.grails.plugins:mail' to your build.gradle and then read the doco here.

In case you have trouble with the installation, try compile 'org.grails.plugins:mail:2.0.0.RC1'.

Then, for smtp configuration, you will need to migrate it to config file :

If you are done , you should be able to send an email following snippet above  :

```<code>mailService.sendMail {
   to "fred@gmail.com","ginger@gmail.com"
   from "john@gmail.com"
   cc "marge@gmail.com", "ed@gmail.com"
   bcc "joe@gmail.com"
   subject "Hello John"
   text 'this is some text'
}
</code>```

Title: Converting Java sendEmail method to Groovy

Body:
Install the mail plugin by adding compile 'org.grails.plugins:mail' to your build.gradle and then read the doco here.

In case you have trouble with the installation, try compile 'org.grails.plugins:mail:2.0.0.RC1'.

Then, for smtp configuration, you will need to migrate it to config file :

If you are done , you should be able to send an email following snippet above  :

mailService.sendMail {
   to "fred@gmail.com","ginger@gmail.com"
   from "john@gmail.com"
   cc "marge@gmail.com", "ed@gmail.com"
   bcc "joe@gmail.com"
   subject "Hello John"
   text 'this is some text'
}


问:
how to use JQuery "toggle" with parameters?
I have a table like this:

```<code><table>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />    </td>
    <td>some data about ID 534534</td>
  </tr>
  <tr id="row534534" class="hiddenRow">
    <td colspan="2">some hidden data about ID 534534 that must show/hide with toggle</td>
  </tr>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" /></td>
    <td>some data about ID 2423434</td>
  </tr>
  <tr id="row2423434" class="hiddenRow">
    <td colspan="2">some hidden data about ID 2423434that must show/hide with toggle</td>
  </tr>
  <!-- many more rows here -->
</table>
</code>```

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

```<code>$("tr.hiddenRow").hide();
</code>```

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

答:
This should do the trick:

```<code>$(document).ready(function() {
    $(".toggle").click(function() {
        $(this).closest('tr').next('tr.hiddenRow').toggle();
    });
});
</code>```

http://jsfiddle.net/DU8rd/1 (Thanks Šime Vidas)

Note: This doesn't pass the ID as you indicated, but it does create the behavior you described.

ContentLicense: CC BY-SA 2.5

Body:
I have a table like this:

    <input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />
    some data about ID 534534

    some hidden data about ID 534534 that must show/hide with toggle

    <input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" />
    some data about ID 2423434

    some hidden data about ID 2423434that must show/hide with toggle

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

$("tr.hiddenRow").hide();

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

Body:
This should do the trick:

$(document).ready(function() {
    $(".toggle").click(function() {
        $(this).closest('tr').next('tr.hiddenRow').toggle();
    });
});

http://jsfiddle.net/DU8rd/1 (Thanks Šime Vidas)

Note: This doesn't pass the ID as you indicated, but it does create the behavior you described.


问:
Class Template SFINAE via Inheritance
The s1 class template specialisation below only allows instantiations of s1 when using integral type template arguments.

```<code>template <typename, typename = void>
  struct s1;

template <typename T>
struct s1<T, std::enable_if_t<std::is_integral<T>::value>> { };
</code>```

The following class template, s2, is similar; though it conditionally inherits privately from a trivial base class. What are the differences in functionality between s1 and s2?

```<code>struct Base { };

template <typename T>
struct s2 : private std::enable_if_t<std::is_integral<T>::value,Base> { };
</code>```

答:
With s1 you can extend it with new specializations that cover more cases in distributed bits of code.  SFINAE would kick in, and so long as only one specialization was valid, it would be chosen.

The expression tested in such specializations is arbitrary.

I could create an s1 specialization that accepts when T is floating point, or a complex type, or is an array.

For s2, only things that template pattern matching can prefer to a bare T can be used to create further matching specializations.  There is no way to create an s2 specialization that accepts any floating point types, for example, but I could create one that accepts any pointers.

Title: Class Template SFINAE via Inheritance

Body:
The s1 class template specialisation below only allows instantiations of s1 when using integral type template arguments.

template <typename, typename = void>
  struct s1;

template <typename T>
struct s1<T, std::enable_if_t<std::is_integral<T>::value>> { };

The following class template, s2, is similar; though it conditionally inherits privately from a trivial base class. What are the differences in functionality between s1 and s2?

struct Base { };

template <typename T>
struct s2 : private std::enable_if_t<std::is_integral<T>::value,Base> { };


问:
Link all in Xamarin release,failed with Autofac Assembly
When setting the Linker behaviour to "Link all" I get the following error at runtime:
Autofac.Core.DependencyResolutionException.

I've tried adding ignore assembly Autofac but without success.

Setting the Linker behavior to "Link Framework SDKs only" does work but I want to enable "Link All" if possible.

Thanks in advance.

Update :

```<code>ReflectionActivator.ActivateInstance (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
    Autofac.Core.DependencyResolutionException: No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.

No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.

An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = RestService (ReflectionActivator), Services = [Eela.Model.Xamarin.Interfaces.IRestService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.)

1
ReflectionActivator.ActivateInstance (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
2
InstanceLookup.Activate (System.Collections.Generic.IEnumerable`1[T] parameters)

An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = RestService (ReflectionActivator), Services = [Eela.Model.Xamarin.Interfaces.IRestService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.)

1
InstanceLookup.Activate (System.Collections.Generic.IEnumerable`1[T] parameters)
2
InstanceLookup.Execute ()
3
ResolveOperation.GetOrCreateInstance (Autofac.Core.ISharingLifetimeScope currentOperationScope, Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
4
ResolveOperation.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
5
ResolveOperation.Execute (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
6
LifetimeScope.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
7
Container.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
8
ResolutionExtensions.TryResolveService (Autofac.IComponentContext context, Autofac.Core.Service service, System.Collections.Generic.IEnumerable`1[T] parameters, System.Object& instance)
9
ResolutionExtensions.ResolveService (Autofac.IComponentContext context, Autofac.Core.Service service, System.Collections.Generic.IEnumerable`1[T] parameters)
10
ResolutionExtensions.Resolve (Autofac.IComponentContext context, System.Type serviceType, System.Collections.Generic.IEnumerable`1[T] parameters)
11
ResolutionExtensions.Resolve[TService] (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
12
ResolutionExtensions.Resolve[TService] (Autofac.IComponentContext context)
13
App+<OnStart>d__4.MoveNext ()
14
ExceptionDispatchInfo.Throw ()
15
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state)
16
SyncContext+<>c__DisplayClass2_0.<Post>b__0 ()
17
Thread+RunnableImplementor.Run ()
18
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
19
(wrapper dynamic-method) System.Object:f9684b08-49ee-4f47-8b7c-c59b675c18f3 (intptr,intptr)
</code>```

答:
So as your Stack Trace indicates. Autofac is trying to instantiate an instance of Eela.Taxi.Service.RestService. However, it seems like the Mono Linker has removed the constructor because it is never directly invoked.

So you could do a couple of things. You could:

Add your assembly to be ignored from the linker

You could add a [Preserve] attribute on your RestService to tell the Linker not to touch it

You could similar to what MvvmCross does have a LinkerPleaseInclude.cs file which describes usage of each type that get stripped out. So for every one you discover you will need to add it here.

So 1. and 2. are fairly self explanatory. You have already used 1. for autofac, just do the same for your own assembly containing RestService. However, the downside here is that nothing in this assembly will be linked, potentially leaving you with a lot more code in it than actually needed.

For 2. you simply add [Preserve] right before declaring your class. So something like:

[Preserve]
public class RestService : IRestService { }
```

<p>You may also consider using it with <code>AllMembers = true</code>: <code>[Preserve(AllMembers = true)]</code> to keep member fields too.</p>

<p>As for the last option. You basically create a <code>LinkerPleaseInclude.cs</code> in your App project. You let the linker do its job. You continue adding stuff to the class until the Linker does kill your App at runtime. So a start on <code>LinkerPleaseInclude.cs</code> could look like:</p>

<pre class="lang-cs prettyprint-override"><code>[Preserve(AllMembers = true)]
public class LinkerPleaseInclude
{
    public void Include(IRestService service)
    {
        service = new RestService();
    }
}
</code>```

This class is never invoked, but it is enough for the linker to know that the constructor of RestService should not be linked out.

Body:
When setting the Linker behaviour to "Link all" I get the following error at runtime:
Autofac.Core.DependencyResolutionException.

I've tried adding ignore assembly Autofac but without success.

Setting the Linker behavior to "Link Framework SDKs only" does work but I want to enable "Link All" if possible.

Thanks in advance.

Update :

ReflectionActivator.ActivateInstance (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
    Autofac.Core.DependencyResolutionException: No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.

No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.

An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = RestService (ReflectionActivator), Services = [Eela.Model.Xamarin.Interfaces.IRestService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.)

1
ReflectionActivator.ActivateInstance (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
2
InstanceLookup.Activate (System.Collections.Generic.IEnumerable`1[T] parameters)

An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = RestService (ReflectionActivator), Services = [Eela.Model.Xamarin.Interfaces.IRestService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.)

1
InstanceLookup.Activate (System.Collections.Generic.IEnumerable`1[T] parameters)
2
InstanceLookup.Execute ()
3
ResolveOperation.GetOrCreateInstance (Autofac.Core.ISharingLifetimeScope currentOperationScope, Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
4
ResolveOperation.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
5
ResolveOperation.Execute (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
6
LifetimeScope.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
7
Container.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
8
ResolutionExtensions.TryResolveService (Autofac.IComponentContext context, Autofac.Core.Service service, System.Collections.Generic.IEnumerable`1[T] parameters, System.Object& instance)
9
ResolutionExtensions.ResolveService (Autofac.IComponentContext context, Autofac.Core.Service service, System.Collections.Generic.IEnumerable`1[T] parameters)
10
ResolutionExtensions.Resolve (Autofac.IComponentContext context, System.Type serviceType, System.Collections.Generic.IEnumerable`1[T] parameters)
11
ResolutionExtensions.Resolve[TService] (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
12
ResolutionExtensions.Resolve[TService] (Autofac.IComponentContext context)
13
App+<OnStart>d__4.MoveNext ()
14
ExceptionDispatchInfo.Throw ()
15
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state)
16
SyncContext+<>c__DisplayClass2_0.<Post>b__0 ()
17
Thread+RunnableImplementor.Run ()
18
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
19
(wrapper dynamic-method) System.Object:f9684b08-49ee-4f47-8b7c-c59b675c18f3 (intptr,intptr)

Body:
So as your Stack Trace indicates. Autofac is trying to instantiate an instance of Eela.Taxi.Service.RestService. However, it seems like the Mono Linker has removed the constructor because it is never directly invoked.

So you could do a couple of things. You could:

Add your assembly to be ignored from the linker

You could add a [Preserve] attribute on your RestService to tell the Linker not to touch it

You could similar to what MvvmCross does have a LinkerPleaseInclude.cs file which describes usage of each type that get stripped out. So for every one you discover you will need to add it here.

So 1. and 2. are fairly self explanatory. You have already used 1. for autofac, just do the same for your own assembly containing RestService. However, the downside here is that nothing in this assembly will be linked, potentially leaving you with a lot more code in it than actually needed.

For 2. you simply add [Preserve] right before declaring your class. So something like:

[Preserve]
public class RestService : IRestService { }

You may also consider using it with AllMembers = true: [Preserve(AllMembers = true)] to keep member fields too.

As for the last option. You basically create a LinkerPleaseInclude.cs in your App project. You let the linker do its job. You continue adding stuff to the class until the Linker does kill your App at runtime. So a start on LinkerPleaseInclude.cs could look like:

[Preserve(AllMembers = true)]
public class LinkerPleaseInclude
{
    public void Include(IRestService service)
    {
        service = new RestService();
    }
}

This class is never invoked, but it is enough for the linker to know that the constructor of RestService should not be linked out.


问:
How to load from Json?
I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:

```<code>import json, urllib.request, requests

def findLocation():
"""returns latlng location value in the form of a list."""

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format
that can be used in python."""
    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['website'])
</code>```

Error:

```<code>Traceback (most recent call last):
  File "google api.py", line 28, in <module>
    print(search['website'])
TypeError: string indices must be integers
</code>```

Any help is appreciated.

答:
The function you are using readJsonUrl() returns a string not JSON. Therefore, when you try search['website'] it fails because the indices on a string can only be integers.
Try parsing the string value to a JSON object. To do this you can try the accepted answer here Convert string to JSON using Python

Title: How to load from Json?

Body:
I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:

import json, urllib.request, requests

def findLocation():
"""returns latlng location value in the form of a list."""

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format
that can be used in python."""
    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['website'])

Error:

Traceback (most recent call last):
  File "google api.py", line 28, in <module>
    print(search['website'])
TypeError: string indices must be integers

Any help is appreciated.


问:
PHP script will not recognize matching strings
I am trying to write a php script that will scroll through a list of strings in a text file and compare each string to user input from an html form.
If a match is found then the string the user entered should be posted to the screen. Somehow the comparison between the two strings never produces a match despite the presence of identical strings.

here is the php code

```<code><?php
session_start();
$myFile = "usernamelist.txt";

if (isset($_POST['originaluserid'])){//verifies the creation user input from the html page(for users signing up for the first time)
    $userid = $_POST['originaluserid'] . PHP_EOL;
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, $userid);
}

if(isset($_POST['userid'])){//verifies the existence of username information for an old user logging back in
    $userid = $_POST['userid'];
    $fh = fopen($myFile, 'r');
}

$theData = fgets($fh);

$_SESSION['id'] = $userid;//so that userid can be called in another page

if ($fh) {
    while (($line = fgets($fh)) !== false) {
        if($userid == $theData){//errors in matching input with collected data in text file
            echo "<html>
            <head></head>
            <body>
            <p>the ID of the user is: $userid</p> <!--I want userid to be displayed here-->
            <p>welcome to My Shopping Page</p>
            </body>
            </html>";
            exit;
        }
    }
    fclose($fh);
} else {
    echo "error";
    exit;
}

echo "access not granted";
?>
</code>```

here is the html code

```<code><html>
<head></head>
<body>
<form action="myshopping.php" method="post">
Log in with User ID:
<input type="text" name="userid">
<br>
<input type="submit">
<br>
Sign up for a brand new account:
<input type="text" name="originaluserid">
<br>
<input type="submit">
</form>

</body>
</html>
</code>```

and all that is in the text file ("usernamelist.txt") is:

```<code>username1
username2
username3
username4
</code>```

答:
Well first off you are using the variable $theData rather than the variable $line.  Also fgets doesn't strip white space characters including newlines so you'll need to use trim.  Try this and see if it works:

```<code>if (trim($userid) == trim($line)) {
</code>```

You'll also need to remove $theData = fgets($fh); because it's fetching the first line and it won't be checked with the above logic.

Body:
I am trying to write a php script that will scroll through a list of strings in a text file and compare each string to user input from an html form.
If a match is found then the string the user entered should be posted to the screen. Somehow the comparison between the two strings never produces a match despite the presence of identical strings.

here is the php code

<?php
session_start();
$myFile = "usernamelist.txt";

if (isset($_POST['originaluserid'])){//verifies the creation user input from the html page(for users signing up for the first time)
    $userid = $_POST['originaluserid'] . PHP_EOL;
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, $userid);
}

if(isset($_POST['userid'])){//verifies the existence of username information for an old user logging back in
    $userid = $_POST['userid'];
    $fh = fopen($myFile, 'r');
}

$theData = fgets($fh);

$_SESSION['id'] = $userid;//so that userid can be called in another page

if ($fh) {
    while (($line = fgets($fh)) !== false) {
        if($userid == $theData){//errors in matching input with collected data in text file
            echo "

the ID of the user is: $userid

welcome to My Shopping Page

            ";
            exit;
        }
    }
    fclose($fh);
} else {
    echo "error";
    exit;
}

echo "access not granted";
?>

here is the html code

<form action="myshopping.php" method="post">
Log in with User ID:
<input type="text" name="userid">

<input type="submit">

Sign up for a brand new account:
<input type="text" name="originaluserid">

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

and all that is in the text file ("usernamelist.txt") is:

username1
username2
username3
username4

Body:
Well first off you are using the variable $theData rather than the variable $line.  Also fgets doesn't strip white space characters including newlines so you'll need to use trim.  Try this and see if it works:

if (trim($userid) == trim($line)) {

You'll also need to remove $theData = fgets($fh); because it's fetching the first line and it won't be checked with the above logic.


问:
Ionic 3 lazy-loading on a tab
I want to add a new tab to my project using lazy-loading.

I am using the @IonicPage decorator for a page that will be the root page of a tab.

My new page:

```<code>// module
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { UsersPage } from './users';

@NgModule({
  declarations: [
    UsersPage,
  ],
  imports: [
    IonicPageModule.forChild(UsersPage),
  ],
})
export class UsersPageModule {}

// page
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-users',
  templateUrl: 'users.html',
})
export class UsersPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad UsersPage');
  }

}
</code>```

And try to use it in my tabs:

```<code>// tabs.ts
export class TabsPage {
  @ViewChild(Tabs) tabs: Tabs;
  @ViewChild('findTab') findTab: ElementRef;

  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = HomePage;
  tab2Root: any = FindPage;
  usersPage: any = "UsersPageModule";
  tab4Root: any = ChatsPage;

  findTabParams: any = {};
  subscriptions: any[] = [];
  totalUnreadMessages: FirebaseObjectObservable<any>;
  unread: boolean;
  anyUnread: boolean;
  ...

// tabs.html
<ion-tabs #tabs>
  <ion-tab [root]="tab1Root" tabIcon="home"></ion-tab>
  <ion-tab #findTab [root]="tab2Root" [rootParams]="findTabParams" tabIcon="calendar"></ion-tab>
  <ion-tab [root]="usersPage" tabIcon="person"></ion-tab>
  <ion-tab [root]="tab4Root" tabIcon="chatbubbles" [tabBadge]="unread?1:null" [tabsHideOnSubPages]=true></ion-tab>
</ion-tabs>
</code>```

But I get the following error:

```<code>Uncaught (in promise): invalid link: UsersPageModule
</code>```

Even if re-running ionic serve

答:
You should not use the module of the page, but the page itself:

```<code>  // ...

  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = HomePage;
  tab2Root: any = FindPage;
  usersPage: any = 'UsersPage'; // <--- here! :)
  tab4Root: any = ChatsPage;

  // ...
</code>```

Title: Ionic 3 lazy-loading on a tab

Body:
I want to add a new tab to my project using lazy-loading.

I am using the @IonicPage decorator for a page that will be the root page of a tab.

My new page:

// module
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { UsersPage } from './users';

@NgModule({
  declarations: [
    UsersPage,
  ],
  imports: [
    IonicPageModule.forChild(UsersPage),
  ],
})
export class UsersPageModule {}

// page
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-users',
  templateUrl: 'users.html',
})
export class UsersPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad UsersPage');
  }

}

And try to use it in my tabs:

// tabs.ts
export class TabsPage {
  @ViewChild(Tabs) tabs: Tabs;
  @ViewChild('findTab') findTab: ElementRef;

  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = HomePage;
  tab2Root: any = FindPage;
  usersPage: any = "UsersPageModule";
  tab4Root: any = ChatsPage;

  findTabParams: any = {};
  subscriptions: any[] = [];
  totalUnreadMessages: FirebaseObjectObservable<any>;
  unread: boolean;
  anyUnread: boolean;
  ...

// tabs.html
<ion-tabs #tabs>
  <ion-tab [root]="tab1Root" tabIcon="home"></ion-tab>
  <ion-tab #findTab [root]="tab2Root" [rootParams]="findTabParams" tabIcon="calendar"></ion-tab>
  <ion-tab [root]="usersPage" tabIcon="person"></ion-tab>
  <ion-tab [root]="tab4Root" tabIcon="chatbubbles" [tabBadge]="unread?1:null" [tabsHideOnSubPages]=true></ion-tab>
</ion-tabs>

But I get the following error:

Uncaught (in promise): invalid link: UsersPageModule

Even if re-running ionic serve

Body:
You should not use the module of the page, but the page itself:

  // ...

  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = HomePage;
  tab2Root: any = FindPage;
  usersPage: any = 'UsersPage'; // <--- here! :)
  tab4Root: any = ChatsPage;

  // ...


问:
Different xquery result between Let and For when using "every" clause
I have the following Xquery:

```<code>let $x := <a>
           <i>false</i>
          </a>
return
    if (every $t in $x/a satisfies $t/i eq "true")
    then $x
    else <nothing/>
</code>```

How I interpret this is, return $x if all  have an  that has the word "true". However, this always return $x.

In contrast, if I have the following XML doc:

```<code><root>
  <a><i>false</i></a>
</root>
</code>```

and the following query:

```<code>for $x in /root
return
    if (every $t in $x/a satisfies $t/i eq "true" )
    then $x
    else <nothing/>
</code>```

It will return <nothing/> when  contains false and will return $x when  is "true"

My questions are:

Why does the query with "let" behave the way it does?

Why does the query with "for" behave differently?

答:
The key difference is the existence of a root element assigned to $x in the second example, but not in the first.

In your first example the root element is , but in your quantifier expression you write every $t in $x/a. $x/a selects child a elements of , and there are none (only i). So $x/a evaluates to empty. The expression is reduced to every $t in () satisfies $t/i eq "true". Since empty is assigned to $t the full quantifier expression evaluates to true.

Body:
I have the following Xquery:

let $x :=
           false

return
    if (every $t in $x/a satisfies $t/i eq "true")
    then $x
    else <nothing/>

How I interpret this is, return $x if all  have an  that has the word "true". However, this always return $x.

In contrast, if I have the following XML doc:

<root>
  false
</root>

and the following query:

for $x in /root
return
    if (every $t in $x/a satisfies $t/i eq "true" )
    then $x
    else <nothing/>

It will return <nothing/> when  contains false and will return $x when  is "true"

My questions are:

Why does the query with "let" behave the way it does?

Why does the query with "for" behave differently?

Body:
The key difference is the existence of a root element assigned to $x in the second example, but not in the first.

In your first example the root element is <a>, but in your quantifier expression you write every $t in $x/a. $x/a selects child a elements of <a>, and there are none (only i). So $x/a evaluates to empty. The expression is reduced to every $t in () satisfies $t/i eq "true". Since empty is assigned to $t the full quantifier expression evaluates to true.


问:
function that calls to author functions (python)
I'm trying to make a map that takes a function that calls other functions, and a list of functions - so here is what I've put in:

```<code>    def function1():
      return 3

    def function2():
      return 4

    def List_Of_Functions(My_Function):
      return My_Function

    print(list(map(List_Of_Functions, [function1, function2])))
</code>```

but this is what I get in the result:

```<code>[<function function1 at 0x7f5e6797a620>, <function function2 at 0x7f5e6797a730>]
</code>```

I'm new to Python so any explanation would be much appreciated.

答:
You missed function1() and function2() in the last statement

```<code>def function1():
    return 3

def function2():
    return 4

def List_Of_Functions(My_Function):
    return My_Function

print(list(map(List_Of_Functions, [function1(), function2()])))
</code>```

Body:
I'm trying to make a map that takes a function that calls other functions, and a list of functions - so here is what I've put in:

    def function1():
      return 3

    def function2():
      return 4

    def List_Of_Functions(My_Function):
      return My_Function

    print(list(map(List_Of_Functions, [function1, function2])))

but this is what I get in the result:

[<function function1 at 0x7f5e6797a620>, <function function2 at 0x7f5e6797a730>]

I'm new to Python so any explanation would be much appreciated.

Body:
You missed function1() and function2() in the last statement

def function1():
    return 3

def function2():
    return 4

def List_Of_Functions(My_Function):
    return My_Function

print(list(map(List_Of_Functions, [function1(), function2()])))


问:
raster diagrams in Matlab based on colormap
I would like to create raster plots in Matlab based on my colormap jet. My colormap jet goes from -3 (blue) to +3 (red). So, I would like to plot the exact value of my data (e.g., +1.20) as the corresponding colour on the colormap jet (e.g., yellow).

However, at the moment I have a structure A of 66x900 double with values of 0 and 1, and a structure B of 66x900 double with different values in each cell (e.g., 0.21, +2.45, -1.09, etc.).

What I need to do is (1) to replace the values equal to 1 in structure A with the exact values of structure B. (2) I would need to plot the new structure (e.g., C) which is made of zeros and of values from structure B.

The tricky part is that in the raster plot, I would only need to plot with the colour of the colourmap jet the values/cells of structure C that were taken from structure B (including when those values were equal to zeros). Those cells that are equal to zero (those that were not replaced with values from structure B, as they were zeros already in structure A) need to become white pixels.

Example:

```<code> Structure A
 0 **1** 0 0 0 **1** 0 **1** **1**   0     0
 0 **1** 0 0 0   0   0 **1** **1**   0     0
 0   0   0 0 0   0   0 **1** **1** **1** **1**
 0   0   0 0 0   0   0 **1** **1** **1** **1**

 Structure B
  1.2   **1.34**  2.34  1.33   1.43 **-2.99**  2.44  **1.27** **-2.76**   0.09      0.00
 -2.3   **0.45**  2.99  2.01  -2.19   -0.98    0.56 **-1.87**  **2.14**   0.00     -0.98
 -0.3     1.20   -0.17  1.2   -2.33   -0.67    1.23  **1.45**  **1.08** **1.01**  **0.00**
  1.11   -0.78   -1.66 -0.88   0.12   -1.04   -0.55  **1.32**  **1.34** **1.00**  **1.97**

 Structure C
  0   **1.34**  0 0   0 **-2.99**  0  **1.27** **-2.76**   0         0
  0   **0.45**  0 0   0    0       0 **-1.87**  **2.14**   0         0
  0     0       0 0   0    0       0  **1.45**  **1.08** **1.01**  **0.00**
  0     0       0 0   0    0       0  **1.32**  **1.34** **1.00**  **1.97**
</code>```

答:
(1) You want to multiply each element of the matrix A with its corresponding element in matrix B. This is done by adding a dot before the multiplication symbol (it also works for division and exponentials).

(2) NaN values are left blank in Matlab plot.

Here's a working example:

```<code>% Your data
A = [1 1 1 1 1 1; 0 0 1 1 1 1; 1 1 1 0 1 1; 1 1 1 1 1 1; 1 1 1 1 1 1; 1 1 1 1 1 1];
B = [1 2 3 4 5 2; 5 4 0 0 0 4; 1 2 3 4 1 2; 5 5 5 3 3 3; 5 2 2 2 3 3; 5 1 5 3 4 4];
% Set all elements equal to zero to NaN so Matlab doesn't draw them
A(A==0) = NaN;
% This returns C(i,j) = A(i,j)*B(i,j) for all elements.
% A*B would do a matrix multiplication
C = A.*B;
%Plot
pcolor(C)
</code>```

Body:
I would like to create raster plots in Matlab based on my colormap jet. My colormap jet goes from -3 (blue) to +3 (red). So, I would like to plot the exact value of my data (e.g., +1.20) as the corresponding colour on the colormap jet (e.g., yellow).

However, at the moment I have a structure A of 66x900 double with values of 0 and 1, and a structure B of 66x900 double with different values in each cell (e.g., 0.21, +2.45, -1.09, etc.).

What I need to do is (1) to replace the values equal to 1 in structure A with the exact values of structure B. (2) I would need to plot the new structure (e.g., C) which is made of zeros and of values from structure B.

The tricky part is that in the raster plot, I would only need to plot with the colour of the colourmap jet the values/cells of structure C that were taken from structure B (including when those values were equal to zeros). Those cells that are equal to zero (those that were not replaced with values from structure B, as they were zeros already in structure A) need to become white pixels.

Example:

 Structure A
 0 **1** 0 0 0 **1** 0 **1** **1**   0     0
 0 **1** 0 0 0   0   0 **1** **1**   0     0
 0   0   0 0 0   0   0 **1** **1** **1** **1**
 0   0   0 0 0   0   0 **1** **1** **1** **1**

 Structure B
  1.2   **1.34**  2.34  1.33   1.43 **-2.99**  2.44  **1.27** **-2.76**   0.09      0.00
 -2.3   **0.45**  2.99  2.01  -2.19   -0.98    0.56 **-1.87**  **2.14**   0.00     -0.98
 -0.3     1.20   -0.17  1.2   -2.33   -0.67    1.23  **1.45**  **1.08** **1.01**  **0.00**
  1.11   -0.78   -1.66 -0.88   0.12   -1.04   -0.55  **1.32**  **1.34** **1.00**  **1.97**

 Structure C
  0   **1.34**  0 0   0 **-2.99**  0  **1.27** **-2.76**   0         0
  0   **0.45**  0 0   0    0       0 **-1.87**  **2.14**   0         0
  0     0       0 0   0    0       0  **1.45**  **1.08** **1.01**  **0.00**
  0     0       0 0   0    0       0  **1.32**  **1.34** **1.00**  **1.97**

Body:
(1) You want to multiply each element of the matrix A with its corresponding element in matrix B. This is done by adding a dot before the multiplication symbol (it also works for division and exponentials).

(2) NaN values are left blank in Matlab plot.

Here's a working example:

% Your data
A = [1 1 1 1 1 1; 0 0 1 1 1 1; 1 1 1 0 1 1; 1 1 1 1 1 1; 1 1 1 1 1 1; 1 1 1 1 1 1];
B = [1 2 3 4 5 2; 5 4 0 0 0 4; 1 2 3 4 1 2; 5 5 5 3 3 3; 5 2 2 2 3 3; 5 1 5 3 4 4];
% Set all elements equal to zero to NaN so Matlab doesn't draw them
A(A==0) = NaN;
% This returns C(i,j) = A(i,j)*B(i,j) for all elements.
% A*B would do a matrix multiplication
C = A.*B;
%Plot
pcolor(C)


问:
Cannot convert value of type '[String]' to expected argument type 'String'
I have a array (from a global constants file) which I am trying to use in an API call to make another dictionary array. The initial array is:

```<code>let callCountries = ["AU" : "Australia", "NZ" : "New Zealand", "UK" : "United Kingdom", "ZA" : "South Africa", "US" : "United States"]
</code>```

I then just want to grab the country shortcode and loop through it to build a new array as per below...

```<code>func getCallCentreNumbers(){

    var countrykeys = Array(callCountries.keys)

    API.getJudeContactNumbers({response in

            self.judeCallCentreNumberDict =  [
                countrykeys : (response.value(forKey: countrykeys) as! String),
        ]

    })

}
</code>```

The initial line of code without the array values being inserted was:

```<code>self.judeCallCentreNumberDict =  [
                "ZM" : (response.value(forKey: "ZM") as! String),
        ]
</code>```

I want to replace the "ZM"s with the countrykeys variable but cannot work this one out. (Sorry I am still quite a newbie). Can anyone point me in the right direction?

答:
I would suggest a loop through out the response

First try to clear judeCallCentreNumberDict before making the request

```<code>judeCallCentreNumberDict = [:]
</code>```

Then when you have the response make an array of the keys and loop through it

(inside API.getJudeContactNumbers({response in)

```<code>let countrykeys = callCountries.map { $0.key }

countrykeys.forEach {
    guard let value = response.value(forKey: $0) as? String else { return }
    judeCallCentreNumberDict[$0] = value
}
</code>```

Note:

$0 means the current item in the loop (in this case it will be one of the keys)

I'm guessing that judeCallCentreNumberDict is of type [String:String] so we can add to it only values of type String not String? and that is what the guard is for

Body:
I have a array (from a global constants file) which I am trying to use in an API call to make another dictionary array. The initial array is:

let callCountries = ["AU" : "Australia", "NZ" : "New Zealand", "UK" : "United Kingdom", "ZA" : "South Africa", "US" : "United States"]

I then just want to grab the country shortcode and loop through it to build a new array as per below...

func getCallCentreNumbers(){

    var countrykeys = Array(callCountries.keys)

    API.getJudeContactNumbers({response in

            self.judeCallCentreNumberDict =  [
                countrykeys : (response.value(forKey: countrykeys) as! String),
        ]

    })

}

The initial line of code without the array values being inserted was:

self.judeCallCentreNumberDict =  [
                "ZM" : (response.value(forKey: "ZM") as! String),
        ]

I want to replace the "ZM"s with the countrykeys variable but cannot work this one out. (Sorry I am still quite a newbie). Can anyone point me in the right direction?

Body:
I would suggest a loop through out the response

First try to clear judeCallCentreNumberDict before making the request

judeCallCentreNumberDict = [:]

Then when you have the response make an array of the keys and loop through it

(inside API.getJudeContactNumbers({response in)

let countrykeys = callCountries.map { $0.key }

countrykeys.forEach {
    guard let value = response.value(forKey: $0) as? String else { return }
    judeCallCentreNumberDict[$0] = value
}

Note:

$0 means the current item in the loop (in this case it will be one of the keys)

I'm guessing that judeCallCentreNumberDict is of type [String:String] so we can add to it only values of type String not String? and that is what the guard is for


答:
Random values:

```<code>a = double(randi([0 1],[4 11]));
b = rand(4,11);
</code>```

Then:

```<code>idx = find(a == 1);
a(idx) = b(idx);
</code>```

And here you have your colormap.

To obtain the white pixels (NaN will just make them transparent so they will take the background color):

```<code>a(a == 0) = 1;
</code>```

Then, plot it:

```<code>colormap(gray);
pcolor(a);
</code>```

Title: raster diagrams in Matlab based on colormap

Body:
Random values:

a = double(randi([0 1],[4 11]));
b = rand(4,11);

Then:

idx = find(a == 1);
a(idx) = b(idx);

And here you have your colormap.

To obtain the white pixels (NaN will just make them transparent so they will take the background color):

a(a == 0) = 1;

Then, plot it:

colormap(gray);
pcolor(a);


问:
cycle a tar list and view tar filename that contains a specific file
In a filename*.tar.gz list, I need to view the tar file name where there is the file1.txt.
How can I improve this instruction ?

```<code>for file in filename*.tar.gz; do tar -ztvf "$file" | grep 'file1.txt'  ;done
</code>```

答:
What you have so far will print the entry in a tar that matches the pattern "file1.txt", but it will not print the name of the tar file itself that contains the entry.

If you want to print the name of the tar file that contains file1.txt, you can use a conditional statement like this:

```<code>for file in filename*.tar.gz; do
    if tar ztf "$file" | grep -q file1.txt; then
        echo "$file"
    fi
done
</code>```

The condition here is the exit code of grep. If the pattern is found, grep exits with zero, which means success, and the echo "$file" will be executed.

Also note that I added the -q flag to grep to make it quiet, and do not print the matched line, as it does by default. With this flag, grep outputs nothing, and that's fine, we need only the exit code to decide the conditional statement.

A more compact equivalent:

```<code>for file in filename*.tar.gz; do
    tar ztf "$file" | grep -q file1.txt && echo "$file"
done
</code>```

Body:
In a filename*.tar.gz list, I need to view the tar file name where there is the file1.txt.
How can I improve this instruction ?

for file in filename*.tar.gz; do tar -ztvf "$file" | grep 'file1.txt'  ;done

Body:
What you have so far will print the entry in a tar that matches the pattern "file1.txt", but it will not print the name of the tar file itself that contains the entry.

If you want to print the name of the tar file that contains file1.txt, you can use a conditional statement like this:

for file in filename*.tar.gz; do
    if tar ztf "$file" | grep -q file1.txt; then
        echo "$file"
    fi
done

The condition here is the exit code of grep. If the pattern is found, grep exits with zero, which means success, and the echo "$file" will be executed.

Also note that I added the -q flag to grep to make it quiet, and do not print the matched line, as it does by default. With this flag, grep outputs nothing, and that's fine, we need only the exit code to decide the conditional statement.

A more compact equivalent:

for file in filename*.tar.gz; do
    tar ztf "$file" | grep -q file1.txt && echo "$file"
done