Create a random subsample by ID and with a certain factor distribution in R

Question: I am working with R and  have the following dataset which consists of sentences taken out of books and contains data about the book id, their cover colour (colour), and a sentence ID which is matched with the corresponding book.
My dataset
    Book ID| sentence ID| Colour      | Sentences
    1      | 1          | Blue        | Text goes here
    1      | 2          | Blue        | Text goes here
    1      | 3          | Blue        | Text goes here
    2      | 4          | Red         | Text goes here
    2      | 5          | Red         | Text goes here
    3      | 6          | Green       | Text goes here
    4      | 7          | Orange      | Text goes here
    4      | 8          | Orange      | Text goes here
    4      | 9          | Orange      | Text goes here
    4      | 10         | Orange      | Text goes here
    4      | 11         | Orange      | Text goes here
    5      | 12         | Blue        | Text goes here
    5      | 13         | Blue        | Text goes here
    6      | 14         | Red         | Text goes here
    6      | 15         | Red         | Text goes here
    .

I would like to take four randomized subsamples (each containing 25% of the original data) with following conditions:
 1) the distribution of book-colours should remain the same as in the original dataset. If there were 10% blue books, this should also be reflected in the subsamples
  2) the subsample should not be taken/split by number of rows (which is the sentence ID) but by "Book ID". This means if Book ID 4 is sampled, then all sentences 7,8,9,10,11 should be in the sample dataset.
  3) Also, each Book ID should only be in one of the 4 sub samples - this means if I decided to merge all 4 subsamples, I want to end up with the original dataset again.
What would be the best solution to split my dataset in the way described above?
Comment: How large is your dataset? In regards to your first specification, you want to reflect the distribution of color in each sample. If you want a truly randomized sample, you would not adjust for this, instead relying on a large enough sample size that your subsample would represent the rest of your samples (or at least **sufficiently** represent, depending on your hypothesis and statistical test).
Comment: Perhaps this helps you: https://stats.stackexchange.com/a/326015/282453
Comment: Maybe I've not understood well, but if the proportions of colors should be equal in each sample and in the full dataset (1), but you do not want repetitions in samples(3), if you put the green book (`book ID` == 3) in the first sample (for example), what do you expect about it in the remaining three samples?
Answer: Here the short version:
library(tidyverse)

df <- tribble(
    ~Book_ID, ~sentence_ID, ~Colour, ~Sentences
    ,1      , 1, "Blue", "Text goes here"
    ,1      , 2, "Blue", "Text goes here"
    ,1      , 3, "Blue", "Text goes here"
    ,2      , 4, "Red", "Text goes here"
    ,2      , 5, "Red", "Text goes here"
    ,3      , 6, "Green", "Text goes here"
    ,4      , 7, "Orange", "Text goes here"
    ,4      , 8, "Orange", "Text goes here"
    ,4      , 9, "Orange", "Text goes here"
    ,4      , 10, "Orange", "Text goes here"
    ,4      , 11, "Orange", "Text goes here"
    ,5      , 12, "Blue", "Text goes here"
    ,5      , 13, "Blue", "Text goes here"
    ,6      , 14, "Red", "Text goes here"
    ,6      , 15, "Red", "Text goes here"
)

df %>%
    left_join(
        df %>%
            distinct(Book_ID, Colour) %>%
            group_by(Colour) %>%
            mutate(sub_sample = sample.int(4, size = n(), replace = TRUE))
        , by = c("Book_ID", "Colour"))

This will give you:
# A tibble: 15 x 5
   Book_ID sentence_ID Colour Sentences        sub_sample
     <dbl>       <dbl> <chr>  <chr>                 <int>
 1       1           1 Blue   "Text goes here"          3
 2       1           2 Blue   "Text goes here"          3
 3       1           3 Blue   "Text goes here"          3
 4       2           4 Red    "Text goes here"          1
 5       2           5 Red    "Text goes here"          1
 6       3           6 Green  "Text goes here"          1
 7       4           7 Orange "Text goes here"          2
 8       4           8 Orange "Text goes here"          2
 9       4           9 Orange "Text goes here"          2
10       4          10 Orange "Text goes here"          2
11       4          11 Orange "Text goes here"          2
12       5          12 Blue   "Text goes here"          2
13       5          13 Blue   "Text goes here"          2
14       6          14 Red    "Text goes here"          3
15       6          15 Red    "Text goes here"          3

And a short explanation of the code:
Let's start with the nested part
# take the dataframe
df %>%
    # ...and extract the distinct combinations of book and colour
    distinct(Book_ID, Colour) %>%
    # and now for each colour...
    group_by(Colour) %>%
    # ...provide random numbers from 1 to 4
    mutate(sub_sample = sample.int(4, size = n(), replace = TRUE))

Grouping by colour ensures that you have the same distribution of colours in each sample.
The result of this is now left_joined to the original dataframe on the two columns we "distincted" before - which ensures that there can be no duplicates.

One addition
To have the same colour distribution in the subsamples you of course need a sufficient number of books for each colour. So, for example, only 20 different books in green is guaranteed to be differently distributed. In that case you would probably want to "group" colours for the sampling. However, that's a statistics question and clearly beyond the scope of a programming forum.
Answer: This should work. Books are grouped by color, and then a number from 1:4 is drawn from a pool that has length: next multiple of 4, to ensure equal distribution. The data frame is then split by sample number.
library(readr)
library(dplyr)
library(tidyr)

books <- read_delim(
'Book ID| sentence ID| Colour      | Sentences
    1      | 1          | Blue        | Text goes here
    1      | 2          | Blue        | Text goes here
    1      | 3          | Blue        | Text goes here
    2      | 4          | Red         | Text goes here
    2      | 5          | Red         | Text goes here
    3      | 6          | Green       | Text goes here
    4      | 7          | Orange      | Text goes here
    4      | 8          | Orange      | Text goes here
    4      | 9          | Orange      | Text goes here
    4      | 10         | Orange      | Text goes here
    4      | 11         | Orange      | Text goes here
    5      | 12         | Blue        | Text goes here
    5      | 13         | Blue        | Text goes here
    6      | 14         | Red         | Text goes here
    6      | 15         | Red         | Text goes here',
'|', trim_ws = TRUE)

books %>%
  # sampling is done on a book ID level. We group by book
  # and nest the sentences, to get only one row per book.
  group_by(`Book ID`) %>%
  nest(book_data = c(`sentence ID`, Sentences)) %>%

  # We want to split colours evenly. We therefore draw a sample number from 1:4
  # for each group of colours. To ensure an even split, we draw from a
  # vector that is a repeat of 1:4 until it has a lenght, that is the
  # first multiple of 4, that is >= the number of colours in a group.
  group_by(Colour) %>%
  mutate(sample = sample(rep_len(1:4, (n() + 3) %/% 4 * 4 ), n(), replace = F)) %>%

  # Unnest the sentences again.
  unnest(book_data) %>%

  # Split the data frame into lists by the sample number.
  split(.$sample)

$`1`
# A tibble: 4 x 5
# Groups:   Colour [2]
  `Book ID` Colour `sentence ID` Sentences      sample
      <dbl> <chr>          <dbl> <chr>           <int>
1         5 Blue              12 Text goes here      1
2         5 Blue              13 Text goes here      1
3         6 Red               14 Text goes here      1
4         6 Red               15 Text goes here      1

$`2`
# A tibble: 2 x 5
# Groups:   Colour [1]
  `Book ID` Colour `sentence ID` Sentences      sample
      <dbl> <chr>          <dbl> <chr>           <int>
1         2 Red                4 Text goes here      2
2         2 Red                5 Text goes here      2

$`3`
# A tibble: 1 x 5
# Groups:   Colour [1]
  `Book ID` Colour `sentence ID` Sentences      sample
      <dbl> <chr>          <dbl> <chr>           <int>
1         3 Green              6 Text goes here      3

$`4`
# A tibble: 8 x 5
# Groups:   Colour [2]
  `Book ID` Colour `sentence ID` Sentences      sample
      <dbl> <chr>          <dbl> <chr>           <int>
1         1 Blue               1 Text goes here      4
2         1 Blue               2 Text goes here      4
3         1 Blue               3 Text goes here      4
4         4 Orange             7 Text goes here      4
5         4 Orange             8 Text goes here      4
6         4 Orange             9 Text goes here      4
7         4 Orange            10 Text goes here      4
8         4 Orange            11 Text goes here      4

Comment: I am not a statistician, but I think that the sampling part `sample(rep_len(1:4, (n() + 3) %/% 4 * 4 ), n(), replace = F)` is not random. Each book must be *randomly (!)* assigned to a group, but this does not work here. Think about the logic here: in a 4-book colour, if books are already assigned to sample 1, 2 and 3 the last book can *only* be assigned to 4 - this is not random. Hence, maybe you should change the answer to `sample(1:4, n(), replace = TRUE)`.
But just a suggestion. :)
Comment: I gave this solution to comply with condition 1 (all sample should have the same distribution of colours). You are right, that this constraint reduces the randomness.


Translating vector elements in R using correspondence table

Question: What is the efficient and simple way in R to do the following:

read in two-column data from a file
use this information to build some kind of translation dictionary, like a python dict
apply the translation to the content of a vector in order to obtain the translated vector, possibly for several vectors but using the same correspondence information

?
I thought that the hash package would help me to do that, but I'm unsure I perform step 3 correctly.
Say my initial vector is my_vect and my hash is my_dict
I tried the following:

values(my_dict, keys=my_vect)

The following observation make me doubt that I'm doing it in the proper way:

The operation seems slow (more than one second on a powerful desktop computer with a vector of 582 entries and a hash of 46665 entries)
It results in something that doesn't look homogeneous with my_vec: while my_vec appeared as "indexed by numbers" (I mean that integer numbers between square brackets appear on the side of the values when displaying the data in the interactive console), the result of calling values as above appears to still somehow looks like a dictionary: each displayed translated value has the original value (i.e. hash key) displayed above it. I just want the values.

Edit:
If I understand correctly, R has some way of using "names" instead of numerical indices for vectors, and what I obtain using the values function is such a vector with names. It seems to work for what I wanted to do, although I imagine it takes more memory than necessary.
Answer: I tried libraries hash and hashmap, and the second seemed more efficient.
A small usage example:
> library(hashmap)
> keys = c("a", "b", "c", "d")
> values = c("A", "B", "C", "D")
> my_dict <- hashmap(keys, values)
> my_vect <- c("b", "c", "c")
> translated <- my_dict$find(my_vect)
> translated
[1] "B" "C" "C"

