问:
How to build a hashcode to support symmetry
I wrote a PointPair class which has a 4 doubles representing the coordinate values of 2 points where first point, A= (a1,a2), second point, B=(b1,b2). I implemented hashCode and equals methods in my class and all worked well until I was told that it needs to support symmetry, i.e. a PointPair object built with A,B needs to be equal to PointPair built with B,A.  </p>

```<code>class PointPair {
    public final double a1, a2, b1, b2;

    public PointPair(Point a, Point b) {
        this.a1 = a.x; this.a2 = a.y;
        this.b1 = b.x; this.b2 = b.y;
    }

    public int hashCode() {
        return Objects.hash(a1, a2, b1, b2); // fix me!
    }

    private boolean bothEqual(double d1, d2) {
       return Double.compare(d1,d2) == 0 ;
    }

    public boolean equals(Object obj) {
        if ((obj == null) || !(obj instanceof PointPair))
            return false;
        PointPair pObj = (PointPair) obj;

        //test for same reference or value match
        return (obj == this) || (bothEqual(a1, pObj.a1) && bothEqual(a2, pObj.a2) && bothEqual(b1, pObj.b1) && bothEqual(b2, pObj.b2)) ||
                (bothEqual(a1, pObj.b1) && bothEqual(a2, pObj.b2) && bothEqual(b1, pObj.a1) && bothEqual(b2, pObj.a2)) ; // symmetry match
    }

}
</code>```

<p>I changed my equals method to support that (pls see above) but I'm looking for ideas to fix the hashCode method or some other scheme for the class.
One idea that came to my mind was to compute a dot-product metric using two imaginary vectors that represented the points (thinking geometrically) and the angle between them.  Will this always give a unique value for the 2 points in my point-pair? </p>

```<code>    public int hashCode() {
         double dotprod = (a1*b1)+(a2*b2) ;
         double mag1 = Math.sqrt(a1*a1+a2*a2)
         double mag2 = Math.sqrt(b1*b1+b2*b2)
         double angle = Math.acos(dotprod/(mag1*mag2))
         Objects.hash(dotprod, angle)
    }
</code>```

答:
You can do this with addition. In the same style as your existing hashCode, it would be:

```<code>Objects.hash(a1, a2) + Objects.hash(b1, b2)
</code>```

This is, for example, how java.util.Set specifies its hashCode to be order-independent.

Another way would be to use XOR.

Body:
I wrote a PointPair class which has a 4 doubles representing the coordinate values of 2 points where first point, A= (a1,a2), second point, B=(b1,b2). I implemented hashCode and equals methods in my class and all worked well until I was told that it needs to support symmetry, i.e. a PointPair object built with A,B needs to be equal to PointPair built with B,A.

class PointPair {
    public final double a1, a2, b1, b2;

    public PointPair(Point a, Point b) {
        this.a1 = a.x; this.a2 = a.y;
        this.b1 = b.x; this.b2 = b.y;
    }

    public int hashCode() {
        return Objects.hash(a1, a2, b1, b2); // fix me!
    }

    private boolean bothEqual(double d1, d2) {
       return Double.compare(d1,d2) == 0 ;
    }

    public boolean equals(Object obj) {
        if ((obj == null) || !(obj instanceof PointPair))
            return false;
        PointPair pObj = (PointPair) obj;

        //test for same reference or value match
        return (obj == this) || (bothEqual(a1, pObj.a1) && bothEqual(a2, pObj.a2) && bothEqual(b1, pObj.b1) && bothEqual(b2, pObj.b2)) ||
                (bothEqual(a1, pObj.b1) && bothEqual(a2, pObj.b2) && bothEqual(b1, pObj.a1) && bothEqual(b2, pObj.a2)) ; // symmetry match
    }

}

I changed my equals method to support that (pls see above) but I'm looking for ideas to fix the hashCode method or some other scheme for the class.
One idea that came to my mind was to compute a dot-product metric using two imaginary vectors that represented the points (thinking geometrically) and the angle between them.  Will this always give a unique value for the 2 points in my point-pair?

    public int hashCode() {
         double dotprod = (a1*b1)+(a2*b2) ;
         double mag1 = Math.sqrt(a1*a1+a2*a2)
         double mag2 = Math.sqrt(b1*b1+b2*b2)
         double angle = Math.acos(dotprod/(mag1*mag2))
         Objects.hash(dotprod, angle)
    }

Body:
You can do this with addition. In the same style as your existing hashCode, it would be:

Objects.hash(a1, a2) + Objects.hash(b1, b2)

This is, for example, how java.util.Set specifies its hashCode to be order-independent.

Another way would be to use XOR.


来源: stackexchange

问:
Yahoo finance.yahoo.com/quotes is redirecting
I use https://finance.yahoo.com/quotes/... for stock quotes and option data.  It continues to work well when viewed in a Safari browser.  I also take it in to an Objective C app as an NSURLSession dataTaskWithUrL.  Last week (circa April 28, 2017)it started forcing a redirect by calling willPerformHTTPRedirection: but the redirect loops to itself and generates the "too many HTTP redirects" error. </p>

<p>Does anyone have a workaround for this?  </p>

答:
Here's the solution I finally came up with:

In the original NSURLRequest, make it an NSURLMutableRequest and add:

```<code>[theRequest setValue:@"Mozilla......." forHTTPHeaderField:@"User-Agent"];
</code>```

This 'spoofing the browser' often works with no redirects.  But sometimes there is a redirect.  Therefore I also added the method:

```<code>- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler{
</code>```

and in the completion handler I examine the task.currentRequest valueForHTTPHeaderField:, set it to a different browser and generate a new NSURLRequest with the different browser.  It seems to be working.

ContentLicense: CC BY-SA 3.0

Body:
I use https://finance.yahoo.com/quotes/... for stock quotes and option data.  It continues to work well when viewed in a Safari browser.  I also take it in to an Objective C app as an NSURLSession dataTaskWithUrL.  Last week (circa April 28, 2017)it started forcing a redirect by calling willPerformHTTPRedirection: but the redirect loops to itself and generates the "too many HTTP redirects" error.

Does anyone have a workaround for this?

Body:
Here's the solution I finally came up with:

In the original NSURLRequest, make it an NSURLMutableRequest and add:

[theRequest setValue:@"Mozilla......." forHTTPHeaderField:@"User-Agent"];

