问:
Extracting results from a txt to csv
I am trying to extract some results i've got into a csv file, from a text one.
The results.txt has this form and I wanted to extract it in the following form as csv:

```<code>Benchmark,        Pass/Fail,     ops/m
compiler.compiler, PASSED,       18.37
compress,          PASSED,       10.87
crypto.aes,        PASSED,        3.91
</code>```

etc...

So I want to keep only the iteration 1 results, in that form. What would you suggest me to do?

Thank you!

答:
The following Python 2.x script should help to get you started (as was originally tagged). The results.txt file can be passed for lines containing iteration 1 as follows:

```<code>import csv
from itertools import ifilter

with open('results.txt', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(ifilter(lambda x: "iteration 1" in x, f_input), delimiter=' ', skipinitialspace=True)
    csv_output = csv.writer(f_output)
    csv_output.writerow(["Benchmark", "Pass/Fail", "ops/m"])

    for row in csv_input:
        csv_output.writerow([row[0], 'PASSED', row[6]])
</code>```

Creating an output CSV file as follows:

Benchmark,Pass/Fail,ops/m
compiler.compiler,PASSED,18.37
compress,PASSED,10.87
crypto.aes,PASSED,3.91
crypto.rsa,PASSED,8.79
crypto.signverify,PASSED,15.10
derby,PASSED,9.40
mpegaudio,PASSED,7.81
scimark.fft.large,PASSED,4.27
scimark.lu.large,PASSED,0.85
scimark.sor.large,PASSED,2.38
scimark.sparse.large,PASSED,1.46
scimark.monte_carlo,PASSED,5.65
scimark.fft.small,PASSED,8.94
scimark.lu.small,PASSED,8.24
scimark.sor.small,PASSED,12.90
scimark.sparse.small,PASSED,5.61
serial,PASSED,4.53
startup.helloworld,PASSED,41.24
startup.compiler.compiler,PASSED,2.05
startup.compress,PASSED,3.62
startup.crypto.aes,PASSED,0.92
startup.crypto.rsa,PASSED,1.87
startup.crypto.signverify,PASSED,2.76
startup.mpegaudio,PASSED,1.82
startup.scimark.fft,PASSED,4.49
startup.scimark.lu,PASSED,2.44
startup.scimark.monte_carlo,PASSED,1.27
startup.scimark.sor,PASSED,3.14
startup.scimark.sparse,PASSED,1.54
startup.serial,PASSED,1.73
startup.sunflow,PASSED,3.55
startup.xml.transform,PASSED,0.27
startup.xml.validation,PASSED,4.28
sunflow,PASSED,3.69
xml.transform,PASSED,10.41
xml.validation,PASSED,15.37
```

However, it simply assumes all entries in the file are considered PASSED as there is no example showing what a failed entry would look like in the sample file.

Title: Extracting results from a txt to csv

Body:
I am trying to extract some results i've got into a csv file, from a text one.
The results.txt has this form and I wanted to extract it in the following form as csv:

Benchmark,        Pass/Fail,     ops/m
compiler.compiler, PASSED,       18.37
compress,          PASSED,       10.87
crypto.aes,        PASSED,        3.91

etc...

So I want to keep only the iteration 1 results, in that form. What would you suggest me to do?

Thank you!

Body:
The following Python 2.x script should help to get you started (as was originally tagged). The results.txt file can be passed for lines containing iteration 1 as follows:

import csv
from itertools import ifilter

with open('results.txt', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(ifilter(lambda x: "iteration 1" in x, f_input), delimiter=' ', skipinitialspace=True)
    csv_output = csv.writer(f_output)
    csv_output.writerow(["Benchmark", "Pass/Fail", "ops/m"])

    for row in csv_input:
        csv_output.writerow([row[0], 'PASSED', row[6]])

Creating an output CSV file as follows:

Benchmark,Pass/Fail,ops/m
compiler.compiler,PASSED,18.37
compress,PASSED,10.87
crypto.aes,PASSED,3.91
crypto.rsa,PASSED,8.79
crypto.signverify,PASSED,15.10
derby,PASSED,9.40
mpegaudio,PASSED,7.81
scimark.fft.large,PASSED,4.27
scimark.lu.large,PASSED,0.85
scimark.sor.large,PASSED,2.38
scimark.sparse.large,PASSED,1.46
scimark.monte_carlo,PASSED,5.65
scimark.fft.small,PASSED,8.94
scimark.lu.small,PASSED,8.24
scimark.sor.small,PASSED,12.90
scimark.sparse.small,PASSED,5.61
serial,PASSED,4.53
startup.helloworld,PASSED,41.24
startup.compiler.compiler,PASSED,2.05
startup.compress,PASSED,3.62
startup.crypto.aes,PASSED,0.92
startup.crypto.rsa,PASSED,1.87
startup.crypto.signverify,PASSED,2.76
startup.mpegaudio,PASSED,1.82
startup.scimark.fft,PASSED,4.49
startup.scimark.lu,PASSED,2.44
startup.scimark.monte_carlo,PASSED,1.27
startup.scimark.sor,PASSED,3.14
startup.scimark.sparse,PASSED,1.54
startup.serial,PASSED,1.73
startup.sunflow,PASSED,3.55
startup.xml.transform,PASSED,0.27
startup.xml.validation,PASSED,4.28
sunflow,PASSED,3.69
xml.transform,PASSED,10.41
xml.validation,PASSED,15.37

However, it simply assumes all entries in the file are considered PASSED as there is no example showing what a failed entry would look like in the sample file.


来源: stackexchange

问:
confused with mobile friendly websites or related
I read somewhere that once you log in here (http://skweezer.com/) and put the website url, we can get the way the site will appear on mobile browsers. I tried getting this url (http://sachindra149.wordpress.com/) and was baffled to see he way it looked.

1) Can anyone please let me know why is that so ??

2) Why such a major difference???

3) And also what needs to be done ...

keeping one thing in mind that I dont have the control over the web codes for the page as it is a blog....
Hope I am clear enough !!!!!!!!

答:
First of all, it's not as bad as it looks. Mobile device have only very limited resources but they are much better today.

What you see on skweezer.com is just the raw text without CSS styling, tables and other complicated HTML. This way, the site loads much (!) faster and you only transfer a fraction of the data. Your original site needs 320KB, the skweezer version needs 50KB - less than 1/6th. Mobile browsing got much faster and cheaper but it's still many times slower and more expensive than on the desktop.

As for what you can do about it: Not much. You could select a design which is optimized for mobile devices but to know how good it looks, you would need all mobile devices that access your site. I suggest to rely on the experience of the designers at Wordpress. Your site does look much better on most mobile devices.

ContentLicense: CC BY-SA 2.5


问:
How to open mail app from Swift
Im working on a simple swift app where the user inputs an email address and presses a button which opens the mail app, with the entered address in the address bar. I know how to do this in Objective-C, but I'm having trouble getting it to work in Swift.</p>

答:
```<code>@IBAction func launchEmail(sender: AnyObject) {
 if if MFMailComposeViewController.canSendMail() {
   var emailTitle = "Feedback"
   var messageBody = "Feature request or bug report?"
   var toRecipents = ["friend@stackoverflow.com"]
   var mc: MFMailComposeViewController = MFMailComposeViewController()
   mc.mailComposeDelegate = self
   mc.setSubject(emailTitle)
   mc.setMessageBody(messageBody, isHTML: false)
   mc.setToRecipients(toRecipents)

   self.present(mc, animated: true, completion: nil)
 } else {
   // show failure alert
 }
}

func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
    switch result {
    case .cancelled:
        print("Mail cancelled")
    case .saved:
        print("Mail saved")
    case .sent:
        print("Mail sent")
    case .failed:
        print("Mail sent failure: \(error?.localizedDescription)")
    default:
        break
    }
    self.dismiss(animated: true, completion: nil)
}
</code>```

Note that not all users have their device configure to send emails, which is why we need to check the result of canSendMail() before trying to send. Note also that you need to catch the didFinishWith callback in order to dismiss the mail window.

ContentLicense: CC BY-SA 3.0

Title: How to open mail app from Swift

Body:
@IBAction func launchEmail(sender: AnyObject) {
 if if MFMailComposeViewController.canSendMail() {
   var emailTitle = "Feedback"
   var messageBody = "Feature request or bug report?"
   var toRecipents = ["friend@stackoverflow.com"]
   var mc: MFMailComposeViewController = MFMailComposeViewController()
   mc.mailComposeDelegate = self
   mc.setSubject(emailTitle)
   mc.setMessageBody(messageBody, isHTML: false)
   mc.setToRecipients(toRecipents)

   self.present(mc, animated: true, completion: nil)
 } else {
   // show failure alert
 }
}

func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
    switch result {
    case .cancelled:
        print("Mail cancelled")
    case .saved:
        print("Mail saved")
    case .sent:
        print("Mail sent")
    case .failed:
        print("Mail sent failure: \(error?.localizedDescription)")
    default:
        break
    }
    self.dismiss(animated: true, completion: nil)
}

Note that not all users have their device configure to send emails, which is why we need to check the result of canSendMail() before trying to send. Note also that you need to catch the didFinishWith callback in order to dismiss the mail window.


问:
Classifying PDF Text Documents based on the presence/absence of specific words in R
I would like to be able to import PDF documents into R and classify them as either:

Relevant (contains a specific string, for example, "tacos", within the first 100 words)

Irrelevant (DOES NOT contain "tacos" within the first 100 words)

To be more specific, I would like to address the following questions:

Does a package(s) exist in R to perform this basic classification?

If so, is it possible to generate a dataset that would look something like this in R if I had 2 PDF documents with Paper1 containing at least one instance of the string, "tacos", in the first 100 words and Paper2 that DOES NOT contain at least one instance of the string, "tacos":

Any references to documentation/R packages/sample R code or mock examples related to this type of classification using R would be greatly appreciated! Thanks!

答:
While @lukeA beat me to it, I wrote another small function that uses pdftools as well. The only real difference is that lukeA looks at the first n-characters, and my skript looks at the first n words.

This is how my approach looks

```<code>library(pdftools)
library(dplyr) # for data_frames and bind_rows

# to find the files better
setwd("~/Desktop/pdftask/")

# list all files in the folder "pdfs"
pdf_files <- list.files("pdfs/", full.names = T)