To build the dictionary from a table obtained using read.table, the option stringsAsFactors = FALSE of read.table has to be used, otherwise weird things happen (see discussion in the comments of https://stackoverflow.com/a/38838271/1878788).
Answer: Did you try the str_replace_all function from the stringr package?
Let's say you have a dictionary data frame dict with columns original and replacement. The following code replaces all instances of original with replacement in the vector.
library(stringr)
translations <- setNames(dict$replacement, dict$original)
new_vect <- str_replace_all(vect, fixed(translations))

I'm not sure if it implements hashing, but the underlying expression is in C code from the stringi package, so it should be fast.
The only case where that won't work as is, is if some of the words in original contain other words in original. In this case you'll need to add regular expression start-string (^) or end-string ($) markers to the original strings you want to replace.
translations <- setNames(dict$replacement, paste0("^", dict$original, "$"))
Comment: I have my data frame `conversion_table` obtained by reading the 2-column file and from which I could build the hash. so `conversion_table$V1` contains the originals and `conversion_table$V2` contains the replacements. Then I do `translation <- setNames(conversion_table$V2, conversion_table$V1)` and `translation` seems to have a similar format than what I get using `values` on the hash: the replacement values "indexed" by the original values. I gues that is what R calls "names". But then, `str_replace_all` strangely returns me a vector of numbers between quotes. And it is slower than the hash.
Comment: Actually, what I describe in my previous comment is what happens when I use the "^" and "$". If I don't use them, the resulting vector contains a few entries that contain a dot among the numbers. Example:
`[289] "1955"  "1955"  "17361" "17392" "17400" "1963"` vs `[289] "12562.12" "12562.12" "27385.1"  "17392"    "17400"    "1963"` for items 289 to 294 of the translated vector. The original was
`[289] R13A5.12   R13A5.12   R13F6.1    R144.7     R148.7     R74.1`
Comment: The "thing" I had obtained using the hash loooked like so for this same `289:294` slice:
`R13A5.12       R13A5.12        R13F6.1         R144.7         R48.7         R74.1`
`WBGene00003063 WBGene00003063 WBGene00020064 WBGene00020097 WBGene00020105 WBGene00003073`
(The "keys" being displayed above the corresponding values.)
The "WBGene*" are what I expect after translation.
Comment: When you read the data frame from the file, did you specify `stringsAsFactors = FALSE`? I believe that's the source of the bug where it returns quoted numbers. But in any, if the hash result is correct and faster, you don't need to use stringr.
Comment: I hadn't used that option. I naively assumed that read.table would simply read the data "normally". I realize now that omitting this option has strange effects in other cases. I tried the hashmap package to build a similar dictionary-like translating device, and omitting to set `stringsAsFactors = FALSE` resulted in a thing that could operate on data from the original table but resulted in numbers instead of names. Besides, it would fail when I would manually provide elements of my vector. The option fixed this.
So far, using R has been a bit frustrating due to weird behaviours like that.


How to replace permalink in Wordpress with the value from a custom field?

Question: I'm really confused by custom values in Wordpress. None of the resources I've found have made much sense to me and answered my specific problem so was hoping I'd be able to get some assistance here.
So on each of my blog posts I have a custom field with the name 'amazon link'. The value for this custom field is in the form 'http://www.amazon.com/abc'.
I am trying to replace the permalink to each post on category pages with the value from the custom field. So I'm thinking that I would edit the following code:
<?php
        endif;

        if ( is_single() ) :
            the_title( '
', '
' );
        else :
            the_title( '
', '
' );
        endif;
    ?>

and replace the 'get_permalink()' bit in the section shown below:
the_title( '
', '
' );

But what code would I need to replace it with?
Thanks in advance for your attention and answers.
Answer: You would use get_post_meta() to get the post meta value. From the docs:
get_post_meta ( int $post_id, string $key = '', bool $single = false )

Therefore, you'd use something like the following:
else :
    $amazon_link = esc_url( get_post_meta( get_the_ID(), 'amazon_link', true ) );
    the_title( '
', '
' );

Keep in mind, your meta keys shouldn't have spaces in them...So I don't know if amazon_link is your actual meta key.
Comment: Awesome - that worked a treat thank you. A couple of points I discovered while trying to implement this that may help future viewers of this thread.

1. Capitalisation matters! Key_name is not the same as key_name

2. I didn't realise you have to store the code get_post_meta( get_the_ID(), 'amazon_link', true ) in a variable. I had seen this code proposed in other threads on a similar topic but it wasn't working for me. This is why.
Comment: @Harry , you actually don't have to store the meta in a variable...I just did that for readability. You could use the following just as well: `the_title( '', '' );`


On a pandiagonal Latin square, what is a broken diagonal?

Question: After reading "No pandiagonal latin squares with order divisible by 3?" I didn't understand what a "broken diagonal" is.
Thanks
Comment: I quoted the question in mine, it is not a duplicate, but I do think I now understand what a broken diagonal is.  I think it is a diagonal containing less entries or cells than the order of the Latin square.
Comment: Sorry, Darren. I'm just so used to the hypertext point of view of "quoting" = "giving a link". I took the liberty of adding that link to your post. Click the edit -button to see how it is done.
Answer: Broken diagonals are collections of $n$ cells - one on each row and column. They are parallel to one of the main diagonals but they wrap around when the diagonal reaches a border of the square. So either a set of cells in positions $(i,i+k)$ for $i=1,2,\ldots,n$,
and a fixed $k$, or in positions $(i,i-k)$. The arithmetic on the column indices is done modulo $n$. Changing the value of $k$ gives another broken diagonal.
For example in the following latin square the red cells form one broken diagonal and
the green cells another one. The brown number is in their intersection.
$$
\pmatrix{
0&\color{Red}2&4&6&\color{Green}1&3&5\cr
1&3&\color{Red}5&\color{Green}0&2&4&6\cr
2&4&\color{Green}6&\color{Red}1&3&5&0\cr
3&\color{Green}5&0&2&\color{Red}4&6&1\cr
\color{Green}4&6&1&3&5&\color{Red}0&2\cr
5&0&2&4&6&1&\color{Brown}3\cr
\color{Red}6&1&3&5&0&\color{Green}2&4\cr
}
$$
Comment: Thank you for that, I'm new to stack exchange, and to the mathematical language of Latin squares.  I guess I need to find a forum. Any recommendations?
Comment: I'm afraid I cannot help you in looking for a better forum. Douglas Stones is the top guy on Latin squares here, but he hasn't been around lately. IIRC he started on another research theme after getting his PhD.Just look at [the earlier questions on latin squares}(http://math.stackexchange.com/questions/tagged/latin-square). You will find that many people can answer basic questions here. Here's to hoping that you find Math.SE of use.
Answer: My illustration for broken diagonals

Please see this thread
https://boinc.progger.info/odlk/forum_thread.php?id=178
Comment: Welcome on the MathSE! I inserted your image link into your post, but link-only answers are not allowed here. It means that if you provide a link in your answer, you need to copy-paste the most important part of the remote content into your post. It is because remote links often go down, making your answer incomprehensible. Your answer need to be comprehensible even without opening the remote link.


$\{x \in \mathbb{R} : f$ is Lebesgue integrable in some open neighborhood of $x\}$ is dense in $\mathbb{R}$.

Question: Suppose $\{F_n\}_{n\in N}$ are a sequence of closed sets with $\cup_n F_n = \mathbb{R}$. Suppose that $f :\mathbb{R} \to \mathbb{R}$ is measurable and $f$ is Lebesgue integrable on $F_n$ for each $n$. Prove that
$\{x \in \mathbb{R} : f$ is Lebesgue integrable in some open neighborhood of $x\}$ is dense in $\mathbb{R}$.
$\textbf{my attempt}$: is the following solution correct?:
suppose not, then $\exists x \in \mathbb{R}$ such that for some $\epsilon >0 , f\notin L^1 (N_\epsilon(x))$. Since $\cup_n F_n = \mathbb{R}$ , it must be that $x\in F_n$ for some $n$. This means that $\exists N_\epsilon(x) \subset F_n $ such that $f$ is not integrable.  This is contradiction to the following lemma.
if $f\in L^1 (A)$ then $f\in L^1 (B)$ for any open (hence lebesgue measurable) $B\subset A$.
proof:
since $f$ is measurable there is sequence of simple functions ,$g_n$, that converges pointwise to $f$. let $f=\chi_B g_n$. Since $B$ is measurable by fatu's lemma we have that $f\in L^1 (B)$.
$\textbf{Question}$: if above solution is right, what role does the closedness of $F_n$ plays?
Comment: I don't know if the proof is right or not. But for me it isn't clear that $N_\epsilon(x)\subset F_n$. $F$ is closed, so it doesn't need to contain a neighbourhood of $x$. At most, $f$ wouldn't be integrable on $N_\epsilon(x)\cap F_n$. And then, the above lemma is contradicted only if you are assuming the relative topology,.
Comment: Do you know Baire's Theorem?
Comment: The closedness of $K_n$ is such that you can apply Baire's theorem.
Comment: @conditionalMethod I was thinking of using Baire, but did not know how to apply that here.
Answer: Baire's theorem implies that one of the $K_n$ has non-empty interior, which obviously is not sufficient for proving the statement (since it will only provide you with the fact that your set contains some open set). However, you may intersect the $K_n$ with (say) dyadic intervals and apply Baire's theorem to show that your set contains an open subset of every dyadic interval, which implies density.


Simple conditional formatting in Google Sheets Script Editor

Question: I am trying to create some basic conditional formatting rules with Scripts instead of the conditional formatting editor in sheets, because when a new row is added or removed, it breaks the rules already set.  For example, when a row is deleted, the condition may be for the range A:C but then it adds "A1:C5,A6:C898".  This causes some rows to be skipped by the rules so I am hoping a script will solve this.
So I want to simply change the cell background to green if the cell text is exactly "Y". I want to change it to red if text is exactly "N". I have other rules that I want to use but I am having trouble with the basics on this.
What I have so far in my script:
function onEdit(e) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("PRECLOSING");
  var range = sheet.getRange("E:E,I:J,M:M,P:P,S:V,AB:AC,AF:AF");
  range.activate();

  var values = rangeY.getValues();

  //for each row that data is present
  for(var i = 0; i < values.length; i++) {
    var cell = sheet.getRange(i + 1, 2);

      if ( values == "X" )
         {
           cell.setBackground('black');
           return;
         } else {
           cell.setBackground('white');
         }
   }
}

Answer: I made some modifications to your code.
The function getRange i don't think it can accept the ranges in that way, instead i think it can get just ranges that are continue (eg. A1:E10)
For that I created an array with the ranges you need and then I loop through them.
The function "getValues" returns a two dimensional array so you will need a second loop to get the actual value from the cell.
Then as you already have the range, you need to get the cell inside that range and not a new complete range.
function onEdit(e) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("PRECLOSING");;
  var columns = ['E:E','I:J','M:M','P:P','S:V','AB:AC','AF:AF'];

  for(var col in columns){ //loop to iterate the desired ranges

    var range = sheet.getRange(columns[col]);
    range.activate();

    var values = range.getValues();

    //for each row that data is present
    for(var i = 0; i < values.length; i++) { //loop to iterate the rows
      for( var j = 0; j< values[i].length ; j++){   //loop to iterate the columns
        var cell = range.getCell(i+1, j+1);
        if ( values[i][j] == "X" )
         {
           cell.setBackground('black');
         }
      }
     }
   }
}

Hope this helps.
Comment: This seems to work, however it "takes control" of the sheet.  What I mean is, when I put the X in the E column, the sheet highlights all the columns we have listed, and goes through it, scrolling the screen left to right.  I have about 50 columns and about 200 rows. Looks like its on the right track though.
Comment: remove the line: range.activate();
Comment: This is great. Now I need to figure out how to have multiple rules in these columns and others.  For example, I thought about making a YES Range, a NO range, N/A range, Date range, etc. for different colors.
Comment: So could I create multiple ranges and have if statements by range? For example, I am looking for "YES" in range A:C, F:F, M:X and looking for "NO" in B:D, F:G, N:AA - see the overlap? Just thinking out loud since I have about 12 rules and 50 columns.


how to show svg graph in vue with only svg graph link

Question: the only thing I have now is a svg link, opening the link on the browser will show up a svg graph.
I want to show up a svg graph in vue application, http://tiku.qycareer.com/api/captcha/index?1661672036108
I tried this way in vue but doesn't work.
any other ways ?
Answer: You can load any external file, and inline it, with the <load-file> (native javascript) Web Component.
Loads of options, unlicensed and only 8 lines of code:
Dev.To blog post <load-file> Web Component

<load-file src="http://tiku.qycareer.com/api/captcha/index?1661672036108"></load-file>


Telegram API code is no longer sending messages

Question: Telegram API/BOT code is no longer sending messages and getting the following error
The request was aborted: Could not create SSL/TLS secure channel.

I also tried the following option
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

API/BOT is working locally as expected but when I hosted the application in live server (Bigrock shared hosting) am getting this issue. Tried in both secure & non-secure environments
Answer: I got the same problem. "Working in dev but not in live"
Found this: https://clickalgo.com/telegram-secure-channel
Worked for me, you probably just need to run it before you create the bot.
Example from site:
Comment: yes its working in Console app, but if you convert this into ASP.Net Web App its not working. Web App also locally working perfectly **but in shared hosting it is not working**.
Comment: @Kiran. So I'm no expert but perhaps I can point you in the right direction. When using ASP.net you run different sessions and nothing is static. The session is only open while a call is being made or its timed out by your web-server(Probably IIS). IIS express which you use to debug works differently and is probably the reason why it worked locally. As far as I am aware best practice is to run a separate service for processes you do not want to get killed I.E Telegram Bot.


Kafka Streams WindowStore build error - Serdes incompatible with Serdes

Question: Im trying to use the aggregate function for a Kafka Stream tumbling [window][1].
However, I'm getting this strange build error.
This is how my code looks like -
kStreamBuilder.stream(topic, Consumed.with(STRING_SERDE, MYBEAN_SERDE))
            .groupBy((key, value) -> value.id(), Grouped.with(
                    Serdes.String(),
                    MYBEAN_SERDE))
            .windowedBy(TimeWindows.of(Duration.ofMinutes(1)))
            .aggregate( Aggregration::new,(key, value, aggregration) ->
                    {
                        aggregration.count++;
                        return aggregration;
                    },Materialized.as(Stores.persistentWindowStore("asd",Duration.ofMinutes(1), Duration.ofMinutes(1),false))
                    .withKeySerde(STRING_SERDE).withValueSerde(AGGREGRATION_SERDE)
            );

This is the error I'm getting in the ".withKeySerde(STRING_SERDE)" part -
java: incompatible types: org.apache.kafka.common.serialization.Serde<java.lang.String> cannot be converted to org.apache.kafka.common.serialization.Serde<java.lang.Object>
Answer: Found the solution here - Kafka Streams Materialized Store Build Error
Here is the updated code -
kStreamBuilder.stream(topic, Consumed.with(STRING_SERDE, MYBEAN_SERDE))
        .groupBy((key, value) -> value.id(), Grouped.with(
                Serdes.String(),
                MYBEAN_SERDE))
        .windowedBy(TimeWindows.of(Duration.ofMinutes(1)))
        .aggregate( Aggregration::new,(key, value, aggregration) ->
                {
                    aggregration.count++;
                    return aggregration;
                },Materialized.<String,Aggregration>as(Stores.persistentWindowStore("asd",Duration.ofMinutes(1), Duration.ofMinutes(1),false))
                .withKeySerde(STRING_SERDE).withValueSerde(AGGREGRATION_SERDE)
        );


inheritance and Overriding in javascript

Question: Below is my JS code:
var Person=function(name,age)
{
   this.name=name;
    this.age=age;
}

Person.prototype.calculateAge=function()
{
    console.log(2016-this.age);
}

var Teacher=function(salary)
{
    this.salary=salary;
}

Teacher.prototype.calculateAge=function() // Ovverriding the fucntion calculateAge
{
    console.log("welcome to my world");
}

var pp=new Person('john',31);  // creating object pp, pp.name // john

Teacher.prototype=pp;

var t= new Teacher(20);   // inherit name and age , t.name // john

// now here am confused
  t.calculateAge() // 1990  but am ovverride it will print my console right
  //

Can anyone please explain how can i override? Here when I am overriding calculate age function, by calling t.calculateAge() its printing inherited one
Comment: See this :  https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
Comment: i checked so many blogs and videos also, i confused, am overriding calculateAge funtion right, but whrn i calling t.calculateAge(), it will print latestone, but here printing parent , how we ovverride in this case, how its workes
Comment: Improved language and made formatting changes
Comment: okay @RahulGupta, You didn't understand my question ??  can i explain again
Answer: This code work probably :
function  Person(name,age)
{
   this.name=name;
    this.age=age;
}

Person.prototype.calculateAge=function()
{
    console.log(2016-this.age);
}

function Teacher(salary)
{
    this.salary=salary;
}
Teacher.prototype = new Person();

Teacher.prototype.calculateAge=function() // Ovverriding the fucntion calculateAge
{
    console.log("welcome to my world");
}

var t= new Teacher(20);   // inherit name and age , t.name // john

// now here am confused
  t.calculateAge() // 1990  but am ovverride it will print my console right
  //

Comment: Yes, working but here i have small doubt,
Teacher.prototype = new Person('john',20);
var t=new teacher(20) //t.name=john, t.age=20 k fine,
But "I am overriding calculatingAge() fucntion in teacher Object, you are created object taking Teacher.prototype, i want person calculateAge() function, Then how we achieve ,

Thanks a lot for replying , I am confused a lot i have so many doubts #ZAhmed
Comment: here how to call  calculateAge()// Function for Person, t.calculateAge() it will print calculateAge()  for  Teacher object right
Comment: by this :   var l = new Person('ahmad',20);

       l.calculateAge();
Answer: Teacher.prototype.calculateAge = function() ... should be after the line Teacher.prototype = pp.
Otherwise, Teacher.prototype = pp will reset Teacher.prototype to pp.
And, t.calculateAge() output 1985 for 2016 - 31 = 1985.
Comment: Thanq @leaf but here i want to print override function() result, i.e console.log() o/p ,


Which distribution would fit this binomial type series of events?

Question:
We have arbitrarily many lottery scratch-n-win tickets
Each ticket has a $p=0.1\%$ chance to win 1 prize (a success event)

Scenario A, Scratch n tickets and record the number of prizes won $X$:
From the binomial distribution, $X$ will have a mean of 1 if $n=1000$. But, I'm more interested in the other scenario,
Scenario B, Scratch until we win ONE prize, then stop and record the nummber of tickets used as parameter $n$:
I understand that the mean value of $n$ is going to be 1000 based on the fact that the expected value, 1, is equal to $np$.
But what distribution will n be described by if we make repetitions of scenario B? What I ultimately want is to be able to produce $n \pm Z$ with $95\%$ confidence where $n$ indicates the number of tickets used whereby 1 and only 1 prize is won. With which model can I get $n$ and $Z$ accurately?
So far the Normal approximation doesn't seem to be working well and I suspect it is due to $p$ being too close to 0.
Answer: That is the geometric distibution. See Wikipedia for more detail.
Comment: exactly what I was looking for thanks


Counting Problem - discrete math

Question: I need help with the following problem:
There are three computers A, B, and C. Computer A has 10 tasks, Computer B has 15 tasks, and Computer C has 20 tasks. Each computer must complete its own tasks in order. After, each computer sends its output to a shared fourth computer. How many different orders can the outputs arrive at the fourth computer.
My work so far:
This is a permutation problem since the order matters. 10! * 15! * 20! is what I believe the answer is but I am unsure.
Answer: HINT: This is not a permutation problem, because the order of tasks for each of the three computers is fixed; the only thing that varies is how the tasks for the three computers are interleaved. Once we know which $10$ of the $10+15+20=45$ positions in the output are occupied by A's tasks, we know which of A's tasks is in each of those $10$ positions: they must have been done in order. Similarly, once we know which $15$ positions have the output of B's tasks, we know which of B's tasks is in each of those positions.

How many ways are there to choose the $10$ positions in the output for A's tasks?
Once that's been done, how many ways are there to choose $15$ of the remaining positions for B's tasks?

At that point all $20$ of the positions that still remain must be filled with C's tasks in their proper order, so there are no more choices to be made. Putting the pieces together, how many different orders are there in which the $45$ outputs can arrive at the fourth computer?
Comment: Okay, so then wouldn't it be C(45, 10) * C(35, 15) * 1 ? This would account for the combinations of each task for each computer running
Comment: @BrockMarshal: Yes, that's right.

Counting Problem - discrete math


How can I use an Or inside of an IF statement in C#?

Question: I am trying to create an if statement that will perform an action if any of the conditions are true. The items I need to test are the text values of eight textboxes. What I have right now is the following and the error it gives me says "Operator '||' cannot be applied to operands of type 'string' and 'string'".
if (textbox1.text = "" || textbox2.text = "" || ...... and so on)

If anyone knows a how I am supposed to be wording this if statement or an easy way to check to see if a .ini file at a known location exists. Either would work for me.
Answer: You need to use the equality operator == not the assignment =.
if (textbox1.text == "" || textbox2.text == "" || ...... and so on)

Your textbox1.text = "" sets the value of textbox1.text to an empty string, and returns this as the result of the assignment. You are therefore attempting to use a boolean or (||) on two strings.
Answer: In C#, if you are checking if a value is equal - you need to use double equal sign.
Your code should look like this:
if (textbox1.text == "" || textbox2.text == "" || ...... and so on)

Answer: String.IsNullOrEmpty() will return a boolean for you:
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
..and, like others have said, use "==" for testing equality.
Answer: textbox1.text == "" ||

Note the DOUBLE = sign.
as written, your question would evaluate by first assigning empty string to each variable then applying the OR to those, so by the time the boolean is evaluated it looks like
if ("" || "" || "" ... etc)

and the OR operator doesn't work on strings.  Note that if you are not careful, then you'll quietly break this rule.
if (x = true || y = false) evaluates to if (true || false), and won't give you such a timely compiler warning
Answer: System.IO.File.Exists(path), returns a boolean
Comment: How is this in any way relevant to the question?
Comment: The last bit of the question: "...or an easy way to check to see if a .ini file at a known location exists."


Convert to template

Question: I'm wondering how can i do something like this ? Using template<typename T> with typedef ?
template <typename T>
typedef bool (*cmp_func)(T i0, T i1); // <- syntax error here

I'm trying to sort items of a template type.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <ctime>

using namespace std;

typedef bool (*cmp_func)(int i0, int i1);

template<typename T>
void print_array(int n, T *x)
{
        cout << "[";
        for (int i = 0; i < n; ++i) {
                cout << setw(3) << x[i];
        }
        cout << " ]\n";
 }

template <typename T>
bool less_than(T i0, T i1) { return i0 < i1; }

template <typename T>
bool greater_than(T i0, T i1) { return i0 > i1; }

template <typename T>
bool is_sorted(int n, T *x, cmp_func cmp)
{
        for (int i = 1; i < n; ++i)
                if ((*cmp)(x[i], x[i-1]))
                        return false;

        return true;
}

  template <typename T>
void exchange(T* x, int i, int j)
{
        T t = x[i];
        x[i] = x[j];
        x[j] = t;
}

template <typename T>
void insertion_sort(T *x, int l, int r, cmp_func cmp)
{
        for (int i = l+1; i <= r; ++i) {
                for (int j = i; j > l; --j){
                        if ((*cmp)(x[j], x[j-1]))
                                exchange(x, j, j-1);
                    cout << "  ";
                    print_array(r-l+1, x+l);
                }
        }
}

template <typename T>
void insertion_sort2(T *x, int l, int r, cmp_func cmp)
{
        for (int i = r; i > l; --i)
                if ((*cmp)(x[i], x[i-1]))
                        exchange(x, i, i-1);

        for (int i = l+2; i <= r; ++i) {
                int j = i;
                int v = x[i];
                while((*cmp)(v, x[j-1])) {
                        x[j] = x[j-1];
                        --j;
                }
                x[j] = v;

                cout << "  ";
                print_array(r-l+1, x+l);
        }
}

template <typename T>
void fill_random(T n, T *x)
{
        const int M = 100;

        srand(time(0));

        for (int i = 0; i < n; ++i)
                x[i] = rand() % M;
}

int main(int argc, char **argv)
{
        const int N = 10;
        int x[N];
        fill_random(N, x);
        print_array(N, x);

        insertion_sort(x, 0, N-1, &less_than);
        print_array(N, x);

        if (is_sorted(N, x, &less_than))
                cout << "SORTED\n";
        else
                cout << "NOT SORTED\n";

        return EXIT_SUCCESS;
}

Comment: Please don't remove your question after receiving an answer; even if you have your answer, the question and answer can still be useful to others in the future.  Thank you.
Answer: Typedefs cannot be templates.  C++11 using aliases, however, can be:
template <typename T>
using cmp_func = bool (*)(T i0, T i1);

The pre-C++11 workaround is to create a template struct that has a type typedef:
template <typename T>
struct cmp_func {
    typedef bool (*type)(T i0, T i1);
};

Which is then referenced as typename cmp_func<int>::type for example.
Comment: Well thanks but when i try to write your first solution i get error. Firstly "error: expected unqualified-id before 'using'
then " 'cmp_func' has not been declared "
Comment: @KaanCaglan It compiles fine for me. Are you compiling in C++11 (or higher) mode?
Comment: @KaanCaglan Also, consider using a template parameter for the comparer and then this problem goes away entirely: `template  bool is_sorted(int n, T *x, U && cmp)`. Then the type of the compare function can be deduced and you don't even need a named `cmp_func` at all. Plus you get the ability to use functors instead of function pointers, you can use `std::function`, etc.
Comment: Actually i don't know  :D im using Notepad++ in win8 and emacs in linux

Convert to template


Does the Stance Tuning options improve the performance of the vehicle?

Question: Does changing the Camber and Height options change the vehicle performance?
Answer: Sorry, no Camber and Height do not affect you car's handling, they are purely cosmetic.
NFS Payback's customization options are not consistent on whether or not they affect your vehicle's performance. For instance, modifications like your car's spoiler or canards will affect downforce strength and improve agility at high speeds but other changes like brake discs don't have any effect.
I'd advise you to look through Payback's wikia page to get a better idea of what modifications affect performance and what modifications don't.
Comment: As the comments on the Reddit post say, is just stupid.
Comment: Couldn't agree more. Especially because camber and height did affect performance in Need For Speed 2015 (IIRC)
Answer: I looked on the internet and it said everywhere that it does not affect performance. So, I went to the garage at the airport, put front weels all straight and the rear wheels with the widest angle. I took it for a spin with 2 turns, 1 normal brake and 1 hand brake. Back to the garage, installed the wheels opposite of what they were.
I went outside again and immediatly after the first turn i already noticed there was a big difference.
Comment: Can you also explain what that difference was?


Modify SQL in NHibernate

Question: I need to know how to modify a sql, to add to every select a sql code.
My problem is, I need to add this sql code after a "FROM table" + " sql_code", even if there is something after "like a GROUP BY".
I know that I need to use the OnPrepareStatement, I just don't know how to edit the SqlString to do so !
One thing that I've tried:
public override SqlString OnPrepareStatement(SqlString sql)
    {
       if (sql.Parts.Cast<string>().FirstOrDefault().Trim().ToLower() != "select")
        {
            return sql;
        }
        StringBuilder novaString = new StringBuilder(sql.ToString());
        String corte = sql.SubstringStartingWithLast("where").ToString();
        if (corte != "")
        {
            StringBuilder sb = new StringBuilder(corte);
            sb.Insert(0, "with(nolock) ");
            novaString.Replace(corte, sb.ToString());
        }
        else
        {
            novaString.Append(" with(nolock)");
        }
        return new SqlString(novaString.ToString());
    }

Thanks !
Comment: I didn't know what that means. I will, sorry !
Comment: He means you need to mark one of the answers in each your previous questions as "accepted", that is if there are answers and they helped.
Comment: yes, I got that part ! Do you have any idea of my issue ? Thanks guys !
Comment: Show us some code? what have you tried so far?
Comment: @Rippo So, I tried that code, but the second time it runs (when there is a strange sql code with _0_0) it returns this error: http://imageshack.us/photo/my-images/577/exceptionh.png/
Comment: Have you read this S.O. answer? http://stackoverflow.com/questions/1302746/how-do-add-nolock-with-nhibernate
Comment: @Rippo My problem is, I need the with(nolock) to be shown on the sql dump ! I just need to fix something in that code ! Thanks !
Comment: @Rippo I have re edited my code, I'd like to know how to fix the error of the img http://imageshack.us/photo/my-images/577/exceptionh.png/ ! Thanks
Answer: I'm a little late to the party but here is how I optomize some of our queries.  The below takes a given sql statement and appends a little bit to the end:
public class OptionInterceptor: EmptyInterceptor
{
    public override SqlString OnPrepareStatement(SqlString sql)
    {
        var parameters = sql.GetParameters();
        var paramCount = parameters.Count();

        if (paramCount > 0)
            return sql;

        string optionString = " OPTION (OPTIMIZE FOR (";

        for (var i = 0; i < paramCount; i++)
        {
            var comma = i > 0 ? "," : string.Empty;
            optionString = optionString + comma + "@p" + i + " UNKNOWN";
        }

        optionString = optionString + "))";

        var builder = new SqlStringBuilder(sql);

        builder.Add(optionString);

        return builder.ToSqlString();
    }
}

Answer: A bit too late, but still. I had to add a hint into generated sql:
private class SqlLogger : EmptyInterceptor
{
    private const string Select = "SELECT";
    private const int SelectLen = 6;
    private const string Hint = " /*+ dynamic_sampling(0) */";
    private const char Param = '?';

    public override SqlString OnPrepareStatement(SqlString sql)
    {
        var s = sql.ToString().ToUpper();
        var start = s.IndexOf(Select, StringComparison.Ordinal);
        if (start != -1)
            s = s.Insert(SelectLen, Hint);

        var builder = new SqlStringBuilder();
        var parts = s.Split(Param);
        for (var i = 0; i < parts.Length - 1; i++)
        {
            builder.Add(parts[i]);
            builder.AddParameter();
        }
        builder.Add(parts.Last());
        sql = builder.ToSqlString();

        return sql;
    }
}

Modify SQL in NHibernate


How to exchange data between MySQL and Parse.com?

Question: We plan to use a MySQL database as the backend for our (Java or Ruby on Rails) based web application. After completing the web application, we want to port the application to iOS and Android.
We want to be able to run the application in "native" mode - that is, if a network connection is not available to the smart-phone, the system should be able to store the data locally, and sync with the backend when the network connection becomes available.
The best kind of framework for this kind of syncing is a library/framework such as Parse.com.
The question to which we want an answer is: is it possible to exchange data between the web application data stored in MySQL, and the Parse.com data which is stored in a proprietary format on the Parse servers?
Comment: Another application that uses the same idea is to have a raspberry pi storing sensor data into a local mysql or sqlite DB and then sync back to parse.com. The data collection will work even without internet connection, and data will be available online as soon as internet connection is available.
Answer: Answer to your question: It is indeed possible, but syncing data is an advanced topic.
However, you also state that you want to access the parse data when offline. As I understand it, you want Parse to handle the offline state, and then sync to MySQL when connection is back up. Parse does not offer functionality to store data offline, other than caching requests. You probably need another service for your specific needs.
I might have misunderstood the use case. If so, my alternate understanding would be that ALL data for the smart phones will be handled by parse: both offline and online, with syncing. The answer is still: parse does not offer this kind of functionality.


What is the beam the Sectoids shoot at each other?

Question: Basic Sectoids use their mind power to shoot beams back and forth amongst each other. I haven't been able to figure out what they are trying to do. What is the point of these beams?
Comment: It is worth noting that once you have autopsied an alien then you can see a list of all their powers in their information screen which I believe describes this power. Mainly relevant in case you have any questions about other powers later...
Answer: The ability is called Mind Merge.
As long as the beam is maintained, the target sectoid gains these benefits:

One additional health bar (meaning they can no longer be killed with 1 grenade).
+25% crit chance

If you kill the sectoid giving the mind merge, the receiving unit will immediately die.  The mind merge effect takes precedence over explosive damage death, so if you catch two sectoids (one mind merging the other) in a rocket, you'll still recover some weapon fragments.
Comment: also Mind Merge heals it target for 1 hp. Very annoying.
Comment: So to summarize, shoot the sectoid in the back and ignore his boosted buddy.
Comment: @SergeyGrinev: Does it actually heal them by one or does it just add one health because of the extra max health? ie if a sectoid with 1/3 health is mind controlled it goes to 2/4 but when it ends is it on 2/3 or 1/3? I don't think I've ever seen a partly injured sectoid mind controlled (and paid attention enough to what happens).
Comment: he will stay with 2 out of 3 hp left at end of turn, so after several turns he can return back to 3 hp.


I replaced my fluorescent light ballast but the bulbs turn off immediately

Question: I changed the ballast on the florescent lights in the laundry room yesterday. Now this morning when I throw the switch they turn on then off immediately.
Is this a loose wire connection? Should I go back and tighten up the the wires? Or do they need new bulbs?
Comment: When I run into dead florescent bulbs or ballasts I usually replace the entire fixture with an LED one.  Florescent has gone the way of the dinosaur and I couldn't be happier.
Comment: Pictures, specs etc please.
Comment: For the LED..  Do I just remove the ballast and hook them up straight in?
Comment: It depends, see @EdBeals response below, it is very detailed.  I was speaking of replacing the entire fixture. I have used replacement led tubes in a florescent fixture with mixed results.
Comment: Fluorescent has evolved and the new lamps and ballasts give superior light to LED.  There's good reason to keep it.  However you must wire the ballast correctly, and that  often goes wrong.  I'd like to see pix of the new ballast and wiring to start.  Also the tubes in use.
Comment: Just a quick note. If you miswired the ballast there is a good chance you will need another one before you begin your repair.
Answer: I check the lamps first prior to changing the ballast because lamps fail more often than ballasts. If the ballast is bad, I usually replace the tubes with ballast bypass LED lamps. Good quality lamps are around 10-11 bucks. Look for DLC certification. The lamps that are not DLC certified do not tend to last in my experience.
I like double-ended LEDs because these will work with shunted tombstones (the part that holds the lamp); with single-ended tombstones you will need to replace them if shunted. To tell if the tombstones are shunted, with the power off use an ohm meter and measure the resistance from the 2 contacts. If reading zero or very low ohms, they are shunted.
Last, purchase from a vendor that has a long warranty - 5 years is my target. Some companies have good no-hassle warranties where you take a photo of the fixture with a working and failed light and they give you a credit or refund. Some companies require you to ship the lamps back as they no one will pay almost as much to return a lamp - those are sham warranties in my opinion.
To install a ballast bypass set of lights double-ended, 1 wire from each tombstone at 1 end can be wire butted together with the hot and the other end and 1 wire from each tombstone nutted to the neutral. The ballast can be left in the fixture but the wires should be cut or removed from the ballast and capped, cutting close to the ballast provides all the wire needed in hundreds of fixtures I have upgraded. Ballast bypass lamps usually come with a sticker that states the fixture was rewired and not to use fluorescent bulbs.
Earlier I used the term DLC certified. This stands for Design Lights Consortium. With this certification, you know that your lamps are efficient (not all LEDs are created equal) and meet the quality standards. Most power companies that provide rebates for upgrades require the new lamps to be DLC certified to get the rebates if available. In my area it is close to 70% of the cost of the lamp so this can bring your final cost to that of  quality fluorescents and now you are saving $ on your power bill and they have longer expected life.
Since you have already replaced the ballast try some new lamps. If the ends of the lamps are black or dark the lamp electrodes are probably gone, this is assuming you installed the proper ballast type for the lamps in the fixture. Universal ballast refers to the input voltage only usually 100-277v. Not long ago a friend installed a universal ballast in a 4 tube t8 lamp fixture, the lights did not work because the ballast was for 2' fluorescents.
I hope this information helps you troubleshoot your problem and or upgrade your lights.
Answer: Making an educated guess from the little info we have... My best guess is a loose wire connection between the ballast and the incoming power. There is a slight possibility your new ballast is bad. It's possible you're using the wrong ballast.
As @Gary Bak mentioned, I'd go with updating to an LED fixture and dump the florescent altogether. To answer your question to Gary, no you cannot remove the ballast and straight wire LED fluorescent styled bulbs to your fluorescent housing.
Comment: Yes Gary  You can remove the ballast and direct wire an LED tube that is specifically made for that purpose, A direct wire LED fluorescent tube replacement.  You need to make sure that you change the tumstones to unshunted ones.  In my opinion there's no point in going the other route of getting an LED that runs off of the existing ballast.  Why power a ballast when it's serving no function, just a waste of electricity.
Answer: Wiring ballasts is a bit tricky, and there are several common wiring mistakes. However there are 2-3 different wiring schemes in use, so we can't walk you through it "blind" - we need pix of the ballast and what you've done.
Staying with real fluorescent is perfectly reasonable and don't be goaded into switching to LED. Fluorescent tech has advanced beautifully and 90CRI light is just normal, with no flicker or cold startup problems.  LED still has major quality issues, DLC or not, and I still don't believe you can get a quality LED "tube" for $12.
Our local Target was built 4 years ago with T8 fluorescent, and they just changed all the fixtures to LED, probably for energy credits. (I wish I had been at the dumpster to snag the old gear!)  What I notice now is several of the fixtures are out.  That's buying commercial grade made-to-be-LED fixtures, not even retrofit tubes. Consumers cannot afford quality in LED, they easily can in fluorescent.

So get us some pix of your fluorescent wiring. There are several ways for ballasts to be wired, they are not necessarily color coded the way you might think, and there's also the possibility of a mismatch between tube and ballast.  I want to look at all of those.   We'll get it right!  And 10 years down the road, the light will still work.
There's no way to go any further with the "how to fix it" conversation, because you have not yet provided the details.

Now if you really want LED, that is not a problem either.  I quite agree you should only use ballast-bypass aka direct-wire, and with double ended LEDs, those double pins at the end of the lamp are for 18 volts not 120V.  Being double ended makes the LED 25 cents more expensive, which is why cheapies are single ended.  Double ended means if you plug a single-end LED or real fluorescent in it, nothing melts and explodes.
Comment: DLC minimum warranty is 5 years, I have purchased several hundred t8's and close to a hundred t5's, of all the DLC certified lamps I have installed only 1 has failed and that company gave us the purchase price with just a photo so they are out there. If my fixture is good. I.e. good ballast I relamp but if I have a bad ballast it cost the same to convert as replace the lamps and ballast and you don't have the rapid roll off of light in LED's that Flouresents.


Sizing a window AC for bedroom, but with extenuating circumstances

Question: I'm looking to install a window AC in my son's bedroom, which is about 120 sq ft.  The guides that I'm reading suggest a 5000 BTU unit due to the size.  However we live in the high desert where the summer temperature gets > 100 degrees (F) at times during the summer.  Also he has several reptile terrariums in his room that require lamps which also heat up his room.  In this case would using a 6000 BTU AC unit be more appropriate?
My 180 sq ft. home office/spare bedroom is in the room next to his.  I use a 6000 BTU unit and it chills this room no problem.  So thinking of getting the a simular sized unit, but don't want to oversize if that's going to cause problems.
Thanks in advance for the advice.
Comment: An estimate of the terrarium lamps power needed.
Comment: About 3 100 - 150 watt bulbs.
Comment: Have you ever heard the term "solar gain"?  Where are the rooms relative to the sun? (exposed west, tree-shaded, etc.) What color are the surfaces which face the sun?
Comment: @Frank 300W are ~1000BTU/h, 450W are ~1500 BTU/h . Whatever number you come to for the room, just add 1500 BTU/h for the lamps.
Comment: @Harper-ReinstateMonica  I was thinking the same thing, orientation of the room is an important consideration. Not only that, but quality (insulation ) of windows as well as the amount of insulation in the walls.
Comment: One more comment.  Although probably not an issue in your area due the "high desert" area, you probably have very low humidity, but in other places, with high humidity, over-sizing the unit can lead to icing up and / or not enough run time to dehumidify the air, which leaves kind of a clammy feeling. It's a balancing act.   This is just a comment , not an answer bc I just don't know enough about your situation to give a good answer.
Comment: either will work, there's not a huge difference between them. I would opt for the bigger one as it's greener and could be used more elsewheres later if needed. You can keep the fan on low while cooling and off when idle to extend cycle time if you're worried about short cycling. But on the other hand, that 5000 one might be working a higher duty cycle than expected with all that added heat, which is non-ideal. That's why I call it a wash.
Answer: I would go larger, I have installed many heating and cooling systems and when the systems are running properly the AC will cycle more often, icing is more of a problem with very high humidity and or low air flow and this can happen even in the desert on a hot day if the filters are dirty reducing the air flow while the system is working at its maximum cooling capacity.
I find customers are happier being able to turn the thermostat up a little verses when the room is still hot with the AC at its lowest setting running full blast. An over sized unit may cost a little more because it may cycle the compressor on and off more often but this cost will be a small percentage of the annual cost to run and you have a better chance of keeping the room comfortable.


Erdős-Rényi model, network reliability

Question: I recently came across the Erdős-Rényi model random graph model, which indeed fascinated me with its beauty and simplicity. I've started to dig into it and saw the following theorem (listed on Wiki, for instance):
Let $G(n, p)$ be a random graph containing $n$ vertices, then the following holds, for $p=\cfrac{c\cdot \log{n}}{n}$:

if $c > 1$, then graph will asymptotically almost surely be connected;
if $c < 1$, then graph will asymptotically almost surely have some isolated vertices and asymptotically almost surely be disconnected

The question is, what can we say about $c=1$? Is there anything interesting to say about this parameter value?
I would appreciate any response.
Answer: When
$$
p=\frac{\ln n}{n}+\frac{s+o(1)}{n}
$$
for some fixed $s\in \mathbb{R}$,
$$
\mathsf{P}(G(n,p)\text{ is connected})\to e^{-\exp(-s)}.
$$
(see, e.g., Theorem 7.3 here).

Erdős-Rényi model, network reliability


SQL Query - Summarising values, Group by and Having clause

Question: I have a database table named car with the schema Car(maker, model, type).
I am trying to find a SQL query that finds out makers who produce only the models of the same type, and the number of those models exceeds 1.
I am a beginner to SQL and have tried the query
select maker, type
from car
group by maker, type
having count(model) > 1

But it yields wrong results. Any help will be highly appreciated.
Thanks
Answer: You need to use CAPITALISED letters for instructions:
Try this:
SELECT maker, type
FROM car
GROUB BY maker, type
HAVING COUNT(model) > 1;

And also let's not forget about the semicolon at the end.


SQL print counts row wise with conditions inside count

Question: I'm new to SQL. I have a table with data as below
+-----+-------+
|Name | value |
+-----+-------+
|AAA  |  25   |
|AAA  |  60   |
|BBB  |  40   |
|BBB  |  200  |
|CCC  |  1010 |
|CCC  |  451  |
|CCC  |  45   |
|DDD  |  20   |
+-----+-------+

What I'm trying to do is get the below output
+-------+-------+
|Name   | COUNT |
+-------+-------+
|AAA    | 2     |
|DDD    | 1     |
|OTHERS | 5     |
+-------+-------+

How can I achieve this in SQL??? Thanks in Advance
Answer: You can use a conditional expression:
select
    case when name = 'AAA' then name else 'OTHERS' end new_name,
    count(*) cnt
from mytable
group by case when name = 'AAA' then name else 'OTHERS' end

Some databases (namely, MySQL and MariaDB) support reusing column aliases defined in the select clause in the group by clause, so you can simplify the group by clause as:
group by new_name

Other databases support positional parameters (Postgres and Oracle are two examples):
group by 1

Comment: Thanks. Will try it out. Is it still same even If I try with more rows? Have edited my question with more data
Comment: That's a slightly different expression: `case when name in ('AAA', 'DDD') then name else 'OTHERS' end new_name`


probability of having an ace on each hand when dealing $52$ cards to $4$ hands

Question: The question from DeGroot's book: "probability and statistics"
"Suppose that a deck of $52$ cards containing four aces is shuffled thoroughly
and the cards are then distributed among four players so that each player
receives $13$ cards. We shall determine the probability that each player will receive one ace."
I so far have $3$ methods to solve this problem, all of them yield the number provided in the book. Below is my $4$th method. Alas, it doesn't give the same answer:
Since the question doesn't concern which suit of ace goes to which hand, and the differences between remaining cards are irrelevant, I simplify the question as:
"Distribute $52$ cards containing $4$ A's and $48$ B's to $4$ piles so that each pile
receives $13$ cards. determine the probability that each pile will receive one A."
to solve this simplified question, I focus on distribution of the $4$ A's, then distribute the $48$ B's to $4$ piles to make each $13$-card pile:

there is only $1$ way to distribute $4$ A's to $4$ piles.
I summed up below sets of outcomes to compute the sample space:

number of combinations that one hand get all $4$ A's: $4$
number of combinations that one hand get 3 A's: $4\times3$
number of combinations that $2$ hands each get $2 $A's, the other $2$ hands get  0 A: 6
number of combinations that one hand get $2$ A's, two other hands each get $1$ A: $12$
number of combinations that each hand get $1$ A: $1$
So, here is the number:
$\frac{1}{35}=0.0286$
which is about $3.7$ time smaller chance than the "correct answer" ($0.1055$).
Why does this way of counting not work ?
Thanks!
P.S.
==================================
I think the first method given by the author partially applied this simplification: it doesn't distinguish different suit of aces.
the method is:
The number of possible different combinations of the four positions in the deck
occupied by the four aces is $\binom{52}{4}$. and there are exactly $13^4$ of combinations for each ace in each player's hand. the result is:
$$P=\frac{13^4}{\binom{52}{4}}= 0.1055$$
Answer: Your simplification doesn't work. Without the simplification, there are $24$ ways to give each player an ace while there are four ways to give all aces to one person. Your simplification skews this relation, and thus the probability.
Comment: I'm aware of this. but the book stated that:
"If we have the choice between whether or not to count
the same elements in different orders as different outcomes, then we need to make
our choice and be consistent throughout the problem. If we count the same elements
in different orders as different outcomes when counting the outcomes in S, we must
do the same when counting the elements of E. If we do not count them as different
outcomes when counting S, we should not count them as different when counting E.". It suggest that it's ok as long as you use the same counting method for E and S.
Comment: as far as the question's requirement is concerned, it sounds a valid simplification.
Comment: "as far as the question's requirement is concerned, it sounds a valid simplification. "  It does?!?!?!?  Seriously?  There are 24 ways to distribute 4 cards to four different piles based on which ace goes to which piles but you equate those all.  So when you distribute all for cards to one hand why do you *then* distinguish which player gets it.  Shouldn't there be only one way?  Either a player gets them all or ... not?  And how can you justify the claim the likely hood of Bill getting 4ace is exactly the same as the liklihood of Sam getting 3 aces and Jill getting 1?
Comment: When it comes to simplification "sounding" like a valid simplification is not enough.  You must prove and demonstrate it is valid.  In math everything is invalid until proven valid.  Not the other way around
Comment: points taken. the fact is, the question doesn't distinguish the suit of ace and the same goes for the rest of the deck (non-ace's). and the order of the 13 cards doesn't matter. it only recognize aces and non-aces. and I think that's it. the assumption for the 3 "correct" answers I have is my eyes must always care both the number (A2..JQK) and suite of each combination of 13 cards, which is not a requirement of the question itself...I'm now suspecting those "correct" answers might not be actually correct.
Comment: as far as I understand, there is no way to validate a answer to a probability question other than  logical deduction from axioms. the likelihood of Bill getting 4 aces, the likelihood of Sam getting 3 aces and Jill getting 1 are calculated based on method counting...
Comment: @fleablood: I should qualify my previous words as: there are ways to validate counting questions (by hand, by computer, etc). as for "why do you then distinguish which player gets it", it does make sense to treat the players as identical. the different result is caused by different experiment setup -> different observation. the key thing needs to be understood is why we need to care about the suits of the card when counting. the question only care about ace and non-ace. I tend to assume that in this kind of questions, if you don't car about the difference, then the difference doesn't exist.
Comment: @fleablood: I finally get your point. thank you very much!
Answer: Your are assuming that all the possibilities you list are equally probable.  This is not true.  There are about twice as many ways to distribute the remaining cards when each person gets an ace than when one person gets four aces.
Comment: thanks. but the book seemed to suggest that counting method doesn't matter as long as consistent counting method for E and S...(see page 53 of the book. I also quoted in the comment above)
Answer: The first Arc can be placed anyhwere, the second only have 39 possible positions, the third 26, the last 13. Thus,
 the answer $\frac{52*39*26*13}{52*51*50*49}$.
Comment: this answer is correct
Answer: It is much harder to determine the probability using the given approach :
The number of possibilities for the distributions are :
$4-0-0-0 : \frac{48!}{13!\cdot13!\cdot13!\cdot9!}\cdot 4$
$3-1-0-0 : \frac{48!}{13!\cdot13!\cdot12!\cdot10!}\cdot 12\cdot 4$
$2-2-0-0 : \frac{48!}{13!\cdot13!\cdot11!\cdot11!}\cdot 6\cdot 6$
$2-1-1-0 : \frac{48!}{13!\cdot12!\cdot12!\cdot11!}\cdot 12\cdot 12$
Just for completion :
$1-1-1-1 : \frac{48!}{12!\cdot12!\cdot12!\cdot12!}\cdot 24$
If you add the first $4$ of the above numbers and divide the sum by the total number of possibilities, you get the probability that not every player receives exactly one ace. The desired probability is $1$ minus that probability.
I will leave it as an exercise to find out how the numbers are determined.
Comment: OP knows the correct answer and has asked why his technique does not yield it.
Comment: if I understand correctly, your counting is based on these assumpitions:
1. suites matter
2. number matter
3. order matter
Answer: I simplified the question below:
"spread 4 aces into 4 pile, so for each ace, it have 4 position to stand, the length of sample space will be 4*4*4*4. and only 1 way to get each position have one ace. the probability will be 1/4*4*4*4 = 0.00390625."
Comment: this answer is wrong.


Friend Class across the Namespace not working in Xcode Cpp (macos dynamic library)

Question: classA.h:
#pragma once
#include "classC.h"

using namespace Bname;

namespace Aname
{
    class  A
    {
        friend class B;
    private:
        void Aclassmethod();
    };

}

classB.h:
#pragma once
namespace Bname
{
    class B
    {
    public:
        void Bclassmethod();
    };
}

classC.h:
#pragma once
namespace Bname
{
    class C
    {
    };
}

classA.cpp:
#include "classA.h"

void Aname::A::Aclassmethod()
{
}

classB.cpp
#include "classB.h"
#include "classA.h"

void Bname::B::Bclassmethod()
{
    Aname::A *vv = new Aname::A();
    vv->Aclassmethod();            **ERROR**// Aclassmethod is a private member of Aname::A
}

I try to compile the code for macos as dynamic library ,The code is Getting compiler error in Xcode cpp (Accessing private Member of class),But Its Properly Compiling without any error in Visual studio.
Comment: On a side note `using namespace Bname;` don't. You pull the whole namspace B into the global namespace. Rather add `using B::B;` in namespace A, or even just `friend class B::B:`.
Comment: I cant able to do that,because i am not included the classB.h in classA.h
Comment: That indicates you are doing something wrong: see answer below. And why are you including `classC.h` in `classA.h`? If you don't directly use it, don't include it.
Answer: In classA.h, when you write friend class B;, there is no way for the compiler to know that you mean Bname::B and not any other B.
An unqualified B like here, will be assumed to belong to the namespace of your line, so the meaning of your line is actually friend class Aname::B.
So change that line to friend class Bname::B and you are (almost) good. Now you will get a complilation error because Bname::B is not seen from A. This can be solved by forward declaring Bname::B in the top of classA.h:
namespace Bname {
class B;
}

So to conclude, change classA.h to:
#pragma once
#include "classC.h"   // This doesn't seem necessary

namespace Bname
{
   class B;
}

namespace Aname
{
    class  A
    {
        friend class Bname::B;
    private:
        void Aclassmethod();
    };

}

Comment: haha, was just writing this at this moment. You were faster. and extra virtual +1 for the class C remark (welcome to stackoverflow. great first contribution)
Comment: Its working,Thanks for your quick response.


Terminal PATH has disappeared OSX - how to reset?

Question: Something has happened to my $PATH variable -- how do i reset it to its initial settings?
If I run the command
$ cat /etc/paths
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin

Then this is all correct. But when I run the command
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.7/bin:/Users/sdev/Library/Enthought/Canopy_64bit/User/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/bin:/usr/bin:/usr/bin:/bin

I tried to fix this by using
export pathname

Need to restore to what it ought to be: I should just have this pathname when i run echo $PATH. I uninstalled Canopy which I thought would solve the problem.
/usr/bin

Answer: If you want to reset your PATH back to just /usr/bin/ put this in ~/.bash_rc
export PATH="/usr/bin/"

Or whatever you want between the quotes. Then you can run source ~/.bash_rc in terminal and the path will be set to what you set it as in .bash_rc.


Mysql index usage issues

Question: Mysql is installed based on docker, the specific version is MYSQL_VERSION=8.0.25-1debian10

Table Structure
CREATE TABLE `test_index` (
    `id` bigint unsigned NOT NULL AUTO_INCREMENT,
    `my_id` varchar(100) NOT NULL COMMENT 'ID',
    `name` varchar(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

Table Data
select * from test_index;
+----+-------+-----------+
| id | my_id | name      |
+----+-------+-----------+
|  1 | 1     | test name |
+----+-------+-----------+

Question statements
Please pay attention to the execution result of explain: possible_keys and key。
For the my_id column in test_index, there is no index, why it is used as a condition in the update statement, which uses the PRIMARY index?
Out of confusion, I did execute the delete statement operation with the same conditions, and the result of the execution was the same as I initially expected, without using any indexes.
What is the underlying rationale for using indexes differently for statements with the same conditions or why they are used? Looking for your help, thanks!

Modify statement
explain update test_index set name="update name" where my_id=1;
+----+-------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table      | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra       |
+----+-------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
|  1 | UPDATE      | test_index | NULL       | index | NULL          | PRIMARY | 8       | NULL |    1 |   100.00 | Using where |
+----+-------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+

Delete statement
explain delete from test_index where my_id=1;
+----+-------------+------------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table      | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+------------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | DELETE      | test_index | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    1 |   100.00 | Using where |
+----+-------------+------------+------------+------+---------------+------+---------+------+------+----------+-------------+

Answer: Short answer: it could have been different. And it might depend on the number of records.

UPDATE: no suitable index found, using the primary index.
No need to use the primary key's index, but the index is available anyhow.
May work better when the table is modified concurrently.

DELETE: no suitable index found, not using any index.
Here the primary key's index is changed, maybe several records with the same my_id are deleted. So instead of doing the index change piecewise, it  is better rebuild the primary key's index once.
Comment: @Akina thanks, that is what I meant; I'll change "loaded" to "available."
Comment: First of all, thank you. * UPDATE: no suitable index found, using the primary index. * DELETE: no suitable index found, not using any index. Is the above description for all cases of MySQL? After adding some data to the table, I tried the above operation again and the situation is the same. I also executed the query and the result was the same as the deletion, whether the query also follows the same guidelines as the deletion
Comment: An update might be better safe-guarded against concurrency, hence using an index. A query does not need that. But I agree, we are trying to find logic, where it just might have been two different programmers. ;)

Mysql index usage issues


Installing angular/core peer dependency

Question: I recently have tried Angular 9.0.0-rc.7, but as a result are am seeing a lot of messages to install the peer dependencies of earlier Angular versions, for example:
email@example.com requires a peer of @angular/core@^7.0.0 || ^8.0.0 || ^9.0.0 but none is installed. You must install peer dependencies yourself.

Usually for a peer dependency, I would do a command such as:
npm install <package> --save

However, do I really want to do that if it's major angular components like angular/core?  Will that just increase the size of the build?
Answer: The modules required for development of you application are used for development phase only. If you have module with size 10MB that does not mean it will get in build.
The size of build is totally dependent on how many imports have you used. If you check currently your node_modules folder will be more than 200MB, but after building angular project, the dist directory will be just in few MB.
You can have any number of dependencies in node_modules, as long as you are not using them, it wont take space in build.
Comment: You can post the answer, if it adds something to the discussion, it will definitely help the OP.
Answer: Why not take the relevent primeng verions instead that matches the angular version you are using? I assume your angular core modules are fairly lower. But the version of primeng you are trying to use is a release candidate version(firstname.lastname@example.com) which is newer than your angular version. If you pick the relevent primeng version which matches your version you dont want to go through installing peer dependencies. Also agreeing to the what @Plochie said above. You can consider this going forward to use the primeng version that matches your project.

Installing angular/core peer dependency


How to refer button name using mutual events in WinForms?

Question: I have a simple code below and I want, if button1 clicked then textBox changed to button1 is clicked. And if button2 clicked then textBox changed to button2 is clicked.
But I want to refer current function's name (button1_Click or button2_Click).
In Form1 [Design] page. In there, Events page using little arrow mutual events.
using System;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = this.Name + "is clicked";
                // "this" isn't work. I think it'd Form1. How to button1 and button2
        }
    }
}

Answer: The sender parameter contains the details you want, you just need to first cast it to a Button
this.textBox1.Text = (sender as Button).Text;

Ideally you would actually implement null value checking, just in case the method is used elsewhere by something which is not as button!  Then you would have
if ((sender as Button) != null)
    this.textBox1.Text = (sender as Button).Text;

Make sure that the same click event is added to every button where you want this functionality.


Majesty 2, how to dissolve a heroes party

Question: I would like to add new members to an existing heroes party when a hero of this party dies. Or kick out members of an existing party. Is this possible? Can I dissolve / delete / cancel a party completly?
Comment: Answres don't belong in the question.  This is strictly for your question.
Comment: I did not put an answer to my question, but used more words for the question. To improve the ability of google to find this questions. Dissolve is harder to understand than delete.
Answer: From both the Gamefaqs forums and the official forums, here is the way of disbanding your party:

Go to the party list click on the star for that party and then there
  is an option to disband in the box at the bottom of the screen.

It seems though that it is not possible to dismiss only 1 heroe: you have to disband the party completely.
Sources:

Gamefaqs forums
Paradox Interactive forums


pgettext in jinja2 django templates

Question: I have configured the Jinja environment with env.install_gettext_translations(translation, newstyle=True) and the jinja2.ext.i18n extension.
I can only use the _(), _gettext() and ngettext() functions in my jinja2 templates.
I want to use pgettext() (django docs) as well to add a context to the translatable strings. Is there an extension that does this, or am I missing something?
update: I have posted a feature request #793. I would still like to know whether there is an answer that can be used right now.
Answer: I don't believe that what you want exists in Jinja... (at least for now)
If you take a look at this issue the developer pretty much states that he won't do it:

This would require patches as I'm not using pgettext myself.

Then he closed the issue.
This was created back in 2014 and something may have changed but I don't think so (based on another issue).
By searching a bit around I found this project which may help: https://pypi.python.org/pypi/jinja2-django-tags/0.1. There I read:

You can also use _, gettext and pgettext directly:
Simple example: {{ _('Hello World') }}
More verbose: {{ gettext('Hello World') }}
With context: {{ pgettext('Hello World', 'another example') }}

Good luck :)