This 'spoofing the browser' often works with no redirects.  But sometimes there is a redirect.  Therefore I also added the method:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler{

and in the completion handler I examine the task.currentRequest valueForHTTPHeaderField:, set it to a different browser and generate a new NSURLRequest with the different browser.  It seems to be working.


问:
Text Analysis Program used to Work, Now it Doesn't
I wrote a file shown below (from the infamous Coursera course and beyond) and it has served me well.  Not sure if something has changed, but it doesn't seem to work now and I have changed nothing.

The first thing that doesn't seem to work is the for loop to remove the special characters.

Next, when I treat it as a Plan Text Doc, the word cloud doesn't seem to want to work.

Finally, the tokenizer functions are producing the same chart, essentially the frequently used single words vs. the ngrams as programmed.  Meaning each ngram is just producing the same chart, the most frequently used words vs. the ngram of 2,3,4 words, etc...

Not sure if package updates or R updates are causing this.

Any thoughts?

```<code>#Set working directory and read file
cname <- file.path( "c:/texts")
cname
dir(cname)
setwd("c:/texts")

library("RColorBrewer")
library("tm")
library("knitr")
library("devtools")
library("plyr")
library("ggplot2")
library("wordcloud")
library("rJava")
library("RWeka")
library("stringi")
library("XLConnect")
library("XLConnectJars")

df<- readWorksheetFromFile("uars.xlsx", sheet=1, startRow=1)
df1 <- df[df$Business %in% "FRAUD", ]

#Load the R package for text mining and then load your texts into R.
library(tm)

docs <- Corpus(VectorSource(df1))

summary(docs)

#read your documents in the R terminal using
inspect(docs)

#Preprocessing

#Removing punctuation
docs <- tm_map(docs, removePunctuation)

# remove special characters.
for(j in seq(docs))
{
  docs[[j]] <- gsub("/", " ", docs[[j]])
  docs[[j]] <- gsub("@", " ", docs[[j]])
  docs[[j]] <- gsub("\\|", " ", docs[[j]])
}

#Removing numbers:
docs <- tm_map(docs, removeNumbers)

#Converting to lowercase:
docs <- tm_map(docs, tolower)

#Removing "stopwords" (common words) that usually have no analytic value
docs <- tm_map(docs, removeWords, c(stopwords("english"), "bank", "account", "customer", "transactions", "sent", "received", "company",
                                    "wire", "wires", "payment", "payments", "wells", "fargo", "transaction", "fraud", "wholesale", "wholesal", "uar", "email"))
#Removing common word endings (e.g., "ing", "es", "s")
library(SnowballC)
docs <- tm_map(docs, stemDocument)

#Stripping unnecesary whitespace from your documents:
docs <- tm_map(docs, stripWhitespace)

#treat your preprocessed documents as text documents.
docs <- tm_map(docs, PlainTextDocument)

#Stage the Data

#To proceed, create a document term matrix
dtm <- DocumentTermMatrix(docs)
dtm
inspect(dtm)

#transpose of this matrix
tdm <- TermDocumentMatrix(docs)
tdm

##TCorpus <- tm_map(TCorpus, removeWords, badWords)
wordcloud(docs, scale=c(3,0.5), min.freq=5, max.words=100, random.order=TRUE,
          rot.per=0.5, colors=brewer.pal(8, "Set1"), use.r.layout=FALSE)
#Tokenizer functions
bigram <- function(x) NGramTokenizer(x, Weka_control(min=2, max=2))
trigram <- function(x) NGramTokenizer(x, Weka_control(min=3, max=3))
quadgram <- function(x) NGramTokenizer(x, Weka_control(min=4, max=4))
fivegram <- function(x) NGramTokenizer (x, Weka_control(min=5, max=5))
sixgram <- function(x) NGramTokenizer (x, Weka_control(min=6, max=6))

#Word/phrase count function
freq_df <- function(tdm){
  # Helper function to tabulate frequency
  freq <- sort(rowSums(as.matrix(tdm)), decreasing=TRUE)
  freq_df <- data.frame(word=names(freq), freq=freq)
  return(freq_df)
}

#Creating the n-grams
corpus.unigram <- TermDocumentMatrix(docs)
corpus.unigram <- removeSparseTerms(corpus.unigram, 0.99)
corpus.unigram.freq <- freq_df(corpus.unigram)

corpus.bigram <- TermDocumentMatrix(docs, control=list(tokenize=bigram))
corpus.bigram <- removeSparseTerms(corpus.bigram, 0.999)
corpus.bigram.freq <- freq_df(corpus.bigram)

corpus.trigram <- TermDocumentMatrix(docs, control=list(tokenize=trigram))
corpus.trigram <- removeSparseTerms(corpus.trigram, 0.99)
corpus.trigram.freq <- freq_df(corpus.trigram)

corpus.quadgram <- TermDocumentMatrix(docs, control=list(tokenize=quadgram))
corpus.quadgram <- removeSparseTerms(corpus.quadgram, 0.9999)
corpus.quadgram.freq <- freq_df(corpus.quadgram)

corpus.fivegram <- TermDocumentMatrix(docs, control=list(tokenize=fivegram))
corpus.fivegram <- removeSparseTerms(corpus.fivegram, 0.9999)
corpus.fivegram.freq <- freq_df(corpus.fivegram)

corpus.sixgram <- TermDocumentMatrix(docs, control=list(tokenize=sixgram))
corpus.sixgram <- removeSparseTerms(corpus.sixgram, 0.9999)
corpus.sixgram.freq <- freq_df(corpus.sixgram)

top_50 <- function(df1, title, color) {
  ggplot(df[1:50,], aes(x = seq(1:50), y = freq)) +
    geom_bar(stat = "identity", fill = color, colour = "black", width = 0.80) +
    coord_cartesian(xlim = c(0, 51)) +
    labs(title = title) +
    xlab("Words") +
    ylab("Count") +
    scale_x_continuous(breaks = seq(1, 50, by = 1), labels = df$word[1:50]) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1))
}

top_50(corpus.unigram.freq,"Top 50 words","green")
top_50(corpus.bigram.freq,"Top 2 word combos","yellow")
top_50(corpus.trigram.freq,"Top 3 word combos","orange")
top_50(corpus.quadgram.freq,"Top 4 word combos","red")
top_50(corpus.fivegram.freq,"Top 5 word combos","blue")
top_50(corpus.sixgram.freq,"Top 6 word combos","purple")
</code>```

答: I found the issue.  In the code above, I was using a simple Corpus (Corpus) which will not work with the controls in Rweka(Weka_control).  I switched to VCorpus and all is well.</p>

Body:
I wrote a file shown below (from the infamous Coursera course and beyond) and it has served me well.  Not sure if something has changed, but it doesn't seem to work now and I have changed nothing.

The first thing that doesn't seem to work is the for loop to remove the special characters.

Next, when I treat it as a Plan Text Doc, the word cloud doesn't seem to want to work.

Finally, the tokenizer functions are producing the same chart, essentially the frequently used single words vs. the ngrams as programmed.  Meaning each ngram is just producing the same chart, the most frequently used words vs. the ngram of 2,3,4 words, etc...

Not sure if package updates or R updates are causing this.

Any thoughts?

#Set working directory and read file
cname <- file.path( "c:/texts")
cname
dir(cname)
setwd("c:/texts")

library("RColorBrewer")
library("tm")
library("knitr")
library("devtools")
library("plyr")
library("ggplot2")
library("wordcloud")
library("rJava")
library("RWeka")
library("stringi")
library("XLConnect")
library("XLConnectJars")

df<- readWorksheetFromFile("uars.xlsx", sheet=1, startRow=1)
df1 <- df[df$Business %in% "FRAUD", ]

#Load the R package for text mining and then load your texts into R.
library(tm)

docs <- Corpus(VectorSource(df1))

summary(docs)

#read your documents in the R terminal using
inspect(docs)

#Preprocessing

#Removing punctuation
docs <- tm_map(docs, removePunctuation)

# remove special characters.
for(j in seq(docs))
{
  docs[[j]] <- gsub("/", " ", docs[[j]])
  docs[[j]] <- gsub("@", " ", docs[[j]])
  docs[[j]] <- gsub("\\|", " ", docs[[j]])
}

#Removing numbers:
docs <- tm_map(docs, removeNumbers)

#Converting to lowercase:
docs <- tm_map(docs, tolower)

#Removing "stopwords" (common words) that usually have no analytic value
docs <- tm_map(docs, removeWords, c(stopwords("english"), "bank", "account", "customer", "transactions", "sent", "received", "company",
                                    "wire", "wires", "payment", "payments", "wells", "fargo", "transaction", "fraud", "wholesale", "wholesal", "uar", "email"))
#Removing common word endings (e.g., "ing", "es", "s")
library(SnowballC)
docs <- tm_map(docs, stemDocument)

#Stripping unnecesary whitespace from your documents:
docs <- tm_map(docs, stripWhitespace)

#treat your preprocessed documents as text documents.
docs <- tm_map(docs, PlainTextDocument)

#Stage the Data

#To proceed, create a document term matrix
dtm <- DocumentTermMatrix(docs)
dtm
inspect(dtm)

#transpose of this matrix
tdm <- TermDocumentMatrix(docs)
tdm

##TCorpus <- tm_map(TCorpus, removeWords, badWords)
wordcloud(docs, scale=c(3,0.5), min.freq=5, max.words=100, random.order=TRUE,
          rot.per=0.5, colors=brewer.pal(8, "Set1"), use.r.layout=FALSE)
#Tokenizer functions
bigram <- function(x) NGramTokenizer(x, Weka_control(min=2, max=2))
trigram <- function(x) NGramTokenizer(x, Weka_control(min=3, max=3))
quadgram <- function(x) NGramTokenizer(x, Weka_control(min=4, max=4))
fivegram <- function(x) NGramTokenizer (x, Weka_control(min=5, max=5))
sixgram <- function(x) NGramTokenizer (x, Weka_control(min=6, max=6))

#Word/phrase count function
freq_df <- function(tdm){
  # Helper function to tabulate frequency
  freq <- sort(rowSums(as.matrix(tdm)), decreasing=TRUE)
  freq_df <- data.frame(word=names(freq), freq=freq)
  return(freq_df)
}

#Creating the n-grams
corpus.unigram <- TermDocumentMatrix(docs)
corpus.unigram <- removeSparseTerms(corpus.unigram, 0.99)
corpus.unigram.freq <- freq_df(corpus.unigram)

corpus.bigram <- TermDocumentMatrix(docs, control=list(tokenize=bigram))
corpus.bigram <- removeSparseTerms(corpus.bigram, 0.999)
corpus.bigram.freq <- freq_df(corpus.bigram)

corpus.trigram <- TermDocumentMatrix(docs, control=list(tokenize=trigram))
corpus.trigram <- removeSparseTerms(corpus.trigram, 0.99)
corpus.trigram.freq <- freq_df(corpus.trigram)

corpus.quadgram <- TermDocumentMatrix(docs, control=list(tokenize=quadgram))
corpus.quadgram <- removeSparseTerms(corpus.quadgram, 0.9999)
corpus.quadgram.freq <- freq_df(corpus.quadgram)

corpus.fivegram <- TermDocumentMatrix(docs, control=list(tokenize=fivegram))
corpus.fivegram <- removeSparseTerms(corpus.fivegram, 0.9999)
corpus.fivegram.freq <- freq_df(corpus.fivegram)

corpus.sixgram <- TermDocumentMatrix(docs, control=list(tokenize=sixgram))
corpus.sixgram <- removeSparseTerms(corpus.sixgram, 0.9999)
corpus.sixgram.freq <- freq_df(corpus.sixgram)

top_50 <- function(df1, title, color) {
  ggplot(df[1:50,], aes(x = seq(1:50), y = freq)) +
    geom_bar(stat = "identity", fill = color, colour = "black", width = 0.80) +
    coord_cartesian(xlim = c(0, 51)) +
    labs(title = title) +
    xlab("Words") +
    ylab("Count") +
    scale_x_continuous(breaks = seq(1, 50, by = 1), labels = df$word[1:50]) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1))
}

top_50(corpus.unigram.freq,"Top 50 words","green")
top_50(corpus.bigram.freq,"Top 2 word combos","yellow")
top_50(corpus.trigram.freq,"Top 3 word combos","orange")
top_50(corpus.quadgram.freq,"Top 4 word combos","red")
top_50(corpus.fivegram.freq,"Top 5 word combos","blue")
top_50(corpus.sixgram.freq,"Top 6 word combos","purple")


问:
HTML panel to appear/disappear depending on DataTables Select
Im using datatables responsive/select right now to display some data. How would I go about making it so when I click on any of these rows in the table, it opens up the "col-md-6" panel? So hidden when no rows are selected, then shown when a row is selected.