# write a small function that takes a vector of paths to pdf-files, a search term,
# and a number of words (i.e., look at the first 100 words)
search_pdf <- function(pdf_files, search_term, n_words = 100) {
  # loop over the files
  res_list <- lapply(pdf_files, function(file) {
    # use the library pdftools::pdf_text to extract the text from the pdf
    content <- pdf_text(file)

    # do some cleanup, i.e., remove punctuation, new-lines and lower all letters
    content2 <- tolower(content)
    content2 <- gsub("\\n", "", content2)
    content2 <- gsub("[[:punct:]]", "", content2)

    # split up the text by spaces
    content_vec <- strsplit(content2, " ")[[1]]

    # look if the search term is within the first n_words words
    found <- search_term %in% content_vec[1:n_words]

    # create a data_frame that holds our data
    res <- data_frame(file = file,
                      relevance = ifelse(found,
                                         "Relevant",
                                         "Irrelevant"))
    return(res)
  })

  # bind the data to a "tidy" data_frame
  res_df <- bind_rows(res_list)
  return(res_df)
}

search_pdf(pdf_files, search_term = "taco", n_words = 100)

# # A tibble: 3 × 2
#                          file  relevance
#                         <chr>      <chr>
# 1         pdfs//pdf_empty.pdf Irrelevant
# 2         pdfs//pdf_taco1.pdf   Relevant
# 3 pdfs//pdf_taco_above100.pdf Irrelevant
</code>```

Body:
While @lukeA beat me to it, I wrote another small function that uses pdftools as well. The only real difference is that lukeA looks at the first n-characters, and my skript looks at the first n words.

This is how my approach looks

library(pdftools)
library(dplyr) # for data_frames and bind_rows

# to find the files better
setwd("~/Desktop/pdftask/")

# list all files in the folder "pdfs"
pdf_files <- list.files("pdfs/", full.names = T)

# write a small function that takes a vector of paths to pdf-files, a search term,
# and a number of words (i.e., look at the first 100 words)
search_pdf <- function(pdf_files, search_term, n_words = 100) {
  # loop over the files
  res_list <- lapply(pdf_files, function(file) {
    # use the library pdftools::pdf_text to extract the text from the pdf
    content <- pdf_text(file)

    # do some cleanup, i.e., remove punctuation, new-lines and lower all letters
    content2 <- tolower(content)
    content2 <- gsub("\\n", "", content2)
    content2 <- gsub("[[:punct:]]", "", content2)

    # split up the text by spaces
    content_vec <- strsplit(content2, " ")[[1]]

    # look if the search term is within the first n_words words
    found <- search_term %in% content_vec[1:n_words]

    # create a data_frame that holds our data
    res <- data_frame(file = file,
                      relevance = ifelse(found,
                                         "Relevant",
                                         "Irrelevant"))
    return(res)
  })

  # bind the data to a "tidy" data_frame
  res_df <- bind_rows(res_list)
  return(res_df)
}

search_pdf(pdf_files, search_term = "taco", n_words = 100)

# # A tibble: 3 × 2
#                          file  relevance
#                         <chr>      <chr>
# 1         pdfs//pdf_empty.pdf Irrelevant
# 2         pdfs//pdf_taco1.pdf   Relevant
# 3 pdfs//pdf_taco_above100.pdf Irrelevant


问:
JPA perfomance with case insensitive in select
I have a JPA select where you receibe a parameter then we can search using some attributes (username, email, identifier) The user only have a text field to write the criteria text.

The problem is perfomance, in the database We have about 9Millions of users registereds, and the search is too slow, using JPA,

Form:
  - Value (Input text)

User sends the value in the form (He doesn't say if he is using username, email or identifier)

User (Table) Fields:
  - Identifier
  - Name
  - Email

JPA Query:

```<code>select u from UserEntity u where u.alias LIKE lower(:query) OR u.email LIKE lower(:query) OR lower(u.identifier) LIKE lower(:query) ORDER BY u.alias
</code>```

I don't know what the best method to improve the speed of the search, (We have some indexes in the table in these fields), if we remove the lower in the u.identifier field the speed improves a lot (almost instant). But we can have the identifier in a lot of ways (migrations, registers, manual client inserts..)

答:
We have about 9 Millions of users registered, and the search is too slow, using JPA

Please note the search will be too slow regardless the technology involved in executing the query just because the SQL query itself is too slow. That being said the problem is not JPA but how to improve the SQL query.

Combining LOWER() function with LIKE operator adds a lot of overhead because the RDBMS must apply a text function to 3 fields before analyse the LIKE match.

IMHO a good approach is using a VIEW to leverage the LOWER() part on the 3 fields and then execute the query over this view (BTW mapping a View with JPA is just as simple as mapping a Table):

```<code>CRAETE VIEW user_view AS SELECT id, lower(identifier) AS identifier, lower(alias) AS alias, lower(email) AS email FROM user;
</code>```

Then create an entity for searching:

```<code>@Entity
@Table("user_view")
public class UserView {

    @Basic private Long id;
    @Basic private String identifier;
    @Basic private String alias;
    @Basic private String email;

    // getters and setters as required
}
</code>```

And finally the JPQL query:

```<code>String jqpl = "SELECT u FROM UserView u WHERE u.alias LIKE :query OR u.email LIKE :query OR u.identifier LIKE :query";
</code>```

Note that you can pass query parameter directly in lower case as a Query parameter and you can order the result list after the query execution. Both will result in the RDBMS making less effort and consequently improving the overall response time.

Body:
I have a JPA select where you receibe a parameter then we can search using some attributes (username, email, identifier) The user only have a text field to write the criteria text.

The problem is perfomance, in the database We have about 9Millions of users registereds, and the search is too slow, using JPA,

Form:
  - Value (Input text)

User sends the value in the form (He doesn't say if he is using username, email or identifier)

User (Table) Fields:
  - Identifier
  - Name
  - Email

JPA Query:

select u from UserEntity u where u.alias LIKE lower(:query) OR u.email LIKE lower(:query) OR lower(u.identifier) LIKE lower(:query) ORDER BY u.alias

I don't know what the best method to improve the speed of the search, (We have some indexes in the table in these fields), if we remove the lower in the u.identifier field the speed improves a lot (almost instant). But we can have the identifier in a lot of ways (migrations, registers, manual client inserts..)

Body:
We have about 9 Millions of users registered, and the search is too slow, using JPA

Please note the search will be too slow regardless the technology involved in executing the query just because the SQL query itself is too slow. That being said the problem is not JPA but how to improve the SQL query.

Combining LOWER() function with LIKE operator adds a lot of overhead because the RDBMS must apply a text function to 3 fields before analyse the LIKE match.

IMHO a good approach is using a VIEW to leverage the LOWER() part on the 3 fields and then execute the query over this view (BTW mapping a View with JPA is just as simple as mapping a Table):

CRAETE VIEW user_view AS SELECT id, lower(identifier) AS identifier, lower(alias) AS alias, lower(email) AS email FROM user;

Then create an entity for searching:

@Entity
@Table("user_view")
public class UserView {

    @Basic private Long id;
    @Basic private String identifier;
    @Basic private String alias;
    @Basic private String email;

    // getters and setters as required
}

And finally the JPQL query:

String jqpl = "SELECT u FROM UserView u WHERE u.alias LIKE :query OR u.email LIKE :query OR u.identifier LIKE :query";

Note that you can pass query parameter directly in lower case as a Query parameter and you can order the result list after the query execution. Both will result in the RDBMS making less effort and consequently improving the overall response time.


问:
Access div using JQuery
Anobody suggest me how to access DIV in td

```<code><table border="0" cellpadding="0" cellspacing="0" width="95%">
    <tr>
        <td valign="top" style="width:25%">
            <img src="../NewsImages/82010437713162453512.bmp" id="rptAllNewsContent__ctl1_imgNews" width="120" height="120" />
        </td>
        <td valign="top" align="left" style="width:*;padding-left:7px;">
            dsdsdsd
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td align="left" style="width:20%;"><a id="rptAllNewsContent__ctl1_lnkbtnTotalComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl1$lnkbtnTotalComments','')" style="color:#80C355;">2 Comments</a></td>
                    <td align="left"><a id="rptAllNewsContent__ctl1_lnkbtnAddComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl1$lnkbtnAddComments','')" style="color:#80C355;">Add Comments</a></td>
                </tr>
            </table>
        </td>
    </tr>
    <tr><td colspan="2" style="height:13px;"></td></tr>
    <tr>
        <td>
            <div id="rptAllNewsContent__ctl1_divComment">
            sdfasdasda
            sdsa
            d
            asdas
            </div>
        </td>
    </tr>
    <tr>
        <td valign="top" style="width:25%">
            <img src="../NewsImages/8201010976151655912.jpg" id="rptAllNewsContent__ctl2_imgNews" width="120" height="120" />
        </td>
        <td valign="top" align="left" style="width:*;padding-left:7px;">
            dasdasd
        </td>
        </tr>
        <tr>
            <td colspan="2">
                <table border="0" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td align="left" style="width:20%;"><a id="rptAllNewsContent__ctl2_lnkbtnTotalComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl2$lnkbtnTotalComments','')" style="color:#80C355;">3 Comments</a></td>
                        <td align="left"><a id="rptAllNewsContent__ctl2_lnkbtnAddComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl2$lnkbtnAddComments','')" style="color:#80C355;">Add Comments</a></td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr><td colspan="2" style="height:13px;"></td></tr>
        <tr>
            <td>
                <div id="rptAllNewsContent__ctl2_divComment">
                sdfasdasda
                sdsa
                d
                asdas
                </div>
            </td>
        </tr>
    </table>
</code>```

I tried in this way but doesn't work.

```<code>$(document).ready(function(){
    $("a[id$='lnkbtnTotalComments']").click(function(){
        $(this).parent("td").parent("tr").next("tr").next("tr td").find("div").text();
        return false;
    });
    });