pgettext in jinja2 django templates


"Open" Method Error with ADO Connection in Excel/Access

Question: I keep getting an error when trying to open a database using an ADO connection in VBA - I am getting the following error:
Run-time error '-2147467259 (80004005)':
Method 'Open' of object '_Recordset' failed
I have checked an re-checked all of my file paths and syntax, and cannot find what is wrong with the code below - can anyone help?
Public Sub PlainTextQuery()

Dim rsData As ADODB.Recordset
Dim sConnect As String
Dim sSQL As String

Dim sCusip As String

sCusip = Trim(Range("cusip").Value)

' Create the connection string
sConnect = "Provider=Microsoft.ACE.OLEDB.12.0; " & _
    "Data Source=C:\Users\intern\Documents\NewStuff\ResiOffers_v1.accdb;"

' Create the SQL statement
sSQL = "SELECT Date, Cusip, Bond, OF, CF, Dealer, Price, Matcher, DayCount, MktValue " & _
    "FROM ResiOffersColor " & _
    "WHERE Cusip = 16163HAE1 " & _
    "ORDER BY Date;"

' Create the recordset object and run the query
Set rsData = New ADODB.Recordset
rsData.Open sSQL, sConnect, adOpenForwardOnly, _
    adLockReadOnly, adCmdText