```<code><!-- begin row -->
<div class="row">
    <!-- begin col-2 -->
    <div class="col-md-2">
        <div id="menu-panel"></div>
        <!-- begin panel -->
        <div class="panel panel-inverse">
            <div class="panel-heading">
                <div class="panel-heading-btn">
                    <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
                </div>
                <h4 class="panel-title">Digital Inputs</h4>
            </div>
            <div class="alert alert-info fade in">
                <button type="button" class="close" data-dismiss="alert">
                    <span aria-hidden="true">×</span>
                </button>
                Click on a Digital Input to edit its properties.
            </div>
            <div class="panel-body">
                <table id="data-table" class="table table-striped table-bordered nowrap" width="100%">
                    <thead>
                        <tr>
                            <th>Input</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="gradeA">
                            <td>1</td>
                            <td>Digital Input 1</td>
                        </tr>
                        <tr class="gradeA">
                            <td>2</td>
                            <td>Digital Input 2</td>
                        </tr>
                        <tr class="gradeA">
                            <td>3</td>
                            <td>Digital Input 3</td>
                        </tr>
                        <tr class="gradeA">
                            <td>4</td>
                            <td>Digital Input 4</td>
                        </tr>
                        <tr class="gradeA">
                            <td>5</td>
                            <td>Digital Input 5</td>
                        </tr>
                        <tr class="gradeA">
                            <td>6</td>
                            <td>Digital Input 6</td>
                        </tr>
                        <tr class="gradeA">
                            <td>7</td>
                            <td>Digital Input 7</td>
                        </tr>
                        <tr class="gradeA">
                            <td>8</td>
                            <td>Digital Input 8</td>
                        </tr>
                        <tr class="gradeA">
                            <td>9</td>
                            <td>Digital Input 9</td>
                        </tr>
                        <tr class="gradeA">
                            <td>10</td>
                            <td>Digital Input 10</td>
                        </tr>
                        <tr class="gradeA">
                            <td>11</td>
                            <td>Digital Input 11</td>
                        </tr>
                        <tr class="gradeA">
                            <td>12</td>
                            <td>Digital Input 12</td>
                        </tr>
                        <tr class="gradeA">
                            <td>13</td>
                            <td>Digital Input 13</td>
                        </tr>
                        <tr class="gradeA">
                            <td>14</td>
                            <td>Digital Input 14</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- end panel -->
    </div>

    <!-- begin col-2 -->
    <div class="col-md-6">
        <!-- begin panel -->
        <div class="panel panel-inverse" data-sortable-id="form-stuff-2">
            <div class="panel-heading">
                <div class="panel-heading-btn">
                    <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
                </div>
                <h4 class="panel-title">New RTU FZB-1000 - FZB-1000</h4>
            </div>
            <div class="panel-body">
                <form class="form-horizontal" action="/" method="POST">
                <legend>Digital Input Basic Settings</legend>
                    <div class="form-group">
                        <label class="col-md-4 control-label">Digital Input:</label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" placeholder="1" disabled />
                        </div>
                    </div>
                     <div class="form-group">
                            <label class="col-md-4 control-label">Display Input:</label>
                            <div class="col-md-2">
                                <input type="checkbox" name="" value="" checked><br>
                            </div>
                    </div>
                    <div class="form-group">
                            <label class="col-md-4 control-label">Signal Name:</label>
                            <div class="col-md-8">
                                <input type="device" class="form-control" value="Digital Input 1" />
                            </div>
                        </div>
            </div>
        </div>
        <!-- end panel -->
        <div class="col-md-8 col-md-offset-4">
            <button type="submit" class="btn btn-sm btn-primary m-r-5">Save</button>
            <button type="submit" class="btn btn-sm btn-default">Cancel</button>
        </div>
    </div>
    <!-- end col-10 -->

</div>
<!-- end row -->
</code>```

```<code>App.restartGlobalFunction();
App.setPageTitle('Color Admin | Managed Tables - Select');
$.getScript('assets/plugins/DataTables/media/js/jquery.dataTables.js').done(function() {
$.getScript('assets/plugins/DataTables/media/js/dataTables.bootstrap.min.js').done(function() {
    $.getScript('assets/plugins/DataTables/extensions/Select/js/dataTables.select.min.js').done(function() {
        $.getScript('assets/plugins/DataTables/extensions/Responsive/js/dataTables.responsive.min.js').done(function() {
            $.getScript('assets/js/table-manage-select.demo.min.js').done(function() {
                TableManageTableSelect.init();
            });
        });
    });
});
});
</code>```

答:
I don't see any JS, you should attempt this yourself. What I can say is that in order to get what you need, you will have to call the inputs and according to which column is selected on the table, place those values equal to what is selected.

So, if you click on  Digital Input 1, set the value for Digital Input to the row selected but the first column. It will display the value of 1.

Then you just need to call the value of the selected column to the signal name and it will display Digital Input 1.

None of your elements have id tags.
In order to do this, your rows and columns will need to have id tags. Then you can easily grab the innerHTML of the id using JS.

I hope this helps.

Body:
Im using datatables responsive/select right now to display some data. How would I go about making it so when I click on any of these rows in the table, it opens up the "col-md-6" panel? So hidden when no rows are selected, then shown when a row is selected.

Digital Inputs

                <button type="button" class="close" data-dismiss="alert">
                    ×
                </button>
                Click on a Digital Input to edit its properties.

                            Input
                            Name

                            1
                            Digital Input 1

                            2
                            Digital Input 2

                            3
                            Digital Input 3

                            4
                            Digital Input 4

                            5
                            Digital Input 5

                            6
                            Digital Input 6

                            7
                            Digital Input 7

                            8
                            Digital Input 8

                            9
                            Digital Input 9

                            10
                            Digital Input 10

                            11
                            Digital Input 11

                            12
                            Digital Input 12

                            13
                            Digital Input 13

                            14
                            Digital Input 14

New RTU FZB-1000 - FZB-1000

                <form class="form-horizontal" action="/" method="POST">
                <legend>Digital Input Basic Settings</legend>

                        Digital Input:

                            <input type="text" class="form-control" placeholder="1" disabled />

                            Display Input:

                                <input type="checkbox" name="" value="" checked>

                            Signal Name:

                                <input type="device" class="form-control" value="Digital Input 1" />

            <button type="submit" class="btn btn-sm btn-primary m-r-5">Save</button>
            <button type="submit" class="btn btn-sm btn-default">Cancel</button>

App.restartGlobalFunction();
App.setPageTitle('Color Admin | Managed Tables - Select');
$.getScript('assets/plugins/DataTables/media/js/jquery.dataTables.js').done(function() {
$.getScript('assets/plugins/DataTables/media/js/dataTables.bootstrap.min.js').done(function() {
    $.getScript('assets/plugins/DataTables/extensions/Select/js/dataTables.select.min.js').done(function() {
        $.getScript('assets/plugins/DataTables/extensions/Responsive/js/dataTables.responsive.min.js').done(function() {
            $.getScript('assets/js/table-manage-select.demo.min.js').done(function() {
                TableManageTableSelect.init();
            });
        });
    });
});
});


问:
Run Time error 6 Overrun in vba for excel
I'm running the following program, and get an overflow error at the first iteration once the program gets to a. From my understanding this shouldn't happen because I'm using Doubles which have a ridiculous amount of capacity, and a Long, but because it's only going up to 100 currently it shouldn't matter, and the code fails long before then. Here is my original inputs:

```<code>h0 = 1000, v0 = 0, a0 = g = -9.80665, dt = .01, m = 752.2528, b = .287875
</code>```

and here's the code:

```<code>Sub drag()
    Dim h0 As Double
    Dim v0 As Double
    Dim a0 As Double
    Dim dt As Double
    Dim m As Double
    Dim b As Double
    Dim g As Double
    Dim i As Long
    Dim h As Double
    Dim v As Double
    Dim a As Double

    h0 = Worksheets("Drag").Cells(2, 8).Value
    v0 = Worksheets("Drag").Cells(2, 9).Value
    a0 = Worksheets("Drag").Cells(2, 10).Value
    g = Worksheets("Drag").Cells(2, 10).Value
    dt = Worksheets("Drag").Cells(2, 7).Value
    m = Worksheets("Drag").Cells(2, 4).Value
    b = Worksheets("Drag").Cells(2, 5).Value
    Debug.Print h0 & v0 & a0 & dt & m & b

    For i = 1 To 100
        v = v0 + a0 * dt
        h = 0.5 * a0 * (dt ^ 2) + v0 * dt + h0
        a = m * g - b * (v ^ 2)   'Line where overflow occurs
        v0 = v
        h0 = h
        a0 = a
        Cells(i + 2, 8) = h0
        Cells(i + 2, 9) = v0
        Cells(i + 2, 10) = a0
        Next i
    Debug.Print h0 & v0 & a0 & dt & m & b
End Sub
</code>```

Hope this is an easy fix.

答:
The variable in question that is getting an overflow is v.  You defined it as a double, which means you can only put numbers in the range of 1.79769313486232 * 10^308 to 4.94065645841247 * 10^–324. VBA uses 8 bytes to hold the double data.  Any number outside of this huge range causes an overflow. (see here for more information about DBA data types)

How big of a number are you expecting?  A rough estimate fo the number of atoms in the universe is 1 * 10^82, and the double value range goes to almost 2 *10^308.  If you need to work with numbers that large, you're going to have to use a different method because it simply won't fit in the standard VBA data types.

Body:
I'm running the following program, and get an overflow error at the first iteration once the program gets to a. From my understanding this shouldn't happen because I'm using Doubles which have a ridiculous amount of capacity, and a Long, but because it's only going up to 100 currently it shouldn't matter, and the code fails long before then. Here is my original inputs:

h0 = 1000, v0 = 0, a0 = g = -9.80665, dt = .01, m = 752.2528, b = .287875

and here's the code:

Sub drag()
    Dim h0 As Double
    Dim v0 As Double
    Dim a0 As Double
    Dim dt As Double
    Dim m As Double
    Dim b As Double
    Dim g As Double
    Dim i As Long
    Dim h As Double
    Dim v As Double
    Dim a As Double

    h0 = Worksheets("Drag").Cells(2, 8).Value
    v0 = Worksheets("Drag").Cells(2, 9).Value
    a0 = Worksheets("Drag").Cells(2, 10).Value
    g = Worksheets("Drag").Cells(2, 10).Value
    dt = Worksheets("Drag").Cells(2, 7).Value
    m = Worksheets("Drag").Cells(2, 4).Value
    b = Worksheets("Drag").Cells(2, 5).Value
    Debug.Print h0 & v0 & a0 & dt & m & b

    For i = 1 To 100
        v = v0 + a0 * dt
        h = 0.5 * a0 * (dt ^ 2) + v0 * dt + h0
        a = m * g - b * (v ^ 2)   'Line where overflow occurs
        v0 = v
        h0 = h
        a0 = a
        Cells(i + 2, 8) = h0
        Cells(i + 2, 9) = v0
        Cells(i + 2, 10) = a0
        Next i
    Debug.Print h0 & v0 & a0 & dt & m & b