</code>```

答:
(completely different from my first solution)

Try this:
- get the id of the link clicked on
- replace "lnkbtnTotalComments" with "divComment" so we get the id of the matching div

```<code>$("a[id$='lnkbtnTotalComments']").click(function() {
    var id = $(this).attr("id").replace("lnkbtnTotalComments", "divComment");
    $("#" + id).html("gotcha");
    return false;
});
</code>```

Works for me. You can do anything you want instead of changing the html contents of course.

Title: Access div using JQuery

Body:
Anobody suggest me how to access DIV in td

            dsdsdsd

                    2 Comments
                    Add Comments

            sdfasdasda
            sdsa
            d
            asdas

            dasdasd

                        3 Comments
                        Add Comments

                sdfasdasda
                sdsa
                d
                asdas

I tried in this way but doesn't work.

$(document).ready(function(){
    $("a[id$='lnkbtnTotalComments']").click(function(){
        $(this).parent("td").parent("tr").next("tr").next("tr td").find("div").text();
        return false;
    });
    });

Body:
(completely different from my first solution)

Try this:
- get the id of the link clicked on
- replace "lnkbtnTotalComments" with "divComment" so we get the id of the matching div

$("a[id$='lnkbtnTotalComments']").click(function() {
    var id = $(this).attr("id").replace("lnkbtnTotalComments", "divComment");
    $("#" + id).html("gotcha");
    return false;
});

Works for me. You can do anything you want instead of changing the html contents of course.


问:
Swift - How to use user input in func with if-statement to decide output
I've been trying to write a function that takes user input and then returns the correct output in the textfield of my app, but can't get output.

What I have so far:

```<code>func outputResult (weeksNumber: Int, hoursNumber: Int) {

    let weeksNumber = Int(weeksNumber)
    let hoursNumber = Int(hoursNumber)

   let result1 = "test1"
    let result2 = "test2"
    let result3 = "test3"

    if hoursNumber < 74 {
        resultText.text = result1 // ResultText being my textfield.
    } else if weeksNumber < 8 {
        resultText.text = result2
    } else {
        resultText.text = result3
    }
}
</code>```

I've been trying to go through Apple's own material on functions and if-statements, but haven't been able to figure out how to do exactly what I want.

I've been trying out with:

```<code>func outputResult (weeksNumber: Int, hoursNumber: Int) - String {

    let weeksNumber = Int(weeksNumber)
    let hoursNumber = Int(hoursNumber)

    if hoursNumber < 74 {
        return resultText.text = "test1"
    }
</code>```

But this also doesn't solve my problem - merely giving me an error message.

My question is : How do I get my function to take user input and return output to my textfield?

Cheers,

答:
You are missing "->" to specify that it has a return. And you have to have return on if else condition. Plus for this example you don't need new variables "weekNumber" and "hoursNumber" in function.</p>

```<code>func outputResult (weeksNumber: Int, hoursNumber: Int) -> String {

        if hoursNumber < 74 {
            return resultText.text = "test1"
        }else{
            return "default"
        }
 }
</code>```

Body:
I've been trying to write a function that takes user input and then returns the correct output in the textfield of my app, but can't get output.

What I have so far:

func outputResult (weeksNumber: Int, hoursNumber: Int) {

    let weeksNumber = Int(weeksNumber)
    let hoursNumber = Int(hoursNumber)

   let result1 = "test1"
    let result2 = "test2"
    let result3 = "test3"

    if hoursNumber < 74 {
        resultText.text = result1 // ResultText being my textfield.
    } else if weeksNumber < 8 {
        resultText.text = result2
    } else {
        resultText.text = result3
    }
}

I've been trying to go through Apple's own material on functions and if-statements, but haven't been able to figure out how to do exactly what I want.

I've been trying out with:

func outputResult (weeksNumber: Int, hoursNumber: Int) - String {

    let weeksNumber = Int(weeksNumber)
    let hoursNumber = Int(hoursNumber)

    if hoursNumber < 74 {
        return resultText.text = "test1"
    }

But this also doesn't solve my problem - merely giving me an error message.

My question is : How do I get my function to take user input and return output to my textfield?

Cheers,

Body:
You are missing "->" to specify that it has a return. And you have to have return on if else condition. Plus for this example you don't need new variables "weekNumber" and "hoursNumber" in function.

func outputResult (weeksNumber: Int, hoursNumber: Int) -> String {

        if hoursNumber < 74 {
            return resultText.text = "test1"
        }else{
            return "default"
        }
 }


问:
How to deploy angular2 cli app on github?
I am front and engineer and have no experience with deploying.

I am developing my pet project using angular-cli.

How can I deploy it on github pages?

There is another simple way to do this?

答:
You should follow the angular-cli Wiki stories which can be found here.

The one you're looking for is Deploy to GitHub Pages.

A simple way to deploy your Angular app is to use GitHub Pages.

The first step is to create a GitHub account, and then create a
  repository for your project. Make a note of the user name and project
  name in GitHub.

Then all you need to do is run ng build --prod --output-path docs
  --base-href PROJECT_NAME, where PROJECT_NAME is the name of your project in GitHub. Make a copy of docs/index.html and name it
  docs/404.html.

Commit your changes and push. On the GitHub project page, configure it
  to publish from the docs folder.

And that's all you need to do! Now you can see your page at
  https://USER_NAME.github.io/PROJECT_NAME/.

You can also use angular-clip-ghpages, a full featured package that
  does this all this for you and has extra functionality.


问:
iOS Development: Is there ever a time when it's appropriate for an app to kill itself?
I've been developing iOS apps for enterprise use for several years now. It was an adjustment from having spent many (!) years developing desktop apps. One of the first things I learned very early on was that it is frowned upon for an app to kill itself. The posters in the Apple dev forum were downright hostile about it, which is a reason I never go there anymore.

Now I have an app that has very critical functions, and it requires that the user accept the terms and conditions before using the app, and that the app will not function if the terms have not been accepted. The choice is there to accept or to decline, but it seems like the best thing to do when the user actively declines is to kill the app entirely.

My question is, under those circumstances, would there be anything wrong with that? Will I be damned to developers hell for eternity?

答:
If you make the app kill itself, Apple won't let you post it on the App Store.

You should adjust your User Experience to the case of the user declining the terms and conditions.

For example, show a screen saying that the app can't be used unless terms are accepted, with a button saying "Take me back" that takes the user back to the terms screen.


问:
Update more than one document in a loop
Background:

I use PouchDB (indexedDB) for an offline NW.js App and I'm new to no-sql. I also use the PouchDB plugin Upsert, this basiclly does an db.get() and db.put() in the background.

Problem:

I dynamically create n documents and in another function i want to update them all with the upsert function in a loop, but i have to return the document that I want to update. So the loop stops at the first run(logically, just normal behavior).

Is there a way to update n documents with one function in a loop?

Here's my code example:

```<code>var temp = $('#number_discuss_points').val();

for (i = 1; i < temp; i++) {
    var v1= $('#discusspoint_heading' + i).val();
    var v2= $('#discusspoint_subheading' + i).val();
    var v3= $('#point_number' + i).val();
    var v4= $('#dpoint_deadline' + i).val();
    var v5= $('#responsible_person' + i).val();
    var v6= $('#dp_text' + i).val();

    db.upsert(id_body + i, function (sheet) {
        sheet._id = id_body + i;
        sheet.discusspoint_heading = v1;
        sheet.discusspoint_subheading = v2;
        sheet.point_number = v3;
        sheet.dpoint_deadline = v4;
        sheet.responsible_person = v5;
        sheet.dp_text = v6;

        return sheet; //Logically, the functions stops here and return everthing with 1

    }).then(function (result) {
        console.log(result);
    }).catch(function (err) {
        console.log(err);
    });
}
</code>```

答:
I think Nolan Lawson will be along shortly with a much better answer than me, but here goes anyway... in your loop you can add each returned promise from db.upsert into an array. After the loop, you can use Promise.all to process all the promises like this:

```<code>var temp = $('#number_discuss_points').val();

var promise_list = [];

for (i = 1; i < temp; i++) {
    var v1= $('#discusspoint_heading' + i).val();
    var v2= $('#discusspoint_subheading' + i).val();
    var v3= $('#point_number' + i).val();
    var v4= $('#dpoint_deadline' + i).val();
    var v5= $('#responsible_person' + i).val();
    var v6= $('#dp_text' + i).val();

    promise_list.push(db.upsert(id_body + i, function (sheet) {
        sheet._id = id_body + i;
        sheet.discusspoint_heading = v1;
        sheet.discusspoint_subheading = v2;
        sheet.point_number = v3;
        sheet.dpoint_deadline = v4;
        sheet.responsible_person = v5;
        sheet.dp_text = v6;

        return sheet; //Logically, the functions stops here and return everthing with 1
    }));
}

Promise.all(promise_list).then(function (result_list) {
    for(var result in result_list) {
        console.log(result);
    }
    }).catch(function (err) {
        console.log(err);
    });
</code>```

Nolan covers this very well in his post "We have a problem with promises".

Title: Update more than one document in a loop

Body:
Background:

I use PouchDB (indexedDB) for an offline NW.js App and I'm new to no-sql. I also use the PouchDB plugin Upsert, this basiclly does an db.get() and db.put() in the background.

Problem:

I dynamically create n documents and in another function i want to update them all with the upsert function in a loop, but i have to return the document that I want to update. So the loop stops at the first run(logically, just normal behavior).

Is there a way to update n documents with one function in a loop?

Here's my code example:

var temp = $('#number_discuss_points').val();

for (i = 1; i < temp; i++) {
    var v1= $('#discusspoint_heading' + i).val();
    var v2= $('#discusspoint_subheading' + i).val();
    var v3= $('#point_number' + i).val();
    var v4= $('#dpoint_deadline' + i).val();
    var v5= $('#responsible_person' + i).val();
    var v6= $('#dp_text' + i).val();

    db.upsert(id_body + i, function (sheet) {
        sheet._id = id_body + i;
        sheet.discusspoint_heading = v1;
        sheet.discusspoint_subheading = v2;
        sheet.point_number = v3;
        sheet.dpoint_deadline = v4;
        sheet.responsible_person = v5;
        sheet.dp_text = v6;

        return sheet; //Logically, the functions stops here and return everthing with 1

    }).then(function (result) {
        console.log(result);
    }).catch(function (err) {
        console.log(err);
    });
}

Body:
I think Nolan Lawson will be along shortly with a much better answer than me, but here goes anyway... in your loop you can add each returned promise from db.upsert into an array. After the loop, you can use Promise.all to process all the promises like this:

var temp = $('#number_discuss_points').val();

var promise_list = [];

for (i = 1; i < temp; i++) {
    var v1= $('#discusspoint_heading' + i).val();
    var v2= $('#discusspoint_subheading' + i).val();
    var v3= $('#point_number' + i).val();
    var v4= $('#dpoint_deadline' + i).val();
    var v5= $('#responsible_person' + i).val();
    var v6= $('#dp_text' + i).val();

    promise_list.push(db.upsert(id_body + i, function (sheet) {
        sheet._id = id_body + i;
        sheet.discusspoint_heading = v1;
        sheet.discusspoint_subheading = v2;
        sheet.point_number = v3;
        sheet.dpoint_deadline = v4;
        sheet.responsible_person = v5;
        sheet.dp_text = v6;

        return sheet; //Logically, the functions stops here and return everthing with 1
    }));
}

Promise.all(promise_list).then(function (result_list) {
    for(var result in result_list) {
        console.log(result);
    }
    }).catch(function (err) {
        console.log(err);
    });

Nolan covers this very well in his post "We have a problem with promises".


问:
Traversing a tree of objects in c#
I have a tree that consists of several objects, where each object has a name (string), id (int) and possibly an array of children that are of the same type. How do I go through the entire tree and print out all of the ids and names?

I'm new to programming and frankly, I'm having trouble wrapping my head around this because I don't know how many levels there are. Right now I'm using a foreach loop to fetch the parent objects directly below the root, but this means I cannot get the children.

答:
Well, you could always use recursion, but in a "real world" programming scenario, it can lead to bad things if you don't keep track of the depth.

Here's an example used for a binary tree: http://www.codeproject.com/KB/recipes/BinarySearchTree.aspx

I would google linked lists and other tree structures if you're new to the whole data structure thing. There's a wealth of knowledge to be had.

OwnerDisplayName: BeafTurkey

ContentLicense: CC BY-SA 4.0

Title: Traversing a tree of objects in c#

OwnerDisplayName: Alex Fort

LastEditorDisplayName: Rich B


问:
MobileFirst 7.1 Server Access Denied when using WL.Client.connect API
We got this error message when using WL.Client.connect API

The server error logs:

[ERROR   ] FWLSE0020E: Ajax request exception: Cannot find application environment, application=test, version=1.0, environment=iphone [project WLTestConnect]

[ERROR   ] FWLSE0117E: Error code: 1, error description: INTERNAL_ERROR, error message: FWLSE0069E: An internal error occurred during gadget request  [project WLTestConnect]Cannot find application environment, application=test, version=1.0, environment=iphone, User Identity {wl_antiXSRFRealm=null, wl_authenticityRealm=null, wl_directUpdateRealm=null, wl_remoteDisableRealm=null, SampleAppRealm=null, wl_deviceNoProvisioningRealm=null, SubscribeServlet=null, wl_anonymousUserRealm=null, wl_deviceAutoProvisioningRealm=null}. [project WLTestConnect]
                                                                                com.worklight.common.log.filters.ErrorFilter

[ERROR   ] FWLSE0335E: Authorization failed: ClientId f5ac9a8cda443cfca33d1e7f926a71f90f8c67a1 was not found on the server. [project WLTestConnect]

Here's the scenario:

Create Hello MobileFirst project in workspace A.

Deploy the project to local MobileFirst Server in workspace A.

Deploy Hello MobileFirst App to iphone and then use WL.Client.connect API. We got connect success callback.

Export this MobileFirst project which named WLTestConnect.

The iPhone device(iOS 10.2.1) still running.

Switching to the new Workspace B.

Import WLTestConnect project to Workspace B.

Deploy WLTestConnect project to local MobileFirst server.

Use WL.Client.connect in iPhone device and we got the access denied error.

MobileFirst version : 7.1.0.00-20151214-1857 & 7.1.0.00-20170608-1107

Is there a way to avoid access denied?

答:
This is a very valid error message and expected behaviour. When you move from one workspace in MobileFirst Studio to another, it creates a fresh copy of the MobileFirst server and the DB that holds the data for this server. </p>

<p>The app attempts to connect to the 'new' server and the error message essentially says that the server doesn't recognize this device because its DB doesn't have any history of this device connecting to it. </p>

Body:
This is a very valid error message and expected behaviour. When you move from one workspace in MobileFirst Studio to another, it creates a fresh copy of the MobileFirst server and the DB that holds the data for this server.

The app attempts to connect to the 'new' server and the error message essentially says that the server doesn't recognize this device because its DB doesn't have any history of this device connecting to it.


问:
How to read message form activemq in camel route
Im trying to read message from a queue using camel route and send it to a bean of message listener, but it ends with exception. am i doing some thing wrong.
I have serialized object in activemq

```<code> <bean class="com.herman.cxf.incident.ReportIncidentRequestConsumer"
            id="requestConsumer" />
        <camelContext id="camelContext-32616f27-d786-4ed8-9f75-2d208cd14b40"
            trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="report_amq">
                <from uri="activemq:queue:INCIDENT_REQUEST" />
                <to uri="bean:requestConsumer" />
            </route>
        </camelContext>
</code>```

Message Listner Class:

```<code>public class ReportIncidentRequestConsumer implements MessageListener {

        Logger _log = Logger.getLogger(ReportIncidentRequestConsumer.class);

        @Override
        public void onMessage(Message arg0) {
            _log.info("================== IM HERE IN REQUEST CONSUMER ===============");
        }

    }
</code>```

Excpetion:
Caused by: javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: Forbidden class org.apache.cxf.message.MessageContentsList! This class is not trusted to be serialized as ObjectMessage payload.

答:
Skipping different ways to handle ActiveMQ in camel, your exception was thrown due to "not trusted package". ActiveMQ uses list of trusted packages which objects it can serialize/deserialize (more details: http://activemq.apache.org/objectmessage.html).
To be able to send/receive your object you need as a ActiveMq client tell that you are trust them. Here are some examples: https://github.com/apache/activemq/blob/master/activemq-camel/src/test/resources/org/apache/activemq/camel/jms-object-message.xml</p>

Body:
Im trying to read message from a queue using camel route and send it to a bean of message listener, but it ends with exception. am i doing some thing wrong.
I have serialized object in activemq

 <bean class="com.herman.cxf.incident.ReportIncidentRequestConsumer"
            id="requestConsumer" />
        <camelContext id="camelContext-32616f27-d786-4ed8-9f75-2d208cd14b40"
            trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="report_amq">
                <from uri="activemq:queue:INCIDENT_REQUEST" />
                <to uri="bean:requestConsumer" />
            </route>
        </camelContext>

Message Listner Class:

public class ReportIncidentRequestConsumer implements MessageListener {

        Logger _log = Logger.getLogger(ReportIncidentRequestConsumer.class);

        @Override
        public void onMessage(Message arg0) {
            _log.info("================== IM HERE IN REQUEST CONSUMER ===============");
        }

    }

Excpetion:
Caused by: javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: Forbidden class org.apache.cxf.message.MessageContentsList! This class is not trusted to be serialized as ObjectMessage payload.


问:
Performance Difference Using Update Operation on a Mutable Map in Scala with a Large Size Data
I would like to know if an update operation on a mutable map is better in performance than reassignment.

Lets assume I have the following Map

```<code>val m=Map(1 -> Set("apple", "banana"),
          2 -> Set("banana", "cabbage"),
          3 -> Set("cabbage", "dumplings"))
</code>```

which I would like to reverse into this map:

```<code> Map("apple" -> Set(1),
     "banana" -> Set(1, 2),
     "cabbage" -> Set(2, 3),
     "dumplings" -> Set(3))
</code>```

The code to do so is:

```<code>def reverse(m:Map[Int,Set[String]])={
  var rm = Map[String,Set[Int]]()
  m.keySet foreach { k=>
       m(k) foreach { e =>
         rm = rm + (e -> (rm.getOrElse(e, Set()) + k))
       }
  }
  rm
}
</code>```

Would it be more efficient to use the update operator on a map if it is very large in size?

The code using the update on map is as follows:

```<code>def reverse(m:Map[Int,Set[String]])={
  var rm = scala.collection.mutable.Map[String,Set[Int]]()
  m.keySet foreach { k=>
      m(k) foreach { e =>
         rm.update(e,(rm.getOrElse(e, Set()) + k))
      }
  }
  rm
}
</code>```

答:
Just using @Aivean method in a functional way:  </p>

```<code>def transform(mp :Map[Int, Set[String]]) = {
   val accum = mp.values.flatten
                 .toSet.map( (_-> scala.collection.mutable.Set[Int]())).toMap
   mp.map {case(k,vals) => vals.map( v => accum(v)+=k)}
   accum.mapValues(_.toSet)
}
</code>```

Body:
I would like to know if an update operation on a mutable map is better in performance than reassignment.

Lets assume I have the following Map

val m=Map(1 -> Set("apple", "banana"),
          2 -> Set("banana", "cabbage"),
          3 -> Set("cabbage", "dumplings"))

which I would like to reverse into this map:

 Map("apple" -> Set(1),
     "banana" -> Set(1, 2),
     "cabbage" -> Set(2, 3),
     "dumplings" -> Set(3))

The code to do so is:

def reverse(m:Map[Int,Set[String]])={
  var rm = Map[String,Set[Int]]()
  m.keySet foreach { k=>
       m(k) foreach { e =>
         rm = rm + (e -> (rm.getOrElse(e, Set()) + k))
       }
  }
  rm
}

Would it be more efficient to use the update operator on a map if it is very large in size?

The code using the update on map is as follows:

def reverse(m:Map[Int,Set[String]])={
  var rm = scala.collection.mutable.Map[String,Set[Int]]()
  m.keySet foreach { k=>
      m(k) foreach { e =>
         rm.update(e,(rm.getOrElse(e, Set()) + k))
      }
  }
  rm
}

Body:
Just using @Aivean method in a functional way:

def transform(mp :Map[Int, Set[String]]) = {
   val accum = mp.values.flatten
                 .toSet.map( (_-> scala.collection.mutable.Set[Int]())).toMap
   mp.map {case(k,vals) => vals.map( v => accum(v)+=k)}
   accum.mapValues(_.toSet)
}


问:
Selected value for DropDownList not showing
I'm trying to set a selected value for my dropdownlist but I can't make it show on page.

This is how I set the selected value;

```<code>productHier = new SelectList(hierarchyList, "ProductHierarchyID", "ProductHierarchyCode", orderline.PrmProductVariant.PrmProduct.PrmProductHierarchy1 );
ViewBag.productHier = productHier;
</code>```

and this is the part in my View

```<code>@Html.DropDownList("Hierarchy", (IEnumerable<SelectListItem>)ViewBag.productHier, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })
</code>```

I tried many suggestions from other question on this subject but none helped me. I wonder what I'm missing.

EDIT: When I debug, I can see the values designated as selected value in controller and view but somehow I can't see them on page.

答:
I think with the way you are doing it, you need to do it like this:

```<code>@Html.DropDownList("productHier", null, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })
</code>```

Beware, that this style of creating drop down lists does not work with validation.

You will have to use DropDownListFor in order to get proper validation.

Hope this helps!

Body:
I'm trying to set a selected value for my dropdownlist but I can't make it show on page.

This is how I set the selected value;

productHier = new SelectList(hierarchyList, "ProductHierarchyID", "ProductHierarchyCode", orderline.PrmProductVariant.PrmProduct.PrmProductHierarchy1 );
ViewBag.productHier = productHier;

and this is the part in my View

@Html.DropDownList("Hierarchy", (IEnumerable<SelectListItem>)ViewBag.productHier, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })

I tried many suggestions from other question on this subject but none helped me. I wonder what I'm missing.

EDIT: When I debug, I can see the values designated as selected value in controller and view but somehow I can't see them on page.

Body:
I think with the way you are doing it, you need to do it like this:

@Html.DropDownList("productHier", null, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })

Beware, that this style of creating drop down lists does not work with validation.

You will have to use DropDownListFor in order to get proper validation.

Hope this helps!


问:
CodeIgniter - Create dynamic html table using form helper functions?
I've a dynamic table which adds more rows. Here is my table.

```<code><table>
  <thead>
    <tr class="success">
     <th>Bank/Lender</th>
     <th>Add More</th>
    </tr>
  </thead>
  <tbody >
   <tr>
    <td>
     <?php
       $data = array(
              'name' => 'debt_info_bank_name[]',
              'id' => '',
              'class' => 'form-control',
              'placeholder' => 'Bank/Lender Name'
              );
       echo form_input($data);
      ?>
    </td>
    <td>
     <input class="add btn btn-success btn-sm" type="button" value="Add More"  />
    </td>
  </tr>