' Make sure we get records back
If Not rsData.EOF Then
    ' Dump the contents onto the worksheet
    Sheet2.Range("A2").CopyFromRecordset rsData
    ' Close the recordset object
    rsData.Close
Else
    ' Close the recordset object
    rsData.Close
    MsgBox "Error: No records returned.", vbCritical
End If

' Destroy the recordset object
Set rsData = Nothing

End Sub

Answer: Whomever is executing the function must have write access to the directory because ms-access is going to try to create a lock (ldb) file.
Comment: Thanks for the reply - I just got the code working by putting brackets [] around each of my field names in the SQL query string...but now have a new problem - no records are printing in my excel workbook.  I am not getting the "no records returned error", so it seems that something is wrong with my attempt to print the records, not in retrieving the records...
Answer: The problem here is the sSQL statement.
This line:
"WHERE Cusip = 16163HAE1 " & _

Should be replaced with:
"WHERE Cusip = '16163HAE1' " & _

In SQL, you enclosed string or text with ' (apostrophe).


Counting the execution of terminating conditions in Fibonacci series

Question: Following pseudo-code, which computes the n-th Fibonacci number:
int fibonacci(int n)
{
    if (n == 0){
        print(0)
        return 0
    }
    if (n == 1)
    {
        print(1)
        return 1
    }
    return fibonacci(n - 1) + fibonacci(n - 2)
}