End Sub

Hope this is an easy fix.


问:
Show Google Map In Modal After Ajax Call
so I'm working on a site where I want to show a google map inside a modal after an ajax call. I'm using bootstrap to show a modal, the problem is the map just stays blank after the modal is opened.

Something weird that happens is when I hit f12 on chrome to bring up the developer tab the map magically shows up although not centered on the marker position.

This is my Ajax Call:

```<code>$('.btnSeeOrder').on("click", function(){
    $("#modalSeeOrder").modal("show"); //open bootstrap modal
    var order_id = $(this).attr("data-orderId");

    $.ajax({
      type: "POST",
      url: "get_order_details.php",
      data: {
        order_id: order_id
      },
      beforeSend: function(){
        $(".order-details-modal").html("<i class='glyphicon glyphicon-refresh spinning'></i>");
      },
      success: function(data){
        $(".order-details-modal").html(data);
      },
      error: function(){
        $(".order-details-modal").html("<b>Ooops... Error....</b>");
      }
    });
  });
</code>```

This is my get_order_details.php file:

```<code><?php
  require '../../../app/Functions.php';
  $obj = new Admin_Functions();

  //Get order info, user info and map
  $info = $obj->getOrderInfo($_POST['order_id']);

?>

<div class="row">
  <div class="col-lg-12" style="margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid #ccc;">
    <div class="row">
      <div id="map-canvas" style="width: 100%; height: 400px;"></div>

    </div>
  </div>
</div>

<script type="text/javascript">
// latitude and longitude are being loaded in from the database
// example coords from database: 50.44444,-19.444444

var myLatlng = new google.maps.LatLng(<?php echo explode(",", $info["lat_lng"])[0]; ?>,<?php echo explode(",", $info["lat_lng"])[1]; ?>);
var mapOptions = {
  zoom: 16,
  center: myLatlng,
  styles:
  [{"featureType":"landscape","elementType":"geometry","stylers":[{"saturation":"-100"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#e9e5dc"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels.text","stylers":[{"color":"#545454"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"saturation":"-87"},{"lightness":"-40"},{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.fill","stylers":[{"color":"#f0f0f0"},{"saturation":"-22"},{"lightness":"-16"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"labels.icon","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.local","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"saturation":"-52"},{"hue":"#00e4ff"},{"lightness":"-16"}]}]
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  icon: 'https://www.robotevents.com/images/maps/markers/orange.png'
});
</script>
</code>```

This is what the map looks like when loaded in:

Anyone know how I can fix or go about this issue? Any help is greatly appreciated!

答:
Ok so as some of the comments said and investigating a bit more I have found the solution. I added some javascript code in my get_order_details.php file after the var marker = google.... to redraw and center my map after the modal has been opened:

```<code>google.maps.event.addListenerOnce(map, 'idle', function() {
     google.maps.event.trigger(map, 'resize');

    // Recenter the map now that it's been redrawn
    var reCenter = new google.maps.LatLng(<?php echo explode(",", $info["lat_lng"])[0]; ?>,<?php echo explode(",", $info["lat_lng"])[1]; ?>);
    map.setCenter(reCenter);
  });
</code>```

So the whole javascript inside get_order_details.php ended up looking like this:

```<code><script type="text/javascript">
  //Show google map
  var myLatlng = new google.maps.LatLng(<?php echo explode(",", $info[0]["lat_lng"])[0]; ?>,<?php echo explode(",", $info[0]["lat_lng"])[1]; ?>);
  var mapOptions = {
    zoom: 16,
    center: myLatlng,
    styles:
    [{"featureType":"landscape","elementType":"geometry","stylers":[{"saturation":"-100"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#e9e5dc"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels.text","stylers":[{"color":"#545454"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"saturation":"-87"},{"lightness":"-40"},{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.fill","stylers":[{"color":"#f0f0f0"},{"saturation":"-22"},{"lightness":"-16"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"labels.icon","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.local","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"saturation":"-52"},{"hue":"#00e4ff"},{"lightness":"-16"}]}]
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    icon: 'https://www.robotevents.com/images/maps/markers/orange.png'
  });

  //Redraw and center map
  google.maps.event.addListenerOnce(map, 'idle', function() {
     google.maps.event.trigger(map, 'resize');

    // Recenter the map now that it's been redrawn
    var reCenter = new google.maps.LatLng(<?php echo explode(",", $info["lat_lng"])[0]; ?>,<?php echo explode(",", $info["lat_lng"])[1]; ?>);
    map.setCenter(reCenter);
  });
</script>
</code>```

Body:
so I'm working on a site where I want to show a google map inside a modal after an ajax call. I'm using bootstrap to show a modal, the problem is the map just stays blank after the modal is opened.

Something weird that happens is when I hit f12 on chrome to bring up the developer tab the map magically shows up although not centered on the marker position.

This is my Ajax Call:

$('.btnSeeOrder').on("click", function(){
    $("#modalSeeOrder").modal("show"); //open bootstrap modal
    var order_id = $(this).attr("data-orderId");

    $.ajax({
      type: "POST",
      url: "get_order_details.php",
      data: {
        order_id: order_id
      },
      beforeSend: function(){
        $(".order-details-modal").html("");
      },
      success: function(data){
        $(".order-details-modal").html(data);
      },
      error: function(){
        $(".order-details-modal").html("Ooops... Error....");
      }
    });
  });

This is my get_order_details.php file:

<?php
  require '../../../app/Functions.php';
  $obj = new Admin_Functions();

  //Get order info, user info and map
  $info = $obj->getOrderInfo($_POST['order_id']);

?>

This is what the map looks like when loaded in:

Anyone know how I can fix or go about this issue? Any help is greatly appreciated!

Body:
Ok so as some of the comments said and investigating a bit more I have found the solution. I added some javascript code in my get_order_details.php file after the var marker = google.... to redraw and center my map after the modal has been opened:

google.maps.event.addListenerOnce(map, 'idle', function() {
     google.maps.event.trigger(map, 'resize');

    // Recenter the map now that it's been redrawn
    var reCenter = new google.maps.LatLng(<?php echo explode(",", $info["lat_lng"])[0]; ?>,<?php echo explode(",", $info["lat_lng"])[1]; ?>);
    map.setCenter(reCenter);
  });

So the whole javascript inside get_order_details.php ended up looking like this:

<script type="text/javascript">
  //Show google map
  var myLatlng = new google.maps.LatLng(<?php echo explode(",", $info[0]["lat_lng"])[0]; ?>,<?php echo explode(",", $info[0]["lat_lng"])[1]; ?>);
  var mapOptions = {
    zoom: 16,
    center: myLatlng,
    styles:
    [{"featureType":"landscape","elementType":"geometry","stylers":[{"saturation":"-100"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#e9e5dc"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels.text","stylers":[{"color":"#545454"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"saturation":"-87"},{"lightness":"-40"},{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.fill","stylers":[{"color":"#f0f0f0"},{"saturation":"-22"},{"lightness":"-16"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"labels.icon","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.local","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"saturation":"-52"},{"hue":"#00e4ff"},{"lightness":"-16"}]}]
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    icon: 'https://www.robotevents.com/images/maps/markers/orange.png'
  });

  //Redraw and center map
  google.maps.event.addListenerOnce(map, 'idle', function() {
     google.maps.event.trigger(map, 'resize');

    // Recenter the map now that it's been redrawn
    var reCenter = new google.maps.LatLng(<?php echo explode(",", $info["lat_lng"])[0]; ?>,<?php echo explode(",", $info["lat_lng"])[1]; ?>);
    map.setCenter(reCenter);
  });
</script>


问:
Why does my Oracle JVM create all these objects for a simple 'Hello World' program?
I was playing around with jmap and found that simple "Hello World" Java program creates thousands of objects. Here is truncated list of objects Oracle JVM update 131 creates on startup:

```<code> num     #instances         #bytes  class name
----------------------------------------------
   1:           402        4903520  [I
   2:          1621         158344  [C
   3:           455          52056  java.lang.Class
   4:           194          49728  [B
   5:          1263          30312  java.lang.String
   6:           515          26088  [Ljava.lang.Object;
   7:           115           8280  java.lang.reflect.Field
   8:           258           4128  java.lang.Integer
   9:            94           3760  java.lang.ref.SoftReference
  10:           116           3712  java.util.Hashtable$Entry
  11:           126           3024  java.lang.StringBuilder
  12:             8           3008  java.lang.Thread
  13:            74           2576  [Ljava.lang.String;
  14:            61           1952  java.io.File
  15:            38           1824  sun.util.locale.LocaleObjectCache$CacheEntry
  16:            12           1760  [Ljava.util.Hashtable$Entry;
  17:            53           1696  java.util.concurrent.ConcurrentHashMap$Node
  18:            23           1472  java.net.URL
  19:            14           1120  [S
  20:             2           1064  [Ljava.lang.invoke.MethodHandle;
  21:             1           1040  [Ljava.lang.Integer;
  22:            26           1040  java.io.ObjectStreamField
  23:            12           1024  [Ljava.util.HashMap$Node;
  24:            30            960  java.util.HashMap$Node
  25:            20            800  sun.util.locale.BaseLocale$Key
</code>```

I know that the JVM loads classes from JAR files and expect to see java.lang.Class, java.lang.String and [Ljava.lang.Object. 258 java.lang.Integer objects are clear tp me too: this is the Integer cache.

But java.lang.reflect.Field? Hashtable? Many StringBuilders? java.util.concurrent.ConcurrentHashMap? Where does this come from?

The program is pretty simple:

```<code>public class Test {
    public static void main(String[] args) throws IOException {
        System.out.println("Hello world");
        System.in.read();
    }
}
</code>```

JVM details:

```<code>java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
</code>```

Ubuntu 16.04.

答:
Checking if tools load additional classes

I tried the following program:

```<code>package test;
public class MainSleep {
    public static void main(String[] args) throws InterruptedException {
        synchronized (MainSleep.class) {
            MainSleep.class.wait(5*1000);
        }
    }
}
</code>```

When I run it with:

```<code>"c:\Program Files\Java\jdk1.8.0_131\bin\java" \
  -verbose:class -cp target\classes test.MainSleep
</code>```

I get verbose class loading messages, then a 5 sec pause and then the shutdown does load even more classes:

```<code>...
[Loaded sun.misc.PerfCounter from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.misc.Perf$GetPerfAction from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.misc.Perf from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.misc.PerfCounter$CoreCounters from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.nio.ch.DirectBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.MappedByteBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.DirectByteBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.LongBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.DirectLongBufferU from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.PermissionCollection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.Permissions from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.net.URLConnection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.net.www.URLConnection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.net.www.protocol.file.FileURLConnection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.net.www.MessageHeader from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.io.FilePermission from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.io.FilePermission$1 from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.io.FilePermissionCollection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.AllPermission from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.UnresolvedPermission from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.BasicPermissionCollection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded test.MainSleep from file:/D:/ws/BIS65/test-java8/target/classes/]
[Loaded sun.launcher.LauncherHelper$FXHelper from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.lang.Class$MethodArray from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.lang.Void from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
...
[Loaded java.lang.Shutdown from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.lang.Shutdown$Lock from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
</code>```

So this would be the baseline. When I now use jstack or jmap on that file and check for verbose class loading messages I can see if it introduces new classes (not sure about instances of course).

With jstack -l and jstack, the following additional one class is loaded:

```<code>[Loaded java.lang.Class$MethodArray from
[Loaded java.lang.Void from
[Loaded java.util.concurrent.locks.AbstractOwnableSynchronizer ...
[Loaded java.lang.Shutdown from
[Loaded java.lang.Shutdown$Lock from
</code>```

With jstack -F or jstack -m no(!) additional class is loaded:

```<code>[Loaded java.lang.Class$MethodArray from
[Loaded java.lang.Void from
[Loaded java.lang.Shutdown from
[Loaded java.lang.Shutdown$Lock from
</code>```

None of jmap -clstat,-finalizerinfo,-heap, -histo or -histo:live loaded additional classes:

```<code>[Loaded java.lang.Class$MethodArray from
[Loaded java.lang.Void from
[Loaded java.lang.Shutdown from
[Loaded java.lang.Shutdown$Lock from
</code>```

The same is true for jmap -dump:format=b,file=ignore.hprof with and without the -F option as well as with and without the live flag.

Just for completeness, if I use jvisualvm or jconsole it will always trigger a lot of JMX class loads for thread, heap and application snapshots. Most likely because it always opens the dashboard for the process.

Exploring Heap Content

So now that we have established this I took a look at the jmap -dump:format=b (non-live, non-forced) heap dump with MAT, looking for the Fields you have been interested in:

The MAT unreachable objects histogram (which shows instances found in the heap but not connected to any GC root, which is basically all not-yet collected garbage) has 3038 objects, and the top 10:

```<code>Class Name                               | Objects | Shallow Heap
------------------------------------------------------------------
char[]                                   |   1.026 |      113.848
java.lang.String                         |     599 |       14.376
int[]                                    |     423 |        7.664
java.lang.Object[]                       |     220 |       14.192
java.lang.StringBuilder                  |     137 |        3.288
java.lang.reflect.Field                  |     115 |        8.280
java.lang.ProcessEnvironment$CheckedEntry|      66 |        1.056
java.io.File                             |      59 |        1.888
java.lang.Class                          |      32 |            0
java.lang.StringBuffer                   |      30 |          720
</code>```

There is currently no single live Field instance visible with MAT and only very limited of Class instances. This looks much like a .hprof or MAT problem: the Class instances seems to not show any of their fields in the heap dump. I think they should be softly(!) referenced by Class#reflectionData : SoftReference<ReflectionData<T>>, but I think this should be visible in the heap dump and not losing 115 fields. (There is no Class$ReflectionData in the live heap and 14 Class$ReflectionData in the unreachable histo. That can fit well with 115 Fields.

(I guess I will check back with Serviceability-dev@openjdk on that. This does not fit in a comment, so this is an incomplete answer but I intend to enhance it).

Body:
I was playing around with jmap and found that simple "Hello World" Java program creates thousands of objects. Here is truncated list of objects Oracle JVM update 131 creates on startup:

 num     #instances         #bytes  class name
----------------------------------------------
   1:           402        4903520  [I
   2:          1621         158344  [C
   3:           455          52056  java.lang.Class
   4:           194          49728  [B
   5:          1263          30312  java.lang.String
   6:           515          26088  [Ljava.lang.Object;
   7:           115           8280  java.lang.reflect.Field
   8:           258           4128  java.lang.Integer
   9:            94           3760  java.lang.ref.SoftReference
  10:           116           3712  java.util.Hashtable$Entry
  11:           126           3024  java.lang.StringBuilder
  12:             8           3008  java.lang.Thread
  13:            74           2576  [Ljava.lang.String;
  14:            61           1952  java.io.File
  15:            38           1824  sun.util.locale.LocaleObjectCache$CacheEntry
  16:            12           1760  [Ljava.util.Hashtable$Entry;
  17:            53           1696  java.util.concurrent.ConcurrentHashMap$Node
  18:            23           1472  java.net.URL
  19:            14           1120  [S
  20:             2           1064  [Ljava.lang.invoke.MethodHandle;
  21:             1           1040  [Ljava.lang.Integer;
  22:            26           1040  java.io.ObjectStreamField
  23:            12           1024  [Ljava.util.HashMap$Node;
  24:            30            960  java.util.HashMap$Node
  25:            20            800  sun.util.locale.BaseLocale$Key

I know that the JVM loads classes from JAR files and expect to see java.lang.Class, java.lang.String and [Ljava.lang.Object. 258 java.lang.Integer objects are clear tp me too: this is the Integer cache.

But java.lang.reflect.Field? Hashtable? Many StringBuilders? java.util.concurrent.ConcurrentHashMap? Where does this come from?

The program is pretty simple:

public class Test {
    public static void main(String[] args) throws IOException {
        System.out.println("Hello world");
        System.in.read();
    }
}

JVM details:

java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Ubuntu 16.04.

Body:
Checking if tools load additional classes

I tried the following program:

package test;
public class MainSleep {
    public static void main(String[] args) throws InterruptedException {
        synchronized (MainSleep.class) {
            MainSleep.class.wait(5*1000);
        }
    }
}

When I run it with:

"c:\Program Files\Java\jdk1.8.0_131\bin\java" \
  -verbose:class -cp target\classes test.MainSleep

I get verbose class loading messages, then a 5 sec pause and then the shutdown does load even more classes:

...
[Loaded sun.misc.PerfCounter from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.misc.Perf$GetPerfAction from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.misc.Perf from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.misc.PerfCounter$CoreCounters from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.nio.ch.DirectBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.MappedByteBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.DirectByteBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.LongBuffer from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.nio.DirectLongBufferU from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.PermissionCollection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.Permissions from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.net.URLConnection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.net.www.URLConnection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.net.www.protocol.file.FileURLConnection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded sun.net.www.MessageHeader from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.io.FilePermission from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.io.FilePermission$1 from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.io.FilePermissionCollection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.AllPermission from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.UnresolvedPermission from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.security.BasicPermissionCollection from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded test.MainSleep from file:/D:/ws/BIS65/test-java8/target/classes/]
[Loaded sun.launcher.LauncherHelper$FXHelper from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.lang.Class$MethodArray from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.lang.Void from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
...
[Loaded java.lang.Shutdown from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]
[Loaded java.lang.Shutdown$Lock from c:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar]

So this would be the baseline. When I now use jstack or jmap on that file and check for verbose class loading messages I can see if it introduces new classes (not sure about instances of course).

With jstack -l and jstack, the following additional one class is loaded:

[Loaded java.lang.Class$MethodArray from
[Loaded java.lang.Void from
[Loaded java.util.concurrent.locks.AbstractOwnableSynchronizer ...
[Loaded java.lang.Shutdown from
[Loaded java.lang.Shutdown$Lock from

With jstack -F or jstack -m no(!) additional class is loaded:

[Loaded java.lang.Class$MethodArray from
[Loaded java.lang.Void from
[Loaded java.lang.Shutdown from
[Loaded java.lang.Shutdown$Lock from

None of jmap -clstat,-finalizerinfo,-heap, -histo or -histo:live loaded additional classes:

[Loaded java.lang.Class$MethodArray from
[Loaded java.lang.Void from
[Loaded java.lang.Shutdown from
[Loaded java.lang.Shutdown$Lock from

The same is true for jmap -dump:format=b,file=ignore.hprof with and without the -F option as well as with and without the live flag.

Just for completeness, if I use jvisualvm or jconsole it will always trigger a lot of JMX class loads for thread, heap and application snapshots. Most likely because it always opens the dashboard for the process.

Exploring Heap Content

So now that we have established this I took a look at the jmap -dump:format=b (non-live, non-forced) heap dump with MAT, looking for the Fields you have been interested in:

The MAT unreachable objects histogram (which shows instances found in the heap but not connected to any GC root, which is basically all not-yet collected garbage) has 3038 objects, and the top 10:

Class Name                               | Objects | Shallow Heap
------------------------------------------------------------------
char[]                                   |   1.026 |      113.848
java.lang.String                         |     599 |       14.376
int[]                                    |     423 |        7.664
java.lang.Object[]                       |     220 |       14.192
java.lang.StringBuilder                  |     137 |        3.288
java.lang.reflect.Field                  |     115 |        8.280
java.lang.ProcessEnvironment$CheckedEntry|      66 |        1.056
java.io.File                             |      59 |        1.888
java.lang.Class                          |      32 |            0
java.lang.StringBuffer                   |      30 |          720

There is currently no single live Field instance visible with MAT and only very limited of Class instances. This looks much like a .hprof or MAT problem: the Class instances seems to not show any of their fields in the heap dump. I think they should be softly(!) referenced by Class#reflectionData : SoftReference<ReflectionData<T>>, but I think this should be visible in the heap dump and not losing 115 fields. (There is no Class$ReflectionData in the live heap and 14 Class$ReflectionData in the unreachable histo. That can fit well with 115 Fields.

(I guess I will check back with Serviceability-dev@openjdk on that. This does not fit in a comment, so this is an incomplete answer but I intend to enhance it).


问:
Lots of confusion about declaration files
Typescript does not have support for many WebGL 2 functions and interfaces, like createVertexArray(). Because of this, I want to write a declaration file that wraps the function so that the compiler won't throw a fit. To do this I have written a javascript file that contains the unsupported functions:

```<code>function createVertexArray(glContext) {
    return glContext.createVertexArray();
}
// a bunch more
</code>```

I now need to create a Typescript declaration file for these functions. As I understand it, when you ask typescript to load a module, it looks at the directory for an index.d.ts file. There you have to define the functions and interfaces used in your javascript file. This is what I have so far:

```<code>declare module Webgl2 {
    export interface WebGLVertexArrayObject {}
    export function createVertexArray(glContext: WebGLRenderingContext):WebGLVertexArrayObject;
    export function deleteVertexArray(glContext: WebGLRenderingContext, vertexArray: WebGLVertexArrayObject):void;
    export function isVertexArray(glContext: WebGLRenderingContext, vertexArray: WebGLVertexArrayObject):boolean;
    export function bindVertexArray(glContext: WebGLRenderingContext, vertexArray: WebGLVertexArrayObject):void;
}

export = Webgl2;
</code>```

However, I need help with the following:

How do I load the module in the rest of my typescript application?

Is the javascript file loaded automatically or do I have to do that manually when the page is served?

In my javascript file do I have to declare the functions as the module exports?

In my javascript file do I have to declare the interface that createVertexArray() returns?

I have put both files on pastebin here.

答:
Somebody has been working on this for some time already. You can find the WebGL2.d.ts file here.

Then you can import using the "files" field in the tsconfig.json file as shown here.

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": true,
        "strictNullChecks": false,
        "types": [],
        "forceConsistentCasingInFileNames": true,
        "lib": ["ES2015", "ES2017.SharedMemory", "DOM"]
    },
    "files": [
        "Misc.d.ts",
        "WebGL2.d.ts"
    ]
}
</code>```

Body:
Typescript does not have support for many WebGL 2 functions and interfaces, like createVertexArray(). Because of this, I want to write a declaration file that wraps the function so that the compiler won't throw a fit. To do this I have written a javascript file that contains the unsupported functions:

function createVertexArray(glContext) {
    return glContext.createVertexArray();
}
// a bunch more

I now need to create a Typescript declaration file for these functions. As I understand it, when you ask typescript to load a module, it looks at the directory for an index.d.ts file. There you have to define the functions and interfaces used in your javascript file. This is what I have so far:

declare module Webgl2 {
    export interface WebGLVertexArrayObject {}
    export function createVertexArray(glContext: WebGLRenderingContext):WebGLVertexArrayObject;
    export function deleteVertexArray(glContext: WebGLRenderingContext, vertexArray: WebGLVertexArrayObject):void;
    export function isVertexArray(glContext: WebGLRenderingContext, vertexArray: WebGLVertexArrayObject):boolean;
    export function bindVertexArray(glContext: WebGLRenderingContext, vertexArray: WebGLVertexArrayObject):void;
}

export = Webgl2;

However, I need help with the following:

How do I load the module in the rest of my typescript application?

Is the javascript file loaded automatically or do I have to do that manually when the page is served?

In my javascript file do I have to declare the functions as the module exports?

In my javascript file do I have to declare the interface that createVertexArray() returns?

I have put both files on pastebin here.

Body:
Somebody has been working on this for some time already. You can find the WebGL2.d.ts file here.

Then you can import using the "files" field in the tsconfig.json file as shown here.

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": true,
        "strictNullChecks": false,
        "types": [],
        "forceConsistentCasingInFileNames": true,
        "lib": ["ES2015", "ES2017.SharedMemory", "DOM"]
    },
    "files": [
        "Misc.d.ts",
        "WebGL2.d.ts"
    ]
}


问:
Retrieving index from multi-index based on column values in Pandas
Say I have a table as such:

```<code>  Attr   |  Foo    |  Bar
Name|Val | 1  | 2  | 3  | 4
-----------------------------
OFO |1   | F  | T  | F  | F
    |2   | T  | F  | F  | T
-----------------------------
ARB |5   | T  | T  | F  | F
    |6   | F  | F  | F  | T
</code>```

Where my rows are controlled by an index with level 0 = {OFO, ARB} and level 1 = {1,2,5,6} and columns are level 0 = {Foo,Bar} and level 1 = {1,2,3,4} I want to be able to pull the respective row and column index from each T entry, so one return would be:

```<code>((Foo,1),(OFO,1))
</code>```

I'm struggling to come up with a good solution.

答:
This was my solution:

```<code>def getIndex(table):
    mask = (pd.notnull(table))
    i, j = np.where(mask)
    return list(zip(table.index[i],table.columns[j]))
</code>```

With significant help from this question:
Get the row and column labels for selected values in a Pandas dataframe

Body:
Say I have a table as such:

  Attr   |  Foo    |  Bar
Name|Val | 1  | 2  | 3  | 4
-----------------------------
OFO |1   | F  | T  | F  | F
    |2   | T  | F  | F  | T
-----------------------------
ARB |5   | T  | T  | F  | F
    |6   | F  | F  | F  | T

Where my rows are controlled by an index with level 0 = {OFO, ARB} and level 1 = {1,2,5,6} and columns are level 0 = {Foo,Bar} and level 1 = {1,2,3,4} I want to be able to pull the respective row and column index from each T entry, so one return would be:

((Foo,1),(OFO,1))

I'm struggling to come up with a good solution.

Body:
This was my solution:

def getIndex(table):
    mask = (pd.notnull(table))
    i, j = np.where(mask)
    return list(zip(table.index[i],table.columns[j]))

With significant help from this question:
Get the row and column labels for selected values in a Pandas dataframe


答:
Can you be more specific about what you're trying do to?

If you just want another vector,

```<code>Combined <- c(Latitude, Longitude)
</code>```

will work. If you're working in a data.frame, you probably are trying to do something that shouldn't be done, since data.frame values need to be atomic instances, not vectors.

Title: Combine two columns into a new vector in R

Body:
I have the following data:

Longitude  Latitude

-84.68934  59.22615
-84.52940  58.79971
-84.68617  58.97750
-84.88737  59.08489
-84.71777  59.14207
-84.71777  59.14207

I'd like to add a third column:

Longitude Latitude Combined

-84.68934 59.22615 c(-84.68934,59.22615)

-84.52940 58.79971 c(-84.52940,58.7997)

*Edit - Pasting won't work (or at least I think it won't) as I need the result to be a vector.

Body:
Can you be more specific about what you're trying do to?

If you just want another vector,

Combined <- c(Latitude, Longitude)

will work. If you're working in a data.frame, you probably are trying to do something that shouldn't be done, since data.frame values need to be atomic instances, not vectors.


问:
Removing padding on columns makes horizontal scrollbar
I wanted to remove the padding from the bootstrap grid column classes.

So I did

```<code>.col-x {
    padding: 0;
}
</code>```

But this is kind of breaking the whole layout because a horizontal scrollbar appears.

I've created a pen for this so you can see it.

What is causing the horizontal scrollbar and how to fix it?

答:
You have .row elements nested in your columns. .row has a negative margin and always needs to be wrapped in a .container, which has padding that the negative margin offsets. The padding on your columns were doing that. I would just wrap all of your rows in .container-fluid

Rows are placed within a fixed or full-width Container (.container or .container-fluid, respectively) for proper alignment.

/* removing padding on columns makes horizontal scrollbar */
.column {
    padding: 0;
}

.column {
    min-height: 100vh;
    border-right: 1px solid #ccc;
}
.column-header {
    border-bottom: 1px solid #ddd;
}
.column.sidebar {
    position: fixed;
    top: 0; left: 0;
    border-right: 1px solid #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">

    <div class="col-2 column sidebar">
      fixed side
    </div>

    <div class="col-6 offset-2 column content">
      <div class="column-header mb-5">
        <div class="container-fluid">
          <div class="row">
            <div class="col-8 pt-4 pb-4 pl-5 pr-5">
              Title
            </div>
            <div class="col-4 pt-4 pb-4 pl-5 pr-5 text-right">
              Right
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-4 column content">
      <div class="column-header mb-5">
        <div class="container-fluid">
          <div class="row">
            <div class="col-8 pt-4 pb-4 pl-5 pr-5">
              Title
            </div>
            <div class="col-4 pt-4 pb-4 pl-5 pr-5 text-right">
              Right
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</div></code>```

Body:
I wanted to remove the padding from the bootstrap grid column classes.

So I did

.col-x {
    padding: 0;
}

But this is kind of breaking the whole layout because a horizontal scrollbar appears.

I've created a pen for this so you can see it.

What is causing the horizontal scrollbar and how to fix it?

Body:
You have .row elements nested in your columns. .row has a negative margin and always needs to be wrapped in a .container, which has padding that the negative margin offsets. The padding on your columns were doing that. I would just wrap all of your rows in .container-fluid

Rows are placed within a fixed or full-width Container (.container or .container-fluid, respectively) for proper alignment.

/* removing padding on columns makes horizontal scrollbar */
.column {
    padding: 0;
}

.column {
    min-height: 100vh;
    border-right: 1px solid #ccc;
}
.column-header {
    border-bottom: 1px solid #ddd;
}
.column.sidebar {
    position: fixed;
    top: 0; left: 0;
    border-right: 1px solid #ccc;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">

    <div class="col-2 column sidebar">
      fixed side
    </div>

    <div class="col-6 offset-2 column content">
      <div class="column-header mb-5">
        <div class="container-fluid">
          <div class="row">
            <div class="col-8 pt-4 pb-4 pl-5 pr-5">
              Title
            </div>
            <div class="col-4 pt-4 pb-4 pl-5 pr-5 text-right">
              Right
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-4 column content">
      <div class="column-header mb-5">
        <div class="container-fluid">
          <div class="row">
            <div class="col-8 pt-4 pb-4 pl-5 pr-5">
              Title
            </div>
            <div class="col-4 pt-4 pb-4 pl-5 pr-5 text-right">
              Right
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</div>


问:
How to apply some changes to each element in List<List<>> structure using Java 8 approach
I have some structure like  List<List<Double>> listOfDoubles I need to transform it to List<List<Integer>> listOfInteger. I wrote code without using Java 8. And it looks like:

```<code>List<List<Integer>> integerList = new ArrayList<>();
for (int i = 0; i < doubleList.size(); i++) {
    for (Double doubleValue : doubleList.get(i)) {
        integerList.get(i).add(doubleValue.intValue());
    }
}
</code>```

I tried to replace second for by foreach but can't because i should be final. How to write this code using Java 8 approach?

答:
We can get rid of the boilerplate code collect(Collectors.toList()) with StreamEx:

```<code>StreamEx.of(listOfDoubles)
        .map(e -> StreamEx.of(e).map(Double::intValue).toList())
        .toList();
</code>```

To me, the readability and maintainability of above code is much better the cod e with JDK stream API:

```<code>List<List<Integer>> integerList =
    doubleList.stream()
          .map(l -> l.stream()
                     .map(Double::intValue)
                     .collect(Collectors.toList()))
          .collect(Collectors.toList());
</code>```

Body:
I have some structure like  List<List<Double>> listOfDoubles I need to transform it to List<List<Integer>> listOfInteger. I wrote code without using Java 8. And it looks like:

List<List<Integer>> integerList = new ArrayList<>();
for (int i = 0; i < doubleList.size(); i++) {
    for (Double doubleValue : doubleList.get(i)) {
        integerList.get(i).add(doubleValue.intValue());
    }
}

I tried to replace second for by foreach but can't because i should be final. How to write this code using Java 8 approach?

Body:
We can get rid of the boilerplate code collect(Collectors.toList()) with StreamEx:

StreamEx.of(listOfDoubles)
        .map(e -> StreamEx.of(e).map(Double::intValue).toList())
        .toList();

To me, the readability and maintainability of above code is much better the cod e with JDK stream API:

List<List<Integer>> integerList =
    doubleList.stream()
          .map(l -> l.stream()
                     .map(Double::intValue)
                     .collect(Collectors.toList()))
          .collect(Collectors.toList());


问:
Sampling a list with linq
I need a helper method for adding axis labels to a chart. I don't want to add a label at every point along the axis that has values in the chart because that would get too busy. So I need to extract samples at regular intervals. So far I've come up with the following method which meets the requirements but I think there must be a neater way of accomplishing this with Linq. Can anyone think of how this could be made more concise (n represents the total number of samples I want back)?</p>

```<code>public static List<T> Sample<T>(this List<T> list, int n)
{
  var samples = new List<T>();
  var divisor = list.Count/n;
  for (var i = 0; i < list.Count; i++)
    if (samples.Count == i/divisor)
      samples.Add(list[i]);
  return samples;
}
</code>```

答:
Hm, what about:

```<code>return Enumerable.Range(0,n).Select(i=>list[(i*list.Count)/(n-1)]);
</code>```

Not that it really matters, but this gives you a slightly better complexity (O(n) instead of O(list.Count)

ContentLicense: CC BY-SA 2.5

Title: Sampling a list with linq

Body:
I need a helper method for adding axis labels to a chart. I don't want to add a label at every point along the axis that has values in the chart because that would get too busy. So I need to extract samples at regular intervals. So far I've come up with the following method which meets the requirements but I think there must be a neater way of accomplishing this with Linq. Can anyone think of how this could be made more concise (n represents the total number of samples I want back)?

public static List<T> Sample<T>(this List<T> list, int n)
{
  var samples = new List<T>();
  var divisor = list.Count/n;
  for (var i = 0; i < list.Count; i++)
    if (samples.Count == i/divisor)
      samples.Add(list[i]);
  return samples;
}

Body:
Hm, what about:

return Enumerable.Range(0,n).Select(i=>list[(i*list.Count)/(n-1)]);

Not that it really matters, but this gives you a slightly better complexity (O(n) instead of O(list.Count)


问:
"amount must be a Numeric" Rails Error
I'm using the active_shipping gem on my rails app and am getting a very strange error reading:

```<code>amount must be a Numeric
</code>```

The error is being called on my shipping method:

```<code>def shipping
    @user = current_user
    @products = current_order.order_items.all
    @order = current_order

    packages =  []
    @products.each do |thing|
      packages << ActiveShipping::Package.new( thing.product.weight * 16,  <<<<<<<<<<ERROR CALLED ON THIS LINE
      [thing.product.box_length, thing.product.box_width, thing.product.box_depth],
      units: :imperial)
    end ## each do

    origin = ActiveShipping::Location.new( country: 'US', state: 'CO', city: 'Sedalia', zip: '80135')

    if @user.country == 'US'
      destination = ActiveShipping::Location.new( country: @user.country, state: @user.state, city: @user.city, zip: @user.zip)
    else
      destination = ActiveShipping::Location.new( country: @user.country, province: @user.state, city: @user.city, postal_code: @user.zip)
    end # if/else for country

    ups = ActiveShipping::UPS.new(login: 'lizbayardelle', password: 'UPSpassw0rd', key: '3D287D7B39D0D398')
    ups_response = ups.find_rates(origin, destination, packages)
    @ups_rates = ups_response.rates.sort_by(&:price).collect {|rate| [rate.service_name, rate.price]}

    usps = ActiveShipping::USPS.new(login: '380LINCH6422')
    usps_response = usps.find_rates(origin, destination, packages)
    @usps_rates = usps_response.rates.sort_by(&:price).collect {|rate| [rate.service_name, rate.price]}
  end
</code>```

The value for the product weight is in the seeds.rb file:

```<code>Product.delete_all
Product.create! id: 1, name: "Rule #23 Tee Shirt (Small)", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Size Small. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 2, name: "Rule #23 Tee Shirt (Medium)", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Size Medium. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 3, name: "Rule #23 Tee Shirt (Large)", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Size Large. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 4, name: "Rule #23 Tee Shirt (XL)", weight: 1, box_width: 12, box_length: 14, box_depth: 3, price: 32.00, short_description: "Size XL. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 5, name: "Grill Glove", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Protect your manly mitts from the fiery dangers of the grill.", active: true
Product.create! id: 6, name: "BBQ Apron", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Standard grilling apron with three pockets for all your necessary tools.  You get to add the grease marks and stains from the marinade of your choosing.", active: true
</code>```

Can anyone see what's going on here?  Google/Stack Overflow don't seem to have heard of this error, which is worrisome...

答: I ended up adding .to_i to each thing and it made it work for some reason.</p>

Title: "amount must be a Numeric" Rails Error

Body:
I'm using the active_shipping gem on my rails app and am getting a very strange error reading:

amount must be a Numeric

The error is being called on my shipping method:

def shipping
    @user = current_user
    @products = current_order.order_items.all
    @order = current_order

    packages =  []
    @products.each do |thing|
      packages << ActiveShipping::Package.new( thing.product.weight * 16,  <<<<<<<<<<ERROR CALLED ON THIS LINE
      [thing.product.box_length, thing.product.box_width, thing.product.box_depth],
      units: :imperial)
    end ## each do

    origin = ActiveShipping::Location.new( country: 'US', state: 'CO', city: 'Sedalia', zip: '80135')

    if @user.country == 'US'
      destination = ActiveShipping::Location.new( country: @user.country, state: @user.state, city: @user.city, zip: @user.zip)
    else
      destination = ActiveShipping::Location.new( country: @user.country, province: @user.state, city: @user.city, postal_code: @user.zip)
    end # if/else for country

    ups = ActiveShipping::UPS.new(login: 'lizbayardelle', password: 'UPSpassw0rd', key: '3D287D7B39D0D398')
    ups_response = ups.find_rates(origin, destination, packages)
    @ups_rates = ups_response.rates.sort_by(&:price).collect {|rate| [rate.service_name, rate.price]}

    usps = ActiveShipping::USPS.new(login: '380LINCH6422')
    usps_response = usps.find_rates(origin, destination, packages)
    @usps_rates = usps_response.rates.sort_by(&:price).collect {|rate| [rate.service_name, rate.price]}
  end

The value for the product weight is in the seeds.rb file:

Product.delete_all
Product.create! id: 1, name: "Rule #23 Tee Shirt (Small)", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Size Small. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 2, name: "Rule #23 Tee Shirt (Medium)", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Size Medium. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 3, name: "Rule #23 Tee Shirt (Large)", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Size Large. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 4, name: "Rule #23 Tee Shirt (XL)", weight: 1, box_width: 12, box_length: 14, box_depth: 3, price: 32.00, short_description: "Size XL. Spread the word. These tee shirts not only have the Manly Art crest, but they also have a man rule on the back to remind any passers-by that may have forgotten.", active: true
Product.create! id: 5, name: "Grill Glove", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Protect your manly mitts from the fiery dangers of the grill.", active: true
Product.create! id: 6, name: "BBQ Apron", weight: 1, box_width: 6, box_length: 9, box_depth: 2, price: 32.00, short_description: "Standard grilling apron with three pockets for all your necessary tools.  You get to add the grease marks and stains from the marinade of your choosing.", active: true

Can anyone see what's going on here?  Google/Stack Overflow don't seem to have heard of this error, which is worrisome...


问:
How to add external library to CMakeLists?
Normal compilation (works fine):

```<code>g++ DBHandler.cpp Functions.cpp Main.cpp -I/usr/local/include -L/usr/local/lib -lconfig++ -lpqxx -lpq -o dbhandler
</code>```

It`s possible to run:

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

CMakeLists.txt (standard):

```<code>cmake_minimum_required(VERSION 2.8.9)
project(DBHandler)
include_directories(include)
file(GLOB SOURCES "src/*.cpp")
target_link_libraries(dbhandler config++ pqxx pq)
add_executable(dbhandler ${SOURCES})
</code>```

How to change CMakeLists.txt and add:

```<code>-I/usr/local/include -L/usr/local/lib -lconfig++ -lpqxx -lpq
</code>```

to compile program using cmake?

答:
The correct solution is to use the CMake package PkgConfig to use pkg_search_module

Your file will become:

```<code>cmake_minimum_required(VERSION 2.8.9)
project(DBHandler)

find_package(PkgConfig REQUIRED)

pkg_search_module(CONFIGPP REQUIRED config++)
pkg_search_module(PQ REQUIRED pq)
pkg_search_module(PQXX REQUIRED pqxx)

include_directories(include ${CONFIGPP_INCLUDE_DIRS} ${PQ_INCLUDE_DIRS} ${PQXX_INCLUDE_DIRS})
file(GLOB SOURCES "src/*.cpp")
target_link_libraries(dbhandler ${CONFIGPP_LIBRARIES} ${PQ_LIBRARIES} ${PQXX_LIBRARIES})
add_executable(dbhandler ${SOURCES})
</code>```

Body:
Normal compilation (works fine):

g++ DBHandler.cpp Functions.cpp Main.cpp -I/usr/local/include -L/usr/local/lib -lconfig++ -lpqxx -lpq -o dbhandler

It`s possible to run:

./dbhandler

CMakeLists.txt (standard):

cmake_minimum_required(VERSION 2.8.9)
project(DBHandler)
include_directories(include)
file(GLOB SOURCES "src/*.cpp")
target_link_libraries(dbhandler config++ pqxx pq)
add_executable(dbhandler ${SOURCES})

How to change CMakeLists.txt and add:

-I/usr/local/include -L/usr/local/lib -lconfig++ -lpqxx -lpq

to compile program using cmake?

Body:
The correct solution is to use the CMake package PkgConfig to use pkg_search_module

Your file will become:

cmake_minimum_required(VERSION 2.8.9)
project(DBHandler)

find_package(PkgConfig REQUIRED)

pkg_search_module(CONFIGPP REQUIRED config++)
pkg_search_module(PQ REQUIRED pq)
pkg_search_module(PQXX REQUIRED pqxx)

include_directories(include ${CONFIGPP_INCLUDE_DIRS} ${PQ_INCLUDE_DIRS} ${PQXX_INCLUDE_DIRS})
file(GLOB SOURCES "src/*.cpp")
target_link_libraries(dbhandler ${CONFIGPP_LIBRARIES} ${PQ_LIBRARIES} ${PQXX_LIBRARIES})
add_executable(dbhandler ${SOURCES})


问:
Swift three double quotes
I am new to Swift. The docuentation says: Use three double quotes (""") for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quote. For example:

```<code>let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
"""
</code>```

However, I copied this example and pasted in my xcode playground and it shows an error:

```<code>Playground execution failed: error: SwiftBasics.playground:9:19: error:
unterminated string literal
let quotation = """
</code>```

What am I doing wrong ?

答: I assume you are using Xcode 8 or earlier. Multi line String Literals have been implemented in Swift 4. You can only use them with Xcode 9 Beta or by including the open source Swift 4 toolchain in your Xcode at the moment.</p>

Title: Swift three double quotes

Body:
I am new to Swift. The docuentation says: Use three double quotes (""") for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quote. For example:

let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
"""

However, I copied this example and pasted in my xcode playground and it shows an error:

Playground execution failed: error: SwiftBasics.playground:9:19: error:
unterminated string literal
let quotation = """

What am I doing wrong ?


问:
How can I send unknown list of arguments to a python decorator?
I have created a python decorator as shown below. I want this decorator to accept an unknown list of arguments. But the code below doesn't work.

```<code>#!/usr/bin/env python

from functools import wraps

def my_decorator(decorated_function, **kwargs):

    print "kwargs = {}".format(kwargs)
    @wraps(decorated_function)
    def inner_function(*args, **kwargs):
        print "Hello world"
        return decorated_function(*args, **kwargs)
    return inner_function

@my_decorator(arg_1="Yolo", arg2="Bolo")
def my_func():
     print "Woo Hoo!"

my_func()
</code>```

When I run it, I get this error:

```<code> File "./decorator_test.py", line 14, in <module>
     @my_decorator(arg_1="Yolo", arg2="Bolo")
 TypeError: my_decorator() takes exactly 1 argument (0 given)
</code>```

Why is the **kwargs not accepting the multiple arguments I'm sending into the decorator? How can I fix it?

答:
Essentially, when you have a decorator that accepts arguments, you're kind of calling it twice, once with the keyword arguments, and then again with just the function to be decorated.

Before the @deco syntax, you would decorate a function just by passing it into the decorator function

```<code>func = deco(func)
</code>```

And if you wanted to include other keyword arguments, you could just pass them in at the same time

```<code>func = deco(func, arg=True, arg2=5)
</code>```

But the @deco syntax doesn't allow that, it works more like this, so you're calling a function returned by the decorator function.

```<code>func = deco(arg=True, arg2=5)(func)
</code>```

To do this with the @deco syntax, you would create a decorator that tests to see whether it was called with just a function (the decoration part), or whether it was called with keyword arguments (which sets up the decorator to be passed a function).

```<code>def deco_with_kwargs(func=None, **kwargs):

    def deco(func_):

        def wrapped_func(*fargs, **fkwargs):
            print kwargs
            return func_(*fargs, **fkwargs)
        return wrapped_func

    if func:
        return deco(func)
    else:
        return deco
</code>```

You could use it like this without any keyword arguments.

```<code>@deco_with_args
def my_func():
    return 1
</code>```

Or you could call it like this with keyword arguments.  In this case, you're actually calling the decorator function, which returns another decorator function, which is then called to actually decorate the function.

```<code>@deco_with_args(test=True)
def my_func():
    return 1
</code>```

Body:
I have created a python decorator as shown below. I want this decorator to accept an unknown list of arguments. But the code below doesn't work.

#!/usr/bin/env python

from functools import wraps

def my_decorator(decorated_function, **kwargs):

    print "kwargs = {}".format(kwargs)
    @wraps(decorated_function)
    def inner_function(*args, **kwargs):
        print "Hello world"
        return decorated_function(*args, **kwargs)
    return inner_function

@my_decorator(arg_1="Yolo", arg2="Bolo")
def my_func():
     print "Woo Hoo!"

my_func()

When I run it, I get this error:

 File "./decorator_test.py", line 14, in <module>
     @my_decorator(arg_1="Yolo", arg2="Bolo")
 TypeError: my_decorator() takes exactly 1 argument (0 given)

Why is the **kwargs not accepting the multiple arguments I'm sending into the decorator? How can I fix it?

Body:
Essentially, when you have a decorator that accepts arguments, you're kind of calling it twice, once with the keyword arguments, and then again with just the function to be decorated.

Before the @deco syntax, you would decorate a function just by passing it into the decorator function

func = deco(func)

And if you wanted to include other keyword arguments, you could just pass them in at the same time

func = deco(func, arg=True, arg2=5)

But the @deco syntax doesn't allow that, it works more like this, so you're calling a function returned by the decorator function.

func = deco(arg=True, arg2=5)(func)

To do this with the @deco syntax, you would create a decorator that tests to see whether it was called with just a function (the decoration part), or whether it was called with keyword arguments (which sets up the decorator to be passed a function).

def deco_with_kwargs(func=None, **kwargs):

    def deco(func_):

        def wrapped_func(*fargs, **fkwargs):
            print kwargs
            return func_(*fargs, **fkwargs)
        return wrapped_func

    if func:
        return deco(func)
    else:
        return deco

You could use it like this without any keyword arguments.

@deco_with_args
def my_func():
    return 1

Or you could call it like this with keyword arguments.  In this case, you're actually calling the decorator function, which returns another decorator function, which is then called to actually decorate the function.

@deco_with_args(test=True)
def my_func():
    return 1


问:
Removing all but specific string sequence
I have a list of strings. Each string contains a specific sequence of characters I need - there are three or four exact sequences I'm looking for - and the rest contains unpredictable data that needs to get eliminated from the string. ie:

```<code>sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']
goalList = ['sequenceB', 'sequenceA', 'sequenceC', '']
</code>```

I can use either sub or .replace to remove specific characters, but this is the inversion: I need to remove everything BUT specific strings, and in the case of list elements without an instance of a specific sequence I still need to keep the element so the list stays in order. I'm still new to regex - is there a way to do this I haven't found yet?

答:
If you like a magic one-liner.</p>

```<code>>>>[ ''.join([x if x in y else '' for x in sequences]) for y in bigList]

['sequenceB', 'sequenceA', 'sequenceC', '']
</code>```

Body:
I have a list of strings. Each string contains a specific sequence of characters I need - there are three or four exact sequences I'm looking for - and the rest contains unpredictable data that needs to get eliminated from the string. ie:

sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']
goalList = ['sequenceB', 'sequenceA', 'sequenceC', '']

I can use either sub or .replace to remove specific characters, but this is the inversion: I need to remove everything BUT specific strings, and in the case of list elements without an instance of a specific sequence I still need to keep the element so the list stays in order. I'm still new to regex - is there a way to do this I haven't found yet?

Body:
If you like a magic one-liner.

>>>[ ''.join([x if x in y else '' for x in sequences]) for y in bigList]

['sequenceB', 'sequenceA', 'sequenceC', '']