</tbody>
</code>```

And Here is my javascript part:

```<code>    $(document).on('click','.add',function(){
    $(this).val('Delete');
    $(this).attr('class','del btn btn-danger btn-sm');
    var appendTxt = '<tr><td><?php  $data = array(
                                    'name' => 'debt_info_bank_name[]',
                                    'id' => '',
                                    'class' => 'form-control',
                                    'placeholder' => 'Bank / Lender Name'
                                  );
                                  echo json_encode(form_input($data)); ?></td><td><input class="add btn btn-success btn-sm" type="button" value="Add More"  /></td></tr>';
    $("#dyn_table > tbody > tr:last").after(appendTxt);
    });

    $(document).on('click','.del',function(){
        $(this).parent().parent().remove();

    });
</code>```

It adds rows but with quotes"" in each td element. How can i correct it?

Note: If i add fields in javascript code using html elements like

```<code> var appendTxt = '<tr><td><input type="text" placeholder="Bank/Lender Name"  /></td> <td><input class="add btn btn-success btn-sm" type="button" value="Add More" /></td></tr>';
</code>```

then it goes fine but i want to add fields in codeigniter style because it is more safe to do that.

答:
remove json_encode from here. just echo</p>

```<code> echo form_input($data); ?></td><td><input class="add btn btn-success btn-sm" type="button" value="Add More"  /></td></tr>';
</code>```

Body:
I've a dynamic table which adds more rows. Here is my table.

     Bank/Lender
     Add More

     <?php
       $data = array(
              'name' => 'debt_info_bank_name[]',
              'id' => '',
              'class' => 'form-control',
              'placeholder' => 'Bank/Lender Name'
              );
       echo form_input($data);
      ?>

     <input class="add btn btn-success btn-sm" type="button" value="Add More"  />

And Here is my javascript part:

    $(document).on('click','.add',function(){
    $(this).val('Delete');
    $(this).attr('class','del btn btn-danger btn-sm');
    var appendTxt = '
<?php  $data = array(
                                    'name' => 'debt_info_bank_name[]',
                                    'id' => '',
                                    'class' => 'form-control',
                                    'placeholder' => 'Bank / Lender Name'
                                  );
                                  echo json_encode(form_input($data)); ?>	<input class="add btn btn-success btn-sm" type="button" value="Add More"  />
';
    $("#dyn_table > tbody > tr:last").after(appendTxt);
    });

    $(document).on('click','.del',function(){
        $(this).parent().parent().remove();

    });

It adds rows but with quotes"" in each td element. How can i correct it?

Note: If i add fields in javascript code using html elements like

 var appendTxt = '
<input type="text" placeholder="Bank/Lender Name"  />	 <input class="add btn btn-success btn-sm" type="button" value="Add More" />
';

then it goes fine but i want to add fields in codeigniter style because it is more safe to do that.

Body:
remove json_encode from here. just echo

 echo form_input($data); ?></td><td><input class="add btn btn-success btn-sm" type="button" value="Add More"  /></td></tr>';


问:
How should I customize my Facebook page?
Okey, so I have a business Facebook Page like many others. And I want to customize it like many others have. But Facebook (henceforth FB) documentation is really bad.

So I go and edit my page and there I find Facebook Static FBML application. So far, great, and I can even use standard HTML to edit it. And then there is also FBML which I can use to make more advanced customization, like show something for people who "Like" and something else for others. Pretty straightforward. But then i notice that Facebook is deprecating FBML and recommend me to use JavaScript SDK and Social Plugins.

So what does this mean for me? Can I customize my site this way or not?

The documentation for JavaScript SDK and Social Plugins is worthless and very general, how do these apply for my Page customization?

But Facebook Static FBML application it self is an application i guess. Will it work in the future?

What is the best way to customize my FB Page and add tabs and so on?
What should I do?

答:
ANSWER (for lazy people):

While Facebook Static FBML application might be working in the near future, it seems like building applications yourself is the right way to go.

Build an application: http://www.facebook.com/developers/createapp.php

Also you do not need the FBML since you can do all that is needed with the graph-api.

Graph-API doc: http://developers.facebook.com/docs/api

Also, by using the iframe canvas when building apps this allows you to host your page tabs where ever you want allowing you do use any coding language you want.


问:
Efficient way of finding the number of decimals a double value has
I want to find an effiecient way of making sure that the number of decimal places in
double is not more than three.

```<code>double num1 = 10.012; //True
double num2 = 10.2211; //False
double num2 = 10.2; //True
</code>```

Currently, what I do is just use a regex split and count index of . like below.

```<code>String[] split = new Double(num).toString().split("\\.")
split[0].length() //num of decimal places
</code>```

Is there an efficient or better way to do this since I'll be calling this
function a lot?

答:
If you want a solution that will tell you that information in a way that will agree with the eventual result of converting the double to a string, then efficiency doesn't really come into it; you basically have to convert to string and check. The result is that it's entirely possible for a double to contain a value that mathematically has a (say) non-zero value in (say) the hundred-thousandth place, but which when converted to string will not. Such is the joy of IEEE-754 double-precision binary floating point: The number of digits you get from the string representation is only as many as necessary to distinguish the value from its adjacent representable value. From the Double docs:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

But if you're not concerned about that, and assuming limiting your value range to long is okay, you can do something like this:

```<code>private static boolean onlyThreePlaces(double v) {
    double d = (double)((long)(v * 1000)) / 1000;
    return d == v;
}
</code>```

...which should have less memory overhead than a String-round-trip.

However, I'd be surprised if there weren't a fair number of times when that method and the result of Double.toString(double) didn't match in terms of digits after the decimal, for the reasons given above.

In a comment on the question, you've said (when I asked about the value range):

Honestly I'm not sure. I'm dealing with prices; For starters, I'll assume 0-200K

Using double for financial values is usually not a good idea. If you don't want to use BigDecimal because of memory concerns, pick your precision and use int or long depending on your value range. For instance, if you only need to-the-penny precision, you'd use values multiplied by 100 (e.g., 2000 is Ⓠ20 [or whatever currency you're using, I'm using Ⓠ for quatloos]). If you need precision to thousanths of a penny (as your question suggests), then multiply by 100000 (e.g., 2000000 is Ⓠ20). If you need more precision, pick a larger multiplier. Even if you go to hundred-thousanths of a penny (muliplier: 10000000), with long you have a range of Ⓠ-922,337,203,685 to Ⓠ922,337,203,685.

This has the side-benefit that it makes this check easier: Just a straight %. If your multiplier is 10000000 (hundred-thousandths of a penny), it's just value % 10000 != 0 to identify invalid ones (or value % 10000 == 0 to identify valid ones).

```<code>long num1 = 100120000;  // 10.012   => true
                        // 100120000 % 10000 is 0 = valid