If one calls fibonacci(3), then the following will happen:

fibonacci(3) calls fibonacci(2) and fibonacci(1) (the first call).
fibonacci(2) calls fibonacci(1) (the second call) and fibonacci(0).
The second call of fibonacci(1) prints 1 and returns 1.
fibonacci(0) prints 0 and returns 0.
fibonacci(2) gets the results of fibonacci(1) and fibonacci(0) and returns 1.
The first call of fibonacci(1) prints 1 and returns 1.
fibonacci(3) gets the results of fibonacci(2) and fibonacci(1) and returns 2.

In total, 1 will be printed twice and 0 will be printed once.
Objective is to know how many times 0 and 1 will be printed for a given integer N.
INPUT
The first line contains an integer T, denoting the number of test cases.
The next T lines contain an integer N.
OUTPUT
For each test case, print one line of output which contains 2 integers separated by a space. The first integer is the number of times 0 is printed. The second integer is the number of times 1 is printed.
CONSTRAINTS
1 <= T <= 50
0 <= N <= 40

SAMPLE INPUT
2

0

3

SMAPLE OUTPUT
1 0

1 2

Code
public class Fibonacci {

    /**
     * @param args
     */
static int zero =0,one = 0;
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] input = readInput();
    for(int i =0; i < input.length;++i) {
        System.out.println(getOutput(input[i]));
    }
}
public static int[] readInput() {
    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
    String temp;
    int[] input = null;
    try {
        temp =bufferReader.readLine();
        int counter = Integer.parseInt(temp);
        input = new int[counter];
        for(int i =0 ; i < counter ;++i)    {
            input[i] =Integer.parseInt(bufferReader.readLine());
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return input;
}
public static String getOutput(int number)  {
    //System.out.println(fibonacci(number));
    return zero+" "+one;
}
public static int fibonacci(int n) {
    if (n == 0) {
        //System.out.println(0);
        ++zero;
        return 0;
    }
    if (n == 1) {
        //System.out.println(1);
        ++one;
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

This works fine for 1st test case but fails for subsequent test cases.
Answer: I think you need to reset the values of zero and one before calling getOutput.
    for(int i =0; i < input.length;++i) {
        zero = 0;
        one = 0;
        System.out.println(getOutput(input[i]));
    }


How to apply wallpaper over styrofoam?

Question: I live in an attic, and the head part of my bed is in a corner where the roof slope, an outer wall and the wall to the neighbour's unheated attic meet. After a few winters of waking up to the feeling of the roof slope sucking the warmth out of me, I got a pack of polystyrol inner wall insulation. Unlike traditional styrofoam, it is a homogenous foam on the inside, similar to polyurethane foam. On the outside, it has a matte finish with a very fine paint-like structure.
I nailed the plates to the wall, right over the existing structured wallpaper. Then I filled the seams and the nail heads with acrylic caulk. Now I'd like to give it a finished look.
I feel adventurous enough to try a wallpaper. I have never applied wallpaper before, but it seems that the new cellulose-fleece-backed type is very easy to work with.
The problem is that the Internet tells me that regular wallpaper glue won't stick to regular styrofoam. I didn't find information specific to the glue for cellulose-backed wallpaper, or about this finished styrofoam. I also found the information that wallpaper can be applied to styrofoam in the following order:

a layer of styrofoam glue, left to dry out
a layer of underwallpaper soaked in normal wallpaper glue
a layer of standard wallpaper, applied in the standard soak-in-glue method

This information came from the site of Henkel, manufacturers of styrofoam glue which costs 7 Euros per kg, an amount which only suffices for 1-2 square meters of wall.
Before I pay for glue two times as expensive as the styrofoam below it and three times as expensive as the wallpaper above it, I'd like to know:

Is a base layer of styrofoam glue the only way to get wallpaper to hold to the styrofoam?
Do I really need an underpaper layer if I am using a cellulose-fleece wallpaper as opposed to a standard one? Does it help hold the real wallpaper to the styrofoam, or is it just to give a nicer look?
All articles I read agree that it is possible to paint over styrofoam using regular water-based inner wall paint. Could I paint over the styrofoam and apply wallpaper to the paint? It would cost three times less than the styrofoam glue.

This is what the caulked styrofoam looks like right now:
Comment: There might be some fire safety concerns with exposed Styrofoam. With XPS foam, for example, it needs to be covered with drywall to protect it from fire.
Comment: +1 on what Steven said. Styrofoam needs to be covered with a non-flammable material such as drywall.
Answer: You should not do this.  Foam insulation (EPS, XPS, etc.) needs to be covered with drywall in order to protect it (extend the amount of time before it melts) from fire. Otherwise you are risk of being exposed to toxic fumes and melting foam should you ever have a fire. Imagine molten foam dripping from your ceiling onto you - not a situation you want to find yourself in.
The correct "solution" is to drywall on top of the foam (using furring strips, or long screws into the studs), mud/tape the drywall, prime, and then apply wall paper using standard wall paper adhesives.
Answer: do you have drywall over in Germany?  i would do a little framing (probably with metal studs, that's used in Europe), insulation inside, then drywall over and wallpaper over drywall.
Comment: Is this styrofoam approved as a wall covering? I'm thinking about fire safety. You may be required to cover it with something like drywall.
Comment: This sounds like it will be much more effort and cost than applying a layer of styrofoam glue and a wallpaper over it. I am looking for a quick and easy finish, don't want to rebuild half the wall.
Answer: Cellulose wallpaper glue works fine
I've just finished (two months ago) gluing polystyrene insulating tiles to my bedroom walls with normal wallpaper glue i.e. cellulose.  Then I stuck on a layer of wallpaper with cellulose wallpaper glue and it has all worked perfectly.
So I do not think you need to use any special glues.  If you 'size' (prepare) the tiles first by painting on a very thin, watery layer of wallpaper cellulose glue and let it dry, you get excellent adhesion with ordinary wallpaper adhesive.  I am a perfectionist, and I can tell you that the end result looks excellent!
Answer: Going back to the original question, it is true that the glue that is activated on the back of pre-pasted wallpaper is probably not enough to make it stick to the wall. Most pre-pasted wallpapers come with instructions advising to SIZE the walls before  wetting the wallpaper strip and THEN use a brush to add wallpaper glue (I can't remember if that is what it's called...quart size bucket of stuff that is thicker than the sizing but not as thick or sticky as Elmer's glue). I realize now that this was from a year ago, but oh, well.

How to apply wallpaper over styrofoam?


Apache Tomcat Windows stdout/stderr configuration

Question: Like many other members before me, I have some questions surrounding configuring Apache Tomcat logging on Windows.  To be more specific, my questions surround the proper method(s) for limiting the size and number of log files that are created for stderr/stdout of the Apache Tomcat server as a whole.
My Java knowledge is pretty much limited to whatever I've been able to find on the web in searches.
What I believe I understand is this:
The Apache Tomcat service on Windows defaults to the -std(out|err).yyyy-mm-dd.log
The Apache Tomcat service uses the following options in the Java startup definition:
  -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
  -Djava.util.logging.config.file=<tomcat_home>\conf\logging.properties
The Apache Tomcat service defines the majority of its core logging options within the logging.properties file.
Is there a proper configuration/directive/option that can/should be added to the logging.properties file to limit the size, number, count, etc. of the std(out|err) log files?
My main confusion is with how the loggers and handlers are defined within the logging.properties file with respect to the Tomcat service itself.
If this has been answered in another thread that I didn't find before posting this, please redirect me.  I have tried to follow along with Apache's documentation for logging (https://tomcat.apache.org/tomcat-9.0-doc/logging.html) but I don't know if I can simply add options like maxDays, count, and maxCapSize (or whatever the appropriate option and value should be) directly into the <tomcat_home>\conf\logging.properties file or if I have to use a different way?
Any help or direction that gets me to a better understanding of this and how to accomplish my end goal of limiting the number and size of std(out|err) log files is and will be greatly appreciated!
Thanks!
Greg
Comment: Almost 2 weeks with no activity.  Anyone have any suggestions or redirection to other posts that might be able to help answer my question?  Thanks!
Answer: According to Apache Tomcat 9 Windows Service How-To There are only the following options:
--LogPath   %SystemRoot%\System32\LogFiles\Apache   Defines the path for logging.  Creates the directory if necessary.
--LogPrefix commons-daemon  Defines the service log filename prefix. The log file is created in the LogPath directory with .YEAR-MONTH-DAY.log suffix
--LogLevel  Info    Defines the logging level and can be either Error, Info, Warn or Debug. (Case insensitive).
--StdOutput     Redirected stdout filename. If named auto then file is created inside LogPath with the name service-stdout.YEAR-MONTH-DAY.log.
--StdError      Redirected stderr filename. If named auto then file is created inside LogPath with the name service-stderr.YEAR-MONTH-DAY.log.

Looks like for deleting of files you would have to create a scheduled task to do so.
Comment: I've added these options to the Service definition in Windows (tomcatw.exe //ES//

-Djava.util.logging.config.file=E:\Apps\Apache Software Foundation\Tomcat 9.0.11\conf\logging.properties
-Djava.util.logging.FileHandler.limit = 10240000
-Djava.util.logging.FileHandler.count = 10
-Djava.util.logging.FileHandler.append = false

It appears to at least keep the stdout/stderr files in check. If no one else has a better/different answer, I'll mark this question as answered.
Comment: The above configuration in service definition is not working, is there any other alternative?
Comment: @Beschi Open a new question as we'll need more background on what [not working](https://stackoverflow.com/help/how-to-ask) means.  One alternative is listed in the existing answer.  As you can see in the answer the Tomcat service itself has only a few tuning options and nothing to deal with deleting of stdout and stderr files.