long num2 = 102211000;  // 10.2211  => false
                        // 102211000 % 10000 is 1000 = invalid
long num3 = 102000000;  // 10.2     => true
                        // 102000000 % 10000 is 0 = valid
</code>```

Body:
I want to find an effiecient way of making sure that the number of decimal places in
double is not more than three.

double num1 = 10.012; //True
double num2 = 10.2211; //False
double num2 = 10.2; //True

Currently, what I do is just use a regex split and count index of . like below.

String[] split = new Double(num).toString().split("\\.")
split[0].length() //num of decimal places

Is there an efficient or better way to do this since I'll be calling this
function a lot?

Body:
If you want a solution that will tell you that information in a way that will agree with the eventual result of converting the double to a string, then efficiency doesn't really come into it; you basically have to convert to string and check. The result is that it's entirely possible for a double to contain a value that mathematically has a (say) non-zero value in (say) the hundred-thousandth place, but which when converted to string will not. Such is the joy of IEEE-754 double-precision binary floating point: The number of digits you get from the string representation is only as many as necessary to distinguish the value from its adjacent representable value. From the Double docs:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

But if you're not concerned about that, and assuming limiting your value range to long is okay, you can do something like this:

private static boolean onlyThreePlaces(double v) {
    double d = (double)((long)(v * 1000)) / 1000;
    return d == v;
}

...which should have less memory overhead than a String-round-trip.

However, I'd be surprised if there weren't a fair number of times when that method and the result of Double.toString(double) didn't match in terms of digits after the decimal, for the reasons given above.

In a comment on the question, you've said (when I asked about the value range):

Honestly I'm not sure. I'm dealing with prices; For starters, I'll assume 0-200K

Using double for financial values is usually not a good idea. If you don't want to use BigDecimal because of memory concerns, pick your precision and use int or long depending on your value range. For instance, if you only need to-the-penny precision, you'd use values multiplied by 100 (e.g., 2000 is Ⓠ20 [or whatever currency you're using, I'm using Ⓠ for quatloos]). If you need precision to thousanths of a penny (as your question suggests), then multiply by 100000 (e.g., 2000000 is Ⓠ20). If you need more precision, pick a larger multiplier. Even if you go to hundred-thousanths of a penny (muliplier: 10000000), with long you have a range of Ⓠ-922,337,203,685 to Ⓠ922,337,203,685.

This has the side-benefit that it makes this check easier: Just a straight %. If your multiplier is 10000000 (hundred-thousandths of a penny), it's just value % 10000 != 0 to identify invalid ones (or value % 10000 == 0 to identify valid ones).

long num1 = 100120000;  // 10.012   => true
                        // 100120000 % 10000 is 0 = valid
long num2 = 102211000;  // 10.2211  => false
                        // 102211000 % 10000 is 1000 = invalid
long num3 = 102000000;  // 10.2     => true
                        // 102000000 % 10000 is 0 = valid


问:
Overloading function templates and inherited arguments
This code:

```<code>#include <iostream>

class A {};

class B : public A {};

class C {
public:
    template <typename T>
    void x(const T& t) {
        std::cout << "template" << std::endl;
    }

    void x(const A*& a) {
        std::cout << "a" << std::endl;
    }

    void x(const int& a) {
        std::cout << "int" << std::endl;
    }

    template <typename T>
    void y(T t) {
        std::cout << "template" << std::endl;
    }

    void y(A* a) {
        std::cout << "a" << std::endl;
    }

    void y(int a) {
        std::cout << "int" << std::endl;
    }

    template <typename T>
    void z(const T& t) {
        std::cout << "template" << std::endl;
    }
};

// Does not compile
// template <>
// void C::z(const A*& a) {
//  std::cout << "a" << std::endl;
// }

template <>
void C::z(const int& a) {
    std::cout << "int" << std::endl;
}

int main(int argc, char** argv) {
    C c;
    c.x(new A());
    c.x(new B());
    c.x(1);
    c.y(new A());
    c.y(new B());
    c.y(1);
    c.z(new A());
    c.z(new B());
    c.z(1);
}
</code>```

Prints:

```<code>template
template
int
a
template
int
template
template
int
</code>```

I have the following questions about that:

Why does void C::z(const int& a) compile but void C::z(const A*& a) does not?

What is a reasonable solution to problem? I need to have a templated function for generically handling a wide variety of arguments, but a large set of classes with a common base needs to be handled specifically. I need some approach that will print a a int.

Edit: Thanks to the suggestion of @AndyG I was able to resolve this with some type_traits and the code below:

```<code>#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/remove_pointer.hpp>

#include <iostream>

class A {};

class B : public A {};

class C {
public:
    template <typename T>
    typename boost::disable_if<boost::is_base_of<A, typename boost::remove_pointer<T>::type>, void>::type x(const T& t) {
        std::cout << "template" << std::endl;
    }

    void x(A*const& a) {
        std::cout << "a" << std::endl;
    }

    void x(const int& a) {
        std::cout << "int" << std::endl;
    }
};

int main(int argc, char** argv) {
    C c;
    c.x(new A());
    c.x(new B());
    c.x(1);
}
</code>```

答:
The answer is because a const on a pointer type is a little weird.

What you want is this:

```<code>template <>
void C::z( A*const&  a) {
  std::cout << "a" << std::endl;
}
</code>```

const needs to be read right to left. Since z accepts a T&, when you want to specialize for A* you need to place the const after A* instead of in front.

Demo

Body:
This code:

#include <iostream>

class A {};

class B : public A {};

class C {
public:
    template <typename T>
    void x(const T& t) {
        std::cout << "template" << std::endl;
    }

    void x(const A*& a) {
        std::cout << "a" << std::endl;
    }

    void x(const int& a) {
        std::cout << "int" << std::endl;
    }

    template <typename T>
    void y(T t) {
        std::cout << "template" << std::endl;
    }

    void y(A* a) {
        std::cout << "a" << std::endl;
    }

    void y(int a) {
        std::cout << "int" << std::endl;
    }

    template <typename T>
    void z(const T& t) {
        std::cout << "template" << std::endl;
    }
};

// Does not compile
// template <>
// void C::z(const A*& a) {
//  std::cout << "a" << std::endl;
// }

template <>
void C::z(const int& a) {
    std::cout << "int" << std::endl;
}

int main(int argc, char** argv) {
    C c;
    c.x(new A());
    c.x(new B());
    c.x(1);
    c.y(new A());
    c.y(new B());
    c.y(1);
    c.z(new A());
    c.z(new B());
    c.z(1);
}

Prints:

template
template
int
a
template
int
template
template
int

I have the following questions about that:

Why does void C::z(const int& a) compile but void C::z(const A*& a) does not?

What is a reasonable solution to problem? I need to have a templated function for generically handling a wide variety of arguments, but a large set of classes with a common base needs to be handled specifically. I need some approach that will print a a int.

Edit: Thanks to the suggestion of @AndyG I was able to resolve this with some type_traits and the code below:

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/remove_pointer.hpp>

#include <iostream>

class A {};

class B : public A {};

class C {
public:
    template <typename T>
    typename boost::disable_if<boost::is_base_of<A, typename boost::remove_pointer<T>::type>, void>::type x(const T& t) {
        std::cout << "template" << std::endl;
    }

    void x(A*const& a) {
        std::cout << "a" << std::endl;
    }

    void x(const int& a) {
        std::cout << "int" << std::endl;
    }
};

int main(int argc, char** argv) {
    C c;
    c.x(new A());
    c.x(new B());
    c.x(1);
}

Body:
The answer is because a const on a pointer type is a little weird.

What you want is this:

template <>
void C::z( A*const&  a) {
  std::cout << "a" << std::endl;
}

const needs to be read right to left. Since z accepts a T&, when you want to specialize for A* you need to place the const after A* instead of in front.

Demo


问:
How to program a convoluted Indicator calculations, that requires the previous period value in its calculation?
If we take the Accumulation/Distribution indicator for example.

Investopedia lists the steps as:

Money Flow Multiplier = [(close  -  low) - (high - close)] /(high - low)

Money Flow Volume = Money Flow Multiplier x volume for the period

Accumulation/Distribution= previous Accumulation/Distribution + current period's Money Flow

The third step is what confuses me, how can I calculate A/D when I don't have the previous A/D, which requires the previous A/D and so on...

There are other indicators that are similar where the indicator requires the indicator itself to be calculated. So how is it done?

答:
There is a common software approach to this:

Your case has a trivial convolution, with a depth of just 1. There are some deeper convolution indicators, going in this very same principle just a bit deeper.

Solution:

find a so called "neutral" value, that the calculus is dependent on and inject it in the "missing" time-steps.

for a PriceDOMAIN Indicator, like a moving average, this can be a Close price of the first available bars, that gets replicated "period"-times back

for multiplicative and exponentiating Indicator, that can be 1

for additive Indicator, that can be 0

All the toys get aligned to fair values within the next "period" time-steps if the neutral values were algebraically correct, or in a little bit longer time, when substituted values were "just approximations". Both the former and the latter case, is typically well back in time to skew the future indicator values and to somehow bother the actual flow of current decisions, based on the recent indicator outputs.


问:
Optimize MySQL Query ti may it faster
I am fairly new to MySQL and would like to ask how can you fine tune this query or rewrite it in a better way.

```<code> SELECT *
 FROM emp
 WHERE birth_date BETWEEN '1999-05-01'
 AND '1999-05-31'
 OR last_name in ('Bart', 'Martha', 'Lisa');
</code>```

Your assistance is greatly appreciated. Can you also explain why you did it so I would know

Thanks.

答: You can also use the EXPLAIN command to get more insight about your query and how you can optimize it.</p>

Title: Optimize MySQL Query ti may it faster

Body:
I am fairly new to MySQL and would like to ask how can you fine tune this query or rewrite it in a better way.

 SELECT *
 FROM emp
 WHERE birth_date BETWEEN '1999-05-01'
 AND '1999-05-31'
 OR last_name in ('Bart', 'Martha', 'Lisa');

Your assistance is greatly appreciated. Can you also explain why you did it so I would know

Thanks.


问:
Parent div, with two children, on of them with exact height, how to give the other child "free left" space as height
As title says, I have one parent div, and two children divs(div1 and div2) and lets assume parent div is always 100% of it's own parent. I give to div1 height of 200px for example, what to do to make div2 take other left space as its height, 100% height of parent minus 200px of a sibling.</p>

答:
Using only css

You can calculate the height in css for div2

```<code>div2{
height :calc(100℅ - 200px);
}
</code>```

You can read more about calc() at mozilla documentation

JavaScript way

You can check the jsfiddle here

Explanation
calculate the height of div and div1, and assign the subtracted height to div2

```<code>var h = document.querySelector("#one").offsetHeight
var h2 = document.querySelector("#two").offsetHeight
document.querySelector("#three").style.height = (h - h2)+"px";
</code>```

Body:
Using only css

You can calculate the height in css for div2

div2{
height :calc(100℅ - 200px);
}

You can read more about calc() at mozilla documentation

JavaScript way

You can check the jsfiddle here

Explanation
calculate the height of div and div1, and assign the subtracted height to div2

var h = document.querySelector("#one").offsetHeight
var h2 = document.querySelector("#two").offsetHeight
document.querySelector("#three").style.height = (h - h2)+"px";


问:
Excel as a data source in SSRS Query a Specific Column of a Sheet
I want to query the data from an excel file utilizing ODBC System DSN for Excel 12.0.

What will be the right syntax to query specific columns from a worksheet and not the whole worksheet like this example:

SELECT 'Sheet1$'.* FROM 'Sheet1$'**

I need to be able to not query all of them and also not let import blank rows.

答:
Your best bet would be to use OPENROWSET. If you Excel file has column headers then you can do something like

```<code>Select MyFirstColumn, MySecondColumn, MyThridColumn, MyLastColumn FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=\\myServer\MyPath\MyFile.xlsx;HDR=YES', 'SELECT * FROM [myWorkSheet$]')
</code>```

If you have no row headers then set HDR=NO and use columns names F1, F2....F99 etc.

You can add a where clause to filter out blank lines just as you would with a regular table.

Note you will need to allow ad-hoc queries and and make sure the provider is installed on the esrver. There are plenty of articles on how to do this, it's pretty simple.

Also remember that the path must be visible to the server, not just your local workstation.

Body:
Your best bet would be to use OPENROWSET. If you Excel file has column headers then you can do something like

Select MyFirstColumn, MySecondColumn, MyThridColumn, MyLastColumn FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=\\myServer\MyPath\MyFile.xlsx;HDR=YES', 'SELECT * FROM [myWorkSheet$]')

If you have no row headers then set HDR=NO and use columns names F1, F2....F99 etc.

You can add a where clause to filter out blank lines just as you would with a regular table.

Note you will need to allow ad-hoc queries and and make sure the provider is installed on the esrver. There are plenty of articles on how to do this, it's pretty simple.

Also remember that the path must be visible to the server, not just your local workstation.


问:
Test if an assertion is thrown
How do I test if an assertion is thrown by the method under test using junit? Heres the method I'm testing:

```<code>public int f(int i){
    assert i > 0;
    return i;
}
</code>```

I'm using junit 4.12.

答:
You can test it by providing parameter in @Test annotation:

```<code>@Test(expected = AssertionError.class)
public void shouldThrowExceptionWhenIncorrectInput() {
    f(-3);
}
</code>```

This will check if the AssertException is thrown.
However, if you want to ensure that this function wont be run with incorrect parameters, you have to be aware that assertions can be turned off by running java with -da parameters.

To ensure that exception is thrown I would suggest throwing IllegalArgumentException inside some validation method, and to provide it with proper message. Then you will be sure that this will always throw exception when incorrect parameters are provided.

Title: Test if an assertion is thrown

Body:
How do I test if an assertion is thrown by the method under test using junit? Heres the method I'm testing:

public int f(int i){
    assert i > 0;
    return i;
}

I'm using junit 4.12.

Body:
You can test it by providing parameter in @Test annotation:

@Test(expected = AssertionError.class)
public void shouldThrowExceptionWhenIncorrectInput() {
    f(-3);
}

This will check if the AssertException is thrown.
However, if you want to ensure that this function wont be run with incorrect parameters, you have to be aware that assertions can be turned off by running java with -da parameters.

To ensure that exception is thrown I would suggest throwing IllegalArgumentException inside some validation method, and to provide it with proper message. Then you will be sure that this will always throw exception when incorrect parameters are provided.


问:
C++ Printing Odd numbers instead of Prime Numbers
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

```<code>int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}
</code>```

答:
```<code>int main() {

    for (int i = 2; i <= 100; i++) {
        for (int j = 2; j < i; j++) {
            if (i%j == 0)
                break;

            if (j==i-1) // means has never run previous if blog
                cout << i << endl;
        }
    }

    return 0;
}
</code>```

Body:
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}


答:
Your print statement is within the inner loop, and it should not be - it's only a prime if you run all the way through the inner loop without finding a divisor.

As a second point, you only need to check for divisors up to the square root of i, not all the way up to i.

Title: C++ Printing Odd numbers instead of Prime Numbers


问:
Running an Ignite Cluster
I have a 12 node Apache Ignite cluser. My application code runs along with Ignite and are both loaded into the same JVM. I am using SprinBoot 1.4.1. I was wondering if there would be some advice on whether I can consider to use peerClassLoading to allow to support the following rough deployment plan:

Node 1 : Will run as a master/primary node (springboot+other java code + ignite jar(s))

Nodes 2-11 : Will run as headless ignite nodes (no springboot/other java app code)

Currently I am using the default setting of false for peerClassLoading.

Please let me know your thoughts.

TIA

答:
With peer-class-loading enabled, you don't have to manually deploy your Java code on each node in the grid and re-deploy it each time it changes.

So, if you want to deploy your code only to one node, you should use peerClassLoading.

Here is doc about it.

Title: Running an Ignite Cluster


问:
"System.OutOfMemoryException" while using ado.net to retrieve 700k records C#
I fill the data from the table into the list for the first time and then i clear the list to select different data from different table so i want the first list to be released from the memory because i will get new data more and more.

I have tried:

```<code>List.Dispose();
List.Clear();
List = null;
GC.Collect();
</code>```

But the memory keeps full.

in the Entity Framework i figured it out and added the .AsNoTracking() and it worked and the memory is cleared

But I have to use ADO.Net.

答:
You can't tell GC what to do. GC releases what GC wants to release. It is usually very good at releasing things when you're under memory pressure; if it can't release, then I suspect that the objects may still be reachable. In particular, events are a very common way that people accidentally keep lots of objects reachable - so you might want to check that you don't have any dangling events.

There are ways to try to influence GC, but it is almost always a mistake to do that, and I'm not going to include the voodoo commands here because I think that is not the fix.

ADO.NET is not to blame here; EF runs on top of ADO.NET. Note that what you can do is avoid lists; you can read over data as a sequence without ever needing it go into a list, but just by working over the reader. Or if you use tools like "dapper" (a very thin helper on top of ADO.NET), you can just use .Query<T>(...., buffered: false) (it buffers by default, because usually people aren't reading 700,000 rows).

On the topic of lists: note that large lists hit the "large object heap", which impacts collection more.

Body:
I fill the data from the table into the list for the first time and then i clear the list to select different data from different table so i want the first list to be released from the memory because i will get new data more and more.

I have tried:

List.Dispose();
List.Clear();
List = null;
GC.Collect();

But the memory keeps full.

in the Entity Framework i figured it out and added the .AsNoTracking() and it worked and the memory is cleared

But I have to use ADO.Net.


问:
how to solve the error when convert string date to integer?
I would like to convert my string date to int but I get an error, example of my date 'dim. janv. 23 24:00:00 +0000 2011`
This is part of my code :

```<code>   String created_at =  (String) jsonObject.get("created_at");
   System.out.println("la date de création de tweet est: " + created_at);
   DateFormat df = new SimpleDateFormat(" ddd. MMMM. EE HH:mm:ss z yyyy");
   String s= df.format(created_at);
   int out=Integer.valueOf(s);
   System.out.println("new date " +out);
</code>```

And the output is:

java.lang.IllegalArgumentException: Cannot format given Object as a Date.

答:
I am aware that there is an accepted answer already. I am posting this to inspire you and anyone else to drop the outdated classes DateFormat and SimpleDateFormat. These days we have so much better in the modern DateTimeFormatter and friends, these classes tend to be much more programmer friendly. So use these if you can — which you can.

```<code>    System.out.println("la date de création de tweet est: " + created_at);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                        Locale.FRENCH);
    OffsetDateTime dateTime = OffsetDateTime.parse(created_at, dtf);
</code>```

This prints:

```<code>la date de création de tweet est: dim. janv. 23 24:00:00 +0000 2011
2011-01-24T00:00Z
</code>```

In French the dots are part of the abbreviations for day of week and month, so they should not be explicit in the format pattern string. Also be aware that you don’t have a leading space in there (unless your date-time string has one too). The result is correct since midnight at 24 hours on 23th of January is the same as 0 hours in the 24th.

The other string from the comment, "Tue Feb 08 12:30:27 +0000 2011", is in the same format, only in English. So you need not change the format pattern, only the locale:

```<code>    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                        Locale.ENGLISH);
</code>```

Now the result is:

```<code>la date de création de tweet est: Tue Feb 08 12:30:27 +0000 2011
2011-02-08T12:30:27Z
</code>```

I didn’t understand the part about converting to integer. I noticed you tried Integer.valueOf(s) in the code in the question, which will only work if you format the date-time into a string of digits first. For example:

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMdd");
    String s = dateTime.format(formatter);
    int out = Integer.parseInt(s);
    System.out.println("new date " + out);
</code>```

This prints

```<code>new date 20110124
</code>```

But I probably guessed incorrectly at what you are aiming at. I shall be happy to edit if you explain your requirement better. I used parseInt() en lieu of valueOf(), the result is the same, I just avoid the automatic conversion from Integer to int.

Edit: What if the date of creation of tweet is for example "dim. janv. 23 24:00:10 +0000 2011"? That is, 10 seconds past midnight. Then we get Invalid value for HourOfDay (valid values 0 - 23): 24.

While Java apparently accepts 24:00:00 as a time, it thinks that times after midnight should written as for example 0:00:10 on the following day. However, we can easily relax that requirement:

```<code>    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                        Locale.FRENCH)
            .withResolverStyle(ResolverStyle.LENIENT);
</code>```

Date time formatters come with three resolver styles, strict, smart (the default) and lenient. Using the last one we get

```<code>2011-01-24T00:00:10Z
</code>```

Again, as expected, 24:00:10 on 23th of January equals 0:00:10 on the 24th.

Body:
I would like to convert my string date to int but I get an error, example of my date 'dim. janv. 23 24:00:00 +0000 2011`
This is part of my code :

   String created_at =  (String) jsonObject.get("created_at");
   System.out.println("la date de création de tweet est: " + created_at);
   DateFormat df = new SimpleDateFormat(" ddd. MMMM. EE HH:mm:ss z yyyy");
   String s= df.format(created_at);
   int out=Integer.valueOf(s);
   System.out.println("new date " +out);

And the output is:

java.lang.IllegalArgumentException: Cannot format given Object as a Date.

Body:
I am aware that there is an accepted answer already. I am posting this to inspire you and anyone else to drop the outdated classes DateFormat and SimpleDateFormat. These days we have so much better in the modern DateTimeFormatter and friends, these classes tend to be much more programmer friendly. So use these if you can — which you can.

    System.out.println("la date de création de tweet est: " + created_at);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                        Locale.FRENCH);
    OffsetDateTime dateTime = OffsetDateTime.parse(created_at, dtf);

This prints:

la date de création de tweet est: dim. janv. 23 24:00:00 +0000 2011
2011-01-24T00:00Z

In French the dots are part of the abbreviations for day of week and month, so they should not be explicit in the format pattern string. Also be aware that you don’t have a leading space in there (unless your date-time string has one too). The result is correct since midnight at 24 hours on 23th of January is the same as 0 hours in the 24th.

The other string from the comment, "Tue Feb 08 12:30:27 +0000 2011", is in the same format, only in English. So you need not change the format pattern, only the locale:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                        Locale.ENGLISH);

Now the result is:

la date de création de tweet est: Tue Feb 08 12:30:27 +0000 2011
2011-02-08T12:30:27Z

I didn’t understand the part about converting to integer. I noticed you tried Integer.valueOf(s) in the code in the question, which will only work if you format the date-time into a string of digits first. For example:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMdd");
    String s = dateTime.format(formatter);
    int out = Integer.parseInt(s);
    System.out.println("new date " + out);

This prints

new date 20110124

But I probably guessed incorrectly at what you are aiming at. I shall be happy to edit if you explain your requirement better. I used parseInt() en lieu of valueOf(), the result is the same, I just avoid the automatic conversion from Integer to int.

Edit: What if the date of creation of tweet is for example "dim. janv. 23 24:00:10 +0000 2011"? That is, 10 seconds past midnight. Then we get Invalid value for HourOfDay (valid values 0 - 23): 24.

While Java apparently accepts 24:00:00 as a time, it thinks that times after midnight should written as for example 0:00:10 on the following day. However, we can easily relax that requirement:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                        Locale.FRENCH)
            .withResolverStyle(ResolverStyle.LENIENT);

Date time formatters come with three resolver styles, strict, smart (the default) and lenient. Using the last one we get

2011-01-24T00:00:10Z

Again, as expected, 24:00:10 on 23th of January equals 0:00:10 on the 24th.


问:
vuejs v-bind:class on a v-for not updating
have this code

```<code><span v-for="tag in ref.tags" @mouseenter="tag.pop=true;tag.adjust($event)" @mouseleave="tag.pop=false" >
    <span  :class="tag.pop? 'ref-tag-pop' : 'tag'">@{{tag.name}}</span>
    <div v-show="tag.pop">@{{tag.info}}</div>
</span>
</code>```

It's basically a popup on hover.
It works fine, but when I add a new "tag", although I see the new tag added to screen, the hover isn't working for it.

When I look in the vue devtools I can see that for the original tags the true and false change dynamically while the new tag doesn't. Although, if I remove the mouseleave event and refresh the devtools I can see the tag.pop does change to true.
If I then hover over one of the old ones both old and new popups show up, so I think it's a change detection problem.

I tried to change the mouseenter to $set(tag,'pop',true), but everything is acting the same way.
I also tried to use the $set for the adding of the new tag, even though the tag was rendered into screen, but still, nothing changed.

I'm not sure what else to do, any suggestions?

Edit:
Code for adding a new tab:

```<code>    submitTab: function(){
            this.form="";
            this.addedObj.name=document.getElementById("fNewTagTitle").value;
            this.addedObj.info=document.getElementById("fNewTagInfo").value;
            if (!this.isEditMode)
                this.isEditMode=true;
            this.editMode.add.tags.push(this.addedObj);
            this.addedObj.pop=false;
            this.addedObj.adjust= function(event) {
                left=event.target.offsetLeft;
                div=event.target.lastChild;
                div.style.left = -left+14+"px";
            };
            ref= this.addedObj.tagRef;
            delete this.addedObj.tagRef;
            this.$set(ref.tags,ref.tags.length, this.addedObj);

            this.addedObj='';
            },
</code>```

Edit 2:

Initial load of refs

```<code>        loadRefs:function(){
            this.$http.get(this.url + "/refs").then(
                function (result) {
                    data = JSON.parse(result.body);
                    var last =0;
                    for  (item of data){
                        if (item.ref_id!= last){
                            if (last!=0)
                                this.refs.push(ref);
                            var ref = new Object();
                            ref.show=false;
                            ref.refId=item.ref_id;
                            ref.type=item.ref_type_id;
                            ref.title=item.title;
                            ref.author=item.author;
                            ref.edition=item.edition;
                            ref.source=item.source;
                            ref.date=item.date;
                            ref.journal=item.journal;
                            ref.year=item.year;
                            ref.page=item.page;
                            ref.publisher=item.publisher;
                            ref.outlet=item.outlet;
                            ref.undersigned=item.undersigned;
                            ref.representing=item.representing;
                            ref.URL=item.URL;
                            ref.created_at=item.created_at;
                            ref.username=item.username;
                            ref.score=item.score;
                            ref.support=item.pivot.support;
                            ref.tags=[];
                        }
                        ref.tags.push({ name:item.tag_name, info: item.tag_info, pop:false, adjust: function(event) {
                            left=event.target.offsetLeft;
                            div=event.target.lastChild;
                            div.style.left = -left+14+"px";
                         }, });
                        last=item.ref_id;
                    }
                    if (data.length>0)
                        this.refs.push(ref);
                },
                function(result) {
                    alert( "error" );//XXX add error function
                }
            )
        },
</code>```

It's also declared in the Data section.

BTW I added the v-for a :key but it didn't change anything.

答: Try executing this.$forceUpdate() after adding the tag and see if it's rendered properly.</p>

Body:
have this code

    @{{tag.name}}

@{{tag.info}}

It's basically a popup on hover.
It works fine, but when I add a new "tag", although I see the new tag added to screen, the hover isn't working for it.

When I look in the vue devtools I can see that for the original tags the true and false change dynamically while the new tag doesn't. Although, if I remove the mouseleave event and refresh the devtools I can see the tag.pop does change to true.
If I then hover over one of the old ones both old and new popups show up, so I think it's a change detection problem.

I tried to change the mouseenter to $set(tag,'pop',true), but everything is acting the same way.
I also tried to use the $set for the adding of the new tag, even though the tag was rendered into screen, but still, nothing changed.

I'm not sure what else to do, any suggestions?

Edit:
Code for adding a new tab:

    submitTab: function(){
            this.form="";
            this.addedObj.name=document.getElementById("fNewTagTitle").value;
            this.addedObj.info=document.getElementById("fNewTagInfo").value;
            if (!this.isEditMode)
                this.isEditMode=true;
            this.editMode.add.tags.push(this.addedObj);
            this.addedObj.pop=false;
            this.addedObj.adjust= function(event) {
                left=event.target.offsetLeft;
                div=event.target.lastChild;
                div.style.left = -left+14+"px";
            };
            ref= this.addedObj.tagRef;
            delete this.addedObj.tagRef;
            this.$set(ref.tags,ref.tags.length, this.addedObj);

            this.addedObj='';
            },

Edit 2:

Initial load of refs

        loadRefs:function(){
            this.$http.get(this.url + "/refs").then(
                function (result) {
                    data = JSON.parse(result.body);
                    var last =0;
                    for  (item of data){
                        if (item.ref_id!= last){
                            if (last!=0)
                                this.refs.push(ref);
                            var ref = new Object();
                            ref.show=false;
                            ref.refId=item.ref_id;
                            ref.type=item.ref_type_id;
                            ref.title=item.title;
                            ref.author=item.author;
                            ref.edition=item.edition;
                            ref.source=item.source;
                            ref.date=item.date;
                            ref.journal=item.journal;
                            ref.year=item.year;
                            ref.page=item.page;
                            ref.publisher=item.publisher;
                            ref.outlet=item.outlet;
                            ref.undersigned=item.undersigned;
                            ref.representing=item.representing;
                            ref.URL=item.URL;
                            ref.created_at=item.created_at;
                            ref.username=item.username;
                            ref.score=item.score;
                            ref.support=item.pivot.support;
                            ref.tags=[];
                        }
                        ref.tags.push({ name:item.tag_name, info: item.tag_info, pop:false, adjust: function(event) {
                            left=event.target.offsetLeft;
                            div=event.target.lastChild;
                            div.style.left = -left+14+"px";
                         }, });
                        last=item.ref_id;
                    }
                    if (data.length>0)
                        this.refs.push(ref);
                },
                function(result) {
                    alert( "error" );//XXX add error function
                }
            )
        },

It's also declared in the Data section.

BTW I added the v-for a :key but it didn't change anything.


问:
how to treat ruby symbols in cross language object serialization
I'm currently working on a project where I need to transfer objects from ruby to python and back again, obviously serialization is the way to go. I've looked at things like yaml but decided to write my own as I didn't want to deal with the dependencies of the libraries and such when it came time to distribute.  I've wrote up how this serialization format works here.

my question is that as this format is intended to work cross language between ruby and python,
how should I serialize ruby's symbols? I'm not aware of a object that works the same way in python. should a dump containing a symbol fail? should I just serialize it as a string? what would be best?

答: Any reason you're not using a standard data interchange format like JSON or XML? They seem to be acceptable to countless applications, services, and programmers.</p>


问:
How can I change an input for a label without an error in value in Angular?
I tried to change the input for a label but it generates an error in value

This is my code

This is html

    Edad

    <input readonly type="text" [value]="CalculateAge()">

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

<p>This is how you changed by the seal as it should be?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small-6 columns">
  <label readonly for="text" [value]="CalculateAge()">
        </label>
</div></code>```

This is component

export class DatosPersonalesComponent implements OnInit {
  @Input()
  datosDTO: DatosDTO;

  public age: number;

  constructor() {}

  ngOnInit() {
    this.datosDTO = new DatosDTO();
  }
  CalculateAge(): void {
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      this.age = Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }
}```

This is error

I would greatly appreciate your help.

答:
You are trying to call the CalculateAge function in the template, where you should just be referencing the age variable.  Also, you have declared CalculateAge to have a void return type, so even if that would work it would still return nothing into the template.

When you call CalculateAge() inside your onInit and it will load the value into the age variable which will then be loaded into your template.

Finally, to solve the actual error you'll need to pass the variable inside the label tag rather than setting the value property of the tag:

```<code><div class="small-6 columns">
  <label readonly for="text">{{age}}</label>
</div>
</code>```

Body:
I tried to change the input for a label but it generates an error in value

This is my code

This is html

    Edad

    <input readonly type="text" [value]="CalculateAge()">

This is how you changed by the seal as it should be?

This is component

export class DatosPersonalesComponent implements OnInit {
  @Input()
  datosDTO: DatosDTO;

  public age: number;

  constructor() {}

  ngOnInit() {
    this.datosDTO = new DatosDTO();
  }
  CalculateAge(): void {
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      this.age = Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }
}

This is error

I would greatly appreciate your help.

Body:
You are trying to call the CalculateAge function in the template, where you should just be referencing the age variable.  Also, you have declared CalculateAge to have a void return type, so even if that would work it would still return nothing into the template.

When you call CalculateAge() inside your onInit and it will load the value into the age variable which will then be loaded into your template.

Finally, to solve the actual error you'll need to pass the variable inside the label tag rather than setting the value property of the tag:

<div class="small-6 columns">
  <label readonly for="text">{{age}}</label>
</div>