How to change decimal places of a factor variable in ggplot2?

Question: I would like change decimal places on x and y axis to two instead of one. For example, I need 17.11 instead of 17.1. The problem is my x and y axis are factor variables, so I can't seem to change the decimal places. I tried to convert mean_temp and total_count to numeric, but got NAs.
Here is the heatmap

Here is the reproducible example used to create the above figure
df <- structure(
  list(
    total_count = c(
      10L,
      0L,
      15L,
      0L,
      20L,
      0L,
      0L,
      50L,
      0L,
      6L,
      1L,
      10L,
      7L,
      0L,
      0L,
      29L,
      0L,
      2L,
      11L,
      3L,
      0L,
      12L,
      0L,
      30L,
      0L,
      0L,
      29L,
      44L,
      10L,
      5L,
      2L,
      145L,
      0L,
      70L
    ),
    mean_temp = c(
      18.87,
      18.87,
      18.87,
      18.87,
      18.87,
      18.87,
      18.87,
      18.87,
      18.87,
      21.85,
      21.85,
      21.85,
      21.85,
      21.85,
      21.85,
      21.85,
      21.85,
      21.85,
      17.11,
      17.11,
      17.11,
      17.11,
      17.11,
      17.11,
      17.11,
      17.11,
      18.82,
      18.82,
      18.82,
      18.82,
      18.82,
      18.82,
      18.82,
      18.82
    ),
    lwd_duration = c(
      64.32,
      64.32,
      64.32,
      64.32,
      64.32,
      64.32,
      64.32,
      64.32,
      64.32,
      104.2,
      104.2,
      104.2,
      104.2,
      104.2,
      104.2,
      104.2,
      104.2,
      104.2,
      53.53,
      53.53,
      53.53,
      53.53,
      53.53,
      53.53,
      53.53,
      53.53,
      60.43,
      60.43,
      60.43,
      60.43,
      60.43,
      60.43,
      60.43,
      60.43
    )
  ),
  row.names = c(NA,-34L),
  class = c("tbl_df", "tbl", "data.frame"),
  na.action = structure(
    c(
      `4` = 4L,
      `5` = 5L,
      `6` = 6L,
      `7` = 7L,
      `8` = 8L,
      `9` = 9L,
      `78` = 78L,
      `87` = 87L,
      `96` = 96L,
      `105` = 105L,
      `114` = 114L,
      `123` = 123L,
      `132` = 132L,
      `141` = 141L,
      `150` = 150L,
      `159` = 159L,
      `168` = 168L,
      `177` = 177L,
      `186` = 186L,
      `849` = 849L,
      `850` = 850L,
      `851` = 851L,
      `852` = 852L,
      `891` = 891L,
      `892` = 892L,
      `893` = 893L,
      `894` = 894L,
      `921` = 921L,
      `922` = 922L,
      `923` = 923L,
      `924` = 924L,
      `937` = 937L,
      `938` = 938L,
      `939` = 939L,
      `940` = 940L,
      `969` = 969L,
      `970` = 970L,
      `971` = 971L,
      `972` = 972L,
      `985` = 985L,
      `986` = 986L,
      `987` = 987L,
      `988` = 988L,
      `1017` = 1017L,
      `1018` = 1018L,
      `1019` = 1019L,
      `1020` = 1020L,
      `1033` = 1033L,
      `1034` = 1034L,
      `1035` = 1035L,
      `1036` = 1036L
    ),
    class = "omit"
  )
)

Code used to create the figure
dat2 <-
  df %>%
  as_tibble() %>%
  mutate(
    mean_temp = cut_interval(mean_temp, n = 10),
    total_count = cut_interval(total_count, n = 10),
  ) %>%
  group_by(mean_temp, total_count) %>%
  summarize(lwd_duration = mean(lwd_duration))
#> `summarise()` has grouped output by 'mean_temp'. You can override using the
#> `.groups` argument.

ggplot(dat2, aes(mean_temp, total_count)) +
  geom_tile(aes(fill = lwd_duration)) +
  geom_text(aes(label = round(lwd_duration, 1))) +
  scale_fill_gradient(low = "white", high = "red")

Note: I'd be happy with whole numbers too, if changing decimal places is not possible. The main objective is to ensure uniformity and consistency among the values displayed on both the x and y axes, as the complete figure contains both one and two decimal places (I cannot paste the entire dataset here due to space constraints). Thanks
Comment: You might look at `dig.lab` parameter for the call to `cut_interval()`?
Comment: @langtang what value do I set `dig. lab` to? I tried `0.2` but got extremely large numbers on the axes. Thanks
Comment: 2 ? (2 decimals)
Comment: tried 2 as well. Same issue
Comment: its not great, because you have to set to 4, because its the total digits, instead of decimal places. Also, it doesn't use a fixed formatting, so `10` doesn't become `10.00` (it remains as a whole number)
Comment: @langtang yes, it didn't work. `10` became `10.1`, so my problem consistency problem remains.
Answer: To get full control of the appearances, I would probably use string parsing. This includes removal of the brackets, which are helpful from a technical point of view, but often confusing or cluttered on a plot.
library(tidyverse)

dat2 %>%
  ungroup() %>%
  separate(mean_temp, into = c("a", "b"), sep = ",") %>%
  separate(total_count, into = c("c", "d"), sep = ",") %>%
  mutate(across(1:4, ~as.numeric(str_remove(., "\\[|\\(|\\]|\\)")))) %>%
  mutate(across(1:4, ~ sprintf("%.2f", .))) %>%
  mutate(mean_temp = paste(a, b, sep = " - ")) %>%
  mutate(total_count = paste(c, d, sep = " - ")) %>%
  dplyr::select(c(6, 7, 5)) %>%
  ggplot(aes(mean_temp, total_count)) +
  geom_tile(aes(fill = lwd_duration)) +
  geom_text(aes(label = round(lwd_duration, 1))) +
  scale_fill_gradient(low = "white", high = "red")

Comment: @Ahsk I know that - it's just that plots are used for illustration, and this is a subtlety that can usually be skipped over when presenting your .data
Answer: You can set dig.lab (in cut_intevals()) to an integer that is sufficiently high, such as 4 or 5.  Then, you can subsequently use this little function to standardize the labels generated by cut_interval
standardize_cut_levels <- function(l, dig=2) {
  sapply(l, \(s) {
    m = gregexpr("\\d+\\.?\\d{0,}",s)
    m = regmatches(s,m)[[1]]
    r = sub(m[1], trimws(sprintf(paste0("%9.", dig, "f"), as.numeric(m[1]))),s)
    sub(m[2], trimws(sprintf(paste0("%9.", dig, "f"), as.numeric(m[2]))),r)
  })
}

Now, after you create dat2, simply call this function like this:
levels(dat2$mean_temp) <- standardize_cut_levels(levels(dat2$mean_temp))
levels(dat2$total_count) <- standardize_cut_levels(levels(dat2$total_count))

Now your plotting code will produce this:


Is there a name for 'heteroskedasticity' but for shape, skewness or kurtosis of the distribution?

Question: Heteroskedasticity means that the variance of the residuals changes with respect to input variables. Is there a name for an analogous concept where the shape of the distribution, i.e., skewness, kurtosis, or some other aspects, not only the variance changes?
Also, are there some established procedures to measure this in the data?
Comment: How about "conditionally varying _____,"  where ______ can be variance, skewness, kurtosis, modality, etc. ?
Answer: I am no expert on language or greek, I just did some good ol' fashion googling.
'skedastic' derives from (ancient) greek root (to spread/disperse) σκεδάννυμι (see McCulloch 1985). Hetero- also derives from a greek root.
Since kurtosis is also based on a greek root (κυρτός) you could argue for something like heterokurtosis.
Following this line of thought I would suggest heteroloxotic, heteroloxoticity from λοξότητα for skewness
Not quite sure about shape since that is not necessarily a definite statistical term (but rather encompassing things like skewness and kurtosis).
McCulloch", J. Huston (March 1985). "Miscellanea: On Heteros*edasticity". Econometrica. 53 (2): 483. JSTOR 1911250.
Comment: Thanks for your answer. I think this Q is more appropriate here. I want to know how is this called in the field, and not how it could be called. I mean, I am sure English majors can come up with a better name to, e.g., "missing completely at random" concept, but I would still rather know that this is how statisticians call it than how they could have called it.
Comment: We could consider moving this to https://english.stackexchange.com/ or https://linguistics.stackexchange.com/
Comment: In that case I have not seen any specific term for these. I would say something like "the kurtosis of the distributions varies by group"
Comment: yes that make sense, I think even if would use something like heteroloxotic, nobody would understand it anyway
Comment: If you want to actually model this have a look at [tag:gamlss]
Comment: @rep_ho, I mean at someone point Pearson used heteroskedastic and probably nobody knew what he meant. But you sir are probably no Pearson haha


Is There A Way To Remove Kickstart Demo Product Types Without Emptying Database?

Question: Is there are a (safe) way to delete the demonstration Product Types in Commerce Kickstart 2 without the entire Drupal install?
It appears that the Commerce Kickstart 'Reset' function simply empties the entire db. (yikes).
I've read many discussions on this but they tend to go back to 2011. I was hoping there was a more current (and hopeful) answer. We want to get rid of all the 'Drinks', 'Tops', etc. but keep the Products/Types and other content we've created.
Answer: hmm my understanding was that Kickstarter kit was a "hey see what it can do once fully configured!" example of Commerce. Understanding the setup -- you could then go back and install/configure Commerce by hands to your needs.
That being said Commerce content I think is just Entities and Nodes, If you want an non-SQL way to reset a site (i've written ~34 sql Delete statements to nuke content from sites in an sql script for drupal -- it's not that hard you just look at node and field_* tables mostly when clearing content from a drupal site) I'd recommend looking at the Delete All module and the documentation found in drush help delete-all as a GUI means of selecting out types of content to nuke from a drupal site.
EDIT: DrupalCamp Montreal 2014 steps to setting up Commerce ala Commerce Kickstart but Not Depending on the Kickstarter kit
Original source (broken):  http://renaudjoubert.com/en/article/step-step-guide-to-installing-commerce-scratch

Step by step guide to installing Commerce from scratch

The following guide was used in a presentation at DrupalCamp Montreal 2014.
The presentation focused on how to install Drupal Commerce from scratch
(i.e. we won't use the Commerce Kickstart distribution).
This is an elevator guide. So get in now because we're going up!

FIRST FLOOR
https://www.drupal.org/project/commerce
Install required modules
drush dl ctools views entity rules addressfield commerce
drush en ctools views entity rules addressfield commerce -y
Installation instructions
https://www.drupal.org/node/1007434
use the provided drush commands
drush en commerce commerce_ui -y
drush en commerce_customer commerce_customer_ui -y
drush en commerce_price -y
drush en commerce_line_item commerce_line_item_ui -y
drush en commerce_order commerce_order_ui -y
drush en commerce_checkout commerce_payment commerce_product -y
drush en commerce_cart commerce_product_pricing -y
drush en commerce_product_ui -y
drush en commerce_tax_ui -y
Add a few more useful modules
drush dl admin_menu module_filter zurb-foundation-7.x-4.x-dev jquery_update -y
drush pm-disable toolbar
drush en admin_menu_toolbar module_filter jquery_update -y
Create a responsive Zurb subtheme
drush fst Your Subtheme Name your_subtheme_name 'A subtheme of ZURB Foundation.'
Set jQuery update to 1.7+ (admin/config/development/jquery_update)
Enable your new responsive subtheme (admin/appearance)

SECOND FLOOR
Quick tour of what we've got soo far
1 Product type named 'Product'
2 tax types
LOTS of hidden functionnalities
NO visible products
and NO, you don't get a store out-of-the-box
Commerce Kickstart gives you that but you won't know how to get there if you don't try from scratch
Create a new product type 'Download'
add file & image fields
Revisit 'Product', the product type installed by Commerce
add an image field
Let's create products
a physical product (Product)
a virtual product (Download)
Now what? where's the store?
Gotcha!

THIRD FLOOR
Out-of-the-box Store is for wimps! ; )
Commerce products only exist in the backstore
products are like brown boxes in a warehouse: they're only accessible to the store's employees
in order to make products accessible to customers, you need to put them on display in a nice and attractive way
how do we do that in Drupal?
we use content types, of course
Create a content type for displaying products
how does Commerce differentiate & recognize product displays from regular content types?
a product reference field!
create product displays and configure them
Alright, let's shop!
wait a minute, nothing happens when i click Add to cart!
Gotcha!

FOURTH FLOOR
In case you didn't read the fine print: some assembly is required, like Ikea, but without the KISS diagrams
Introducing Rules... doh! where's the UI ?
drush en rules_admin -y
go to admin/config/workflow/rules and add a rule that redirects to the cart
Welcome to the cart
Time to checkout wouldn't you say ?
doh!... something isn't right
where are the taxes?
Like I said, Out-of-the-box taxes are for wimps! ; )
Commerce's taxe model is simple
there are tax types; like there are product types and content types
and then there are tax rates which you create using one of the available tax types
Create GST & PST tax rates (note - these taxes are specific to the Province of Quebec in Canada where the camp was held)
Revisit the checkout
Darn, the taxes are not displayed in the expected order! (i.e. GST on this first row, PST on the second row)
How do we change the order in which taxes are displayed ?
the hard way: by overriding theme_commerce_price_formatted_components() in the theme's template.php (see https://drupal.org/node/1095576#comment-8721217)
the easy way: by creating separate tax types for GST and PST and playing with their respective weight (note that at the time of this writing, the behaviour for tax weights does not follow the convention where lighter weights float to the top; see this issue)
Are we in business yet? Not quite.

FITH FLOOR
Setting up a payment method
for simple tests, use the 'Example payment' module (provided by Commerce)
For serious tests and real sales, you can use Stripe or Paypal or whatever works for you. For the purpose of this presentation,I used Stripe.
www.stripe.com
setup an account
get the API keys (secret and publishable)
Install & configure Stripe
drush dl commerce_stripe
drush en commerce_stripe -y
add both keys to the Stripe payment method rule (admin/commerce/config/payment-methods/manage/commerce_payment_commerce_stripe)
Time for some tests
for this, we use the dummy credit cards provided by Stripe
https://stripe.com/docs/testing
When you're happy that all works like it should you can replace de test API keys by the live API keys.
Done!
Comment: I'm actually about 100% more comfortable with SQL statements if there is a -reasonably- safe way to do this. Please advise. And thanks! The other attempts I've read about -seem- to work, but then there is always a follow-up post of 'gotchas' that don't show up immediately.
Comment: BTW: this may just be -me- being 'old', but I (and my co-workers) find this 'no way to delete demo data' approach unbelievable. We (literally) could not imagine that in 2014 that would be the case. We just assumed that this basic nicety would be in place.
Comment: to answer your first question for the clearing of tables via SQL. For the site I built uses community modules, I simply inventory the table structures and hand write the `Delete` statements as needed. Eg, I'm the developer -- I should understand the schema. For your second question there is no flag that denotes the content as `dummy data` you seem to be assuming that all users will be inserting their own content and running with the kickstarter setup and wanting to clean it out as you are -- that's not strictly true. Your free to submit patches to add the functionality of course :)
Comment: see http://webcache.googleusercontent.com/search?q=cache:Sx2VZSgY_PgJ:renaudjoubert.com/en/article/step-step-guide-to-installing-commerce-scratch%3Futm_source%3Dtwitterfeed%26utm_medium%3Dtwitter%26utm_campaign%3DDrupal%2BUniverse%26utm_term%3D%2523drupal%2B%2523drupalcr+&cd=1&hl=en&ct=clnk≷=us

the site has since moved and the old url i have is broken.
Comment: You may want to follow the above steps (tweaked to your needs) and node_export/uuid module(s) to migrate your existing kickstart site content to a kickstart free Commerce installation. Just a thought.
Comment: Thanks. I've read a couple of articles where the poster removed the demo data via SQL and then it re-appeared again later... along with various errors. This implies that there is some flag in Kickstart that attempts to 'rebuild' the demo data if missing.
Answer: This worked for me:
drush dis commerce_kickstart_product -y
drush vset commerce_kickstart_demo_store 0
drush en commerce_kickstart_lite_product -y

This seemed to allow one to delete the demo product types and such.  Not sure if they are regenerated later or not.
Comment: For deleting basic content types `drush dis commerce_kickstart_product -y
` should be enough. Then just remove them from content types page.
Other commands will also change views and some other predefined settings what you might want to avoid.
Comment: This was so long ago (Thank God!) I've forgotten the details. They will be regenerated later. It's in the Commerce Kickstart Feature.
Comment: I've been working with a setup where I did the above.  It's been a month now of cleared caches, registry rebuilds, cron runs, etc. and they still haven't regenerated.  When I look in Features, I don't even see the Commerce Kickstart Product feature anymore.  It appears to be replaced with Commerce Kickstart Lite Product feature automatically by having done the above.
Comment: The items enabled/disabled above ARE the Features and the Commerce Kickstart Lite Product feature won't regenerate the sample store content since it's the same Feature that is enabled at install if you elect NOT to install the sample store content.
Comment: there's a whole series by the code karate guys which covers this.


Somar de valores de coluna em SQL SELECT

Question: Estou fazendo um Select em que preciso que venham alguns dados :

Cliente
Valor Principal Devido
Valor Multa Devido
Valor Juros Devido
Valor Total Devido
Soma Valor Total Devido

Porém não sei como fazer que em uma linha seja apresentado a Soma do Valor Total Devido. Alguém pode me ajudar? O Script está assim, até então:
SELECT C.NomeCliente,
       C.ValorPrincipal,
       C.ValorMulta,
       C.ValorJuros,
       C.ValorPrincipal + C.ValorMulta + C.ValorJuros AS 'Valor Devido Total'
FROM Cadastro.Cleintes AS C
    JOIN Financeiro.Debitos AS D
        ON D.IdPessoa = C.IdPessoa;

Comment: já tentou utilizar a função [sum()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_sum)?
Comment: Queria o total em uma LINHA.. Seria a Soma de todas as linhas da coluna  Valor Total Devido
Comment: Você quer o total em uma COLUNA (o total de cada linha) ou em uma LINHA (o total de todas as linhas)?
Answer: Altere a linha:
C.ValorPrincipal + C.ValorMulta + C.ValorJuros) AS 'Valor Devido total'

Para:
(C.ValorPrincipal + C.ValorMulta + C.ValorJuros) AS Valor-Devido-total

SELECT C.NomeCliente,
       C.ValorPrincipal,
       C.ValorMulta,
       C.ValorJuros,
       (C.ValorPrincipal + C.ValorMulta + C.ValorJuros) AS Valor-Devido-total
FROM Cadastro.Cleintes AS C
    JOIN Financeiro.Debitos AS D
        ON D.IdPessoa = C.IdPessoa;


Checking to see entry of custom class is in List Array using c#

Question: Ive done alot of searching on the net and on here(foundLOTS of useful entries that helped me out)
In need of help trying to figure something out.
Im currently developing a game for my son.  And I am creating a inventory system.  Im using a List to hold all of the current items in his inventory but its reference to a custom class.
HERE is the class so far for setting up the items.
using UnityEngine;
using System.Collections;

public class Item
{
    public string Name;
    public string Description;
    public int ID;
    public int Type;
    public int Quantity;
    // Use this for initialization
    public Item(string newName, string newDesc, int newId, int newType, int newQty)
    {
        Name = newName;
        Description = newDesc;
        ID = newId;
        Type = newType;
        Quantity = newQty;
    }
}

in my playerstats i have a few items entered just to test things
void SetStartingInventory()
{
    Inventory.Add( new Item("Rookie Ball","Stater Capturing Device",1,1,5));
    Inventory.Add( new Item("Potion", "Replenish 5 health points.",2,2,2));
}

everything will display properly and i know i dont have a proper database setup yet for items this is more along the lines to test things out and find something that works..
im sure there is a better and more organized way to keep this.
ANYWAYS!  for testing purposes i want to press the g button  which is a no brainer i got that.
what i want to do is find if there is already an entry in the Inventory list, that matches say.. "Potion" or its item ID#, if returns true, what is the index of that entry so i could give another potion and incease my quantity by one.
any help and guidance be massively helpful.
Comment: are you familiar with the `string.Contains()` method.. also have you considered using a `List or creating a small class of Item of it's own like CustItem using auto properties` there are HasTables, Dictionary's HashSets, etc... too many different ways to skin this cat..
Comment: also you could have `SetStartingInventory(string name)` accept a string name param as well
Comment: no i havent,  i am realativly new to c# and finding my way pretty decently.. i think at least. just run into a few snags here and there.  ill definitly take a look into  the different approaches you have suggested thankyou !  I have been able to get it to work so far using for() so far but im sure it will get too difficult as i start adding more items into play.
Answer: I suggest you to have a quick look to extension methods provided by Linq to Enumerable collections. It let you query enumerable collections in very simple ways.
For example here's a quick example looking for a potion with an id greater than 20.
using System.Linq;
List<Item> items;

Item[] potionItemWithIdsGreaterThan20 =
  items.Where(i => i.Name.Equals("Potion") && i.ID > 20).ToArray();


Gradle 0.9.2 with Appengine 1.4.2

Question: Is there a Gradle plugin (compatible with Gradle 0.9.2) that'll let me deploy to Google App Engine 1.4.2?
If yes, how can I integrate it (build.gradle snippet)?
Answer: Axel,
today is your lucky day. ;-) I just released a Gradle GAE plugin that provides tasks for uploading, running and managing Google App Engine Java projects. Give it a shot. The
documentation describes setup and convention properties in detail. Let me know if you have feedback or feature requests.
Comment: Hey Benjamin! We are having great results so far! How can I store a password to run gaeUpload from Jenkins (without ever having to input it from the command-line)?
Comment: I "solved" this by running the build once from a shell within the workspace and entering the password by hand.
Comment: Yeah, once you enter it correctly the sign-in credentials get stored as a cookie.
Comment: Awesome! Good to hear. Internally the plugin uses [appcfg.sh](http://code.google.com/appengine/docs/java/tools/uploadinganapp.html) (actually the Java implementation of it) which doesn't provide a way to store the password per se as far as I can see. I asked [this question](http://groups.google.com/group/google-appengine-java/browse_thread/thread/84c0983be6d62565#) on the Google App Engine Java forum. If you know a way to do that please let me know so I can build it in. Right now there's no support for it.
Comment: I now face another issue: how can I execute gaeRun and have it NOT wait? So I can run an HtmlUnit test against the app, and stop the server afterwards.
Comment: That feature doesn't exist yet. Can you open an issue on GitHub? I'll try to working on this as soon as I can.
Comment: The issues have been logged. Did you make any progress?
Comment: I implemented passing in the password. Running the local development server in the background hasn't been implemented yet. I wanted to release both fixes at once. Let me know if the password passin feature is important enough to create a subrelease.
Comment: Yes, that would definitely be great.
Comment: I'd like you to give it a shot before I officially release it. Can you send me a mail? I'd send you the new version then.
Comment: @Axel: Version 0.3 of the plugin has been released. Both requested features are part of this release.
Answer: The Spring Security build uses gradle to deploy a sample app to GAE. You could copy that (see the sample app gradle file), or clone the repo and use it in place as a guide. It uses a simple internal plugin.

Gradle 0.9.2 with Appengine 1.4.2


If I ask $2N$ people a yes or no question, what's the probability $N$ say yes?

Question: Suppose I ask $2N$ people a yes or no question. The answer are independent binomially distributed random variables. Each individual has his own probability of saying yes. When the $i$th responds, he says yes with probability $p_i$. Moreover,
$$\\p_1,p_2,...,p_{2n} \sim Uniform[0,1]$$
and are independently and identically distributed. What is the probability half of the responders say yes?

I know that
$$\int_0^1p dp$$
Is the probability of voting yes for some individual. I'm inclined to express the probability half of the responders say yes as,
$$\\\int_0^1\binom{2N}{N} p^{N}(1-p)^{N}dp.\\$$
But this seems to impose that $p=p_1,p_2,...,p_{2n}$, which doesn't need to be the case.
Comment: I suspect that this is actually quite tricky to answer after seeing a paper that covers this question (https://www.sciencedirect.com/science/article/pii/0022053181900223).
Comment: Have you had a look at the answer I provided?
Answer: I am not entirely sure, but here what looks right to me.
Conditioned on $p=(p_1,\dots,p_{2N})$, what you have is a random variable $X_p$ following a Poisson Binomial distribution with parameters $2N$ and $p$. So what you want is the probability that your random variable $X$ equals $N$, which is
$$
\mathbb{P}\{X=N\} = \mathbb{E}\mathbf{1}_{\{X=N\}} = \mathbb{E}[\mathbb{E}[\mathbf{1}_{\{X=N\}}\mid p]]
= \mathbb{E}[\mathbb{P}[X_p = N]]
$$
From the known expression (cf. Wikipedia article) of the pmf of a Poisson Binomial r.v., we have
$$
\mathbb{P}[X_p = N] = \sum_{A\in F_N} \prod_{i\in A} p_i \prod_{j\in A^c} (1-p_j)
$$
so that, by linearity of expectation and independence of the $p_i$'s,
$$\begin{align}
\mathbb{P}\{X=N\} &= \sum_{A\in F_N}\mathbb{E}\left[\prod_{i\in A} p_i \prod_{j\in A^c} (1-p_j)\right]
= \sum_{A\in F_N} \prod_{i\in A} \mathbb{E}[p_i] \prod_{j\in A^c} \mathbb{E}[(1-p_j)]\\
&= \sum_{A\in F_N} \left(\frac{1}{2}\right)^{\lvert A\rvert}\left(\frac{1}{2}\right)^{\lvert A^c\rvert}
= \frac{\lvert F_N\rvert}{2^{2N}}\\
&= \boxed{\frac{1}{2^{2N}}\binom{2N}{N}}
\end{align}$$
(I followed the notation of Wikipedia, writing $F_k$ for the set of all subsets of $k$ integers that can be selected from $\{1,2,3,\dots,2N\}$).
Comment: This is really clever. It is also intuitive that $\frac{1}{2^{2n}}\binom{2N}{N}$ is decreasing in $N$ (i.e. the probability of an even split should decrease with more degrees of freedom).
Comment: Yes. I reckon that the fact that this matches the probability of a Binomial with parameters $2N$ and $1/2$ is not too surprising in hindsight, due to the uniform distribution and independence of the $p_i$'s which average things out.


Do birth defects in the neck limit the range of some singers?

Question: Some people have a birth defect in their neck, so they can't bend their head up or down as much as other singers can.
Can such singers learn to sing higher pitched notes and lower pitched notes with practice,  or does this birth defect limit their ability to reach very high or very low notes?
Answer: You don't get high notes by bending your head up, or low notes by bending it down!  So, in itself, there's no reason why limited mobility such as you describe should affect singing.


How do I get different user selected SQL tables displayed as an html table using PHP?

Question: I am creating a page that prompts for server login info, and redirects after submitting correct information. Once on the next page, there is a select form with different table names representing tables inside of the database. Once one is selected, and 'select table' is clicked, it is to display the entire table from the database as a table in html by using PHP. I'm not sure how to figure out the number of columns in a sql table to be able to display it using a loop and html table tags.
<?
session_start();
if(!isset($_SESSION['session']))
{
    $_SESSION['session'] = 0;
}
if(isset($_POST['host']))
{
    $_SESSION['host'] = $_POST['host'];
    $_SESSION['dbname'] = $_POST['dbname'];
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['pw'] = $_POST['pw'];
}

?>
<!DOCTYPE html>

    <?
    if(isset($_POST['logout']))
    {
        $_SESSION['session'] = 0;
    }

    if(isset($_POST['submit']))
    {
        try
        {
            $db = new PDO("mysql:host=".$_POST['host'].";dbname=".$_POST['dbname'], $_POST['username'], $_POST['pw']);
        }
        catch(Exception $error)
        {
            die("Connection to user database failed: " . $error->getMessage());
        }

        try
        {
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
            $query = "SHOW TABLES";
            $results = $db->query($query)->fetchall();
            $_SESSION['session']=1;
        }
        catch(Exception $error)
        {
            echo "Problem with ~query, go back to home screen";
            $_SESSION['session']=0;
        }
    }

    if($_SESSION['session'] == 0)
    {?>
    <form action="<?$_SERVER['PHP_SELF']?>" method="post" name='initialentry'>

                Enter host name:

                    <input type='text' name='host' value='localhost'>

                Enter database name:

                    <input type='text' name='dbname' value='zxyx999'>

                Enter user name:

                    <input type='text' name='username' value='zxyx999'>

                Enter password:

                    <input type='password' name='pw' width='15' value='12345'>

                    <input type="reset" value="Reset">

                    <input name='submit' type="submit" value="Submit">

    </form>
    <?}

    if($_SESSION['session']==1)
    {
        ?><form action='<?$_SERVER['PHP_SELF']?>' method='post' name='tableList'>
        <select name='selected'><?
            foreach($results as $row)
            {
                echo "<option value=".$row[0].">" . $row[0] . "</option>";
            }?>
        </select>
        <input type="submit" name="selectTable" value="Select Table">
        <input type="submit" name="logout" value="logout">
        </form><?
    }

    if(isset($_POST['selectTable']))
    {
        try
        {
            $db = new PDO("mysql:host=".$_SESSION['host'].";dbname=".$_SESSION['dbname'], $_SESSION['username'], $_SESSION['pw']);
        }
        catch(Exception $error)
        {
            die("Connection to user database failed: " . $error->getMessage());
        }

        try
        {
            $statement = $db->prepare("SELECT * FROM ".$_POST['selected']);
            $statement->execute();
        }
        catch(Exception $error)
        {
            echo "Problem with ~query";
        }

        echo "
";
        echo "
";

        while($row = $statement->fetch())
        {
            echo $row['book_id'] . $row['title'];
        }

        echo "
";
    }

    ?>

Comment: Possible dubplicate of: http://stackoverflow.com/questions/658395/find-the-number-of-columns-in-a-table
Answer: You can use columncount property of the PDOStatement object after execute() has been called to determine the number of columns in the resultset.
Update: let's see some code
...
$c=$statement->columnCount()-1; //column indexes in resultset are 0 based
while($row = $statement->fetch())
    {
        echo '
'; //start row
        for($i=0; $i<=$c; $i++)
            {
                echo ''.$row[$i] . '	'; //print cell
            }
        echo '
'; //close the row
    }
...

Comment: Honestly, your answer is the most sensible here so far. Please include some example with explanation and I'll upvote.
Comment: Thank you, this was what i was looking for. Now the only thing I have left to do is to get the column names to display from the database. Here's the code I have to create an html table of the table, all it's missing is the column header names:

>   `echo "";
>   echo "";
>
   while($row = $statement->fetch())
   {
    echo "";

   for($i=0; $i < $statement->columnCount(); $i++)
>    {
     echo "" . $row[$i] . "";
    }

    echo "";
   }`
Comment: fetch() will retrieve the column names as well at the default settings of PDO.
Answer: To select the number of the columns of a table you can use this query.
SELECT COUNT(*) AS total_columns
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'selected_table' AND table_schema = 'your_database';

You can find more info about INFORMATION_SCHEMA here.
Comment: Is this correctly formatted?

    `$columns= $db->prepare("SELECT COUNT(*) AS total_columns FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name =" . $_POST['selected'] . " AND table_schema =" . $_SESSION['host']);
   $columns->execute();
   echo var_dump($columns);`

Because I get this output when I run it:

`object(PDOStatement)#3 (1) { ["queryString"]=> string(115) "SELECT COUNT(*) AS total_columns FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name =book AND table_schema =localhost" }`
Comment: No, try this: $columns= $db->prepare("SELECT COUNT(*) AS total_columns FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '".$_POST['selected']."' AND table_schema = '".$_SESSION['host']."';");
Comment: If you cannot do it this way try what @Shadow proposed.
Answer: you'd want to use the INFORMATION_SCHEMA.COLUMNS table as indicated in this answer
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
    AND `TABLE_NAME`='yourtablename';

you first create a loop where you make the
[CONTENT]	...
 row of the table then you run your existing loop to generate the
[CONTENT]	...
 rows.
your first loop would more or less be the same as your second with the difference being that you are using a different sql result, using  instead of  and a loop inside your second loop. this will...

display the entire table from the database as a table in html

and if you need a row/column count you can stick some sort of iterator in each loop
first loop example
echo "
";
$countColumn = 0;
while($row = $statement->fetch())
{
    echo "".$row['COLUMN_NAME']."	";
    $countColumn += 1;
}
echo "
";

second loop example
$countRow = 0;
while($row = $statement->fetch())
{
    echo "
";
    foreach($row as $data)
    {
        echo "".$data."	";
        $countRow += 1;
    }
    echo "
";
}

NOTE: Browsers are retarded children, unless in your
echo "
";

while($row = $statement->fetch())
{
    echo $row['book_id'] . $row['title'];
}

echo "
";

part your $row['book_id'] . $row['title'] has your
 tags don't let them fill in the blanks in. especially if this is going to be a non-intranet page


Solving an equation for a sum index

Question: I have the following equation:
$$T=P\left [1+\sum_{i=1}^{n}(1.02)^i \right ]$$
How can I solve the equation for the $n$ value? I don't know how to expand the sum so I can handle algebraically $n$
Comment: @Salahamam_Fatima Thanks for pointing it out. $n=1$
Answer: hint
if $a\ne 1$, then
$$a^p+a^{p+1}+a^{p+2}+...a^q=$$
$$a^p\frac {a^{q-p+1}-1}{a-1} .$$
in your case
$$p=1 \;, \; a=1.02 \;,\;q=n $$
If $n $ is great , you can use the approximation
$$(1+0.02)^n\approx 1+0.02n $$
Comment: How do you get the first expression?
Comment: For $a>1$ gives negative values in the denominator of the first expression. How can I get a negative value by summing positive $a$?
Comment: @JoshuaSalazar numerator is also negative. so ...
Comment: @JoshuaSalazar A/B=(-A)/(-B).
Answer: Making the problem more general, let us consider $$T=P\left [1+\sum_{i=1}^{n}a^i \right ]$$ and remember the geometric series
$$\sum_{i=1}^{n}a^i =\frac{a \left(a^n-1\right)}{a-1}$$ Now, rearrange to isolate the term $a^n$ and get $$a^n=\frac{(a-1) T+P}{a P}$$ Now take logarithms of both sides to get $$n=\frac{\log\left(\frac{(a-1) T+P}{a P} \right) }{\log(a)}$$ which is the exact solution.
Now, if $a=1+\epsilon$ where $\epsilon\ll 1$ and, for conveniency, setting $T=\lambda P$ we have $$n=\frac{\log \left(\frac{1+\lambda  \epsilon }{1+\epsilon}\right)}{\log (1+\epsilon
   )}$$ Using Taylor expansion around $\epsilon=0$, this would give $$n=(\lambda -1)-\frac{1}{2} \lambda\left(\lambda -1\right) \epsilon +\frac{1}{12}
   \left(4 \lambda ^3-3 \lambda ^2-\lambda \right) \epsilon ^2+O\left(\epsilon
   ^3\right)$$ For illustration purposes, let us consider $\lambda=10$ (that is to say $T=10P$) and $\epsilon=0.02$; the above approximation would give $n=8.22300$ while the exact value should be $n=8.20694$
Edit
If you want to avoid logarithms and Taylor series, you could use instead Padé approximants. The simplest would give $$n=\frac{(\lambda -1) ((1+\lambda)  \epsilon  +6)}{(4 \lambda+1)  \epsilon  +6}$$ which, for the worked example, would give $n=\frac{2799}{341}\approx 8.20821$.
Answer: Let $r=0.02$.
$$\begin{align}
T&+P\bigg[1+\sum_{i=1}^n (1+r)^i\bigg]\\
&=P\sum_{i=0}^n (1+r)^i\\
&=P\cdot \frac {(1+r)^{n+1}-1}{(1+r)-1}\\
&=\frac Pr\left((1+r)^{n+1}-1\right)\\
1-\frac {rT}P&=(1+r)^{n+1}\\
n&=\color{red}{\frac {\log(1-\frac {rT}P)}{\log(1+r)}-1}
\end{align}$$
Note that a real solution for $n$ exists only if $\frac {rT}P>1$, ie. $r>\frac PT$.
Also, $n$ must be rounded up to the nearest integer (as it must be an integer) meaning that the sum may not be exact, but the number of periods for repayment (assuming this is a time value of money problem, which it appears to be) should be correct.

Solving an equation for a sum index


How does topic count affect channels performance in the Phoenix framework?

Question: I am currently creating an application with the Phoenix framework that uses channels for two way communication between a large number of mobile devices and a back-end service (obviously Phoenix based).
I am intending to create a single topic for each device given that devices are defined by ID, for example device:2149, device:1234 etc.
I have the following socket:
defmodule Webservice.DeviceSocket do
  use Phoenix.Socket
  channel "device:*", Webservice.DeviceChannel
  transport :websocket, Phoenix.Transports.WebSocket

  def connect(_params, socket) do
    {:ok, socket}
  end

  def id(_socket), do: nil
end

and the following channel:
defmodule Webservice.DeviceChannel do
  use Phoenix.Channel

  def join("device:" <> device_id, _params, _socket) do
    # do some stuff
    {:ok, socket}
  end

  def handle_in("some_message", %{"data" => data }, socket) do
    # Do stuff
    {:noreply, socket}
  end
end

Now given that I expect a large number of devices to use this service say around 90000, this means that 90000 topics need to be managed.
Will a large number of topics result in some overhead that will hurt the application's performance?
Comment: If each device connects to its own channel, how will the devices communicate with one another?
Comment: Devices does not need to communicate with each other directly.
Answer: According to this blog post, Phoenix can handle at least 2 million websocket connections, but of course that assumes your machine is beefy enough. 90,000 should be a breeze.


How to costumize the input fields but only in the page /user?

Question: I want to create a particular style with css for input style in the field of login, register and request new password.
The css if i see it width firebug is only one and i must adding a type only for the form of the /user page, but not for all page that containes form.
Thank you for help!
Comment: You should review your questions and mark the answers that solved your question as the accepted answer. This is done by clicking the big check button next to the voting widget. Doing so adwards the one that spent his time answering your question with a little rep, but more importantly is helps other people with the same problem to quickly see what solution helped you. Sometimes there are no answers that solves your question, but I find it hard to believe this is the case for **ALL** your questions.
Answer: Check out the classes added to the opening body tag in the HTML. It will help you narrow down styles to just that page.
I know one of my D6 sites, there is a class in the body tag 'page-user' so you can use some CSS such as...
<code>body.page-user .form-text {
  /* Add styling */
}
</code>
Inspect the HTML and style as necessary. :o)


TypeError: 'bool' object has no attribute '__getitem__' for palindrome

Question: I am trying to create a palindrome without using a reverse function:
Below is my code
<code>    import sys
    print (sys.argv)
    arg=len(sys.argv)

# check to determine if there is more than one argument on the command line

    if len(sys.argv) !=2:
       print("Specify 1 argument")

    else:
       statement=sys.argv[1]

#remove any space in the statement
    list=[]

for info in statement:
    if info == " ":
        list.append(info)
# create one string variable
    string="".join(list)

# make string lower case
    string_lower=string.islower()

# reversing list
    reverse_lower = string_lower[::-1]

# compare the orginal list to the reverse list
    if (string_lower == reverse_lower):
       print("It's a palindrome!")
    else:
       print("It's not a palindrome!")
</code>
I get an error stating:
reverse_lower=string_lower[::-1]
TypeError: 'bool' object has no attribute 'getitem'
Any help would be beneficial
Comment: Incorrect function called to make string lower case. User lower() instead of islower()
Answer: The .islower() Method returns a bool that says if the given string is only lowercase, you want .lower()
Comment: Thank you the error goes away but I am having issues with my strings not being compared
Answer: .islower returns True or False, .lower() returns the actual string:
<code>>>> 'a'.islower()
True
>>> 'a'.lower()
'a'
</code>
[::-1] returns a string. When you try to compare the string and the boolean, your error arises.


postfix mailserver fails to start on centos5.2

Question: I've just compiled and installed postfix and set domain names in main.cf.
Unfortunately postfix does not start. Nothing new shows up in the list of processes
when I issue
 /usr/sbin/postfix start
echo $? gives 0
Are there any log files or other clues I could use to figure out what goes wrong? Thanks.
Which processes should I look for in the ps output?
Thanks.
Answer: First, check to see that you're in a sane environment:
system-switch-mail
chkconfig --level 2345 postfix on

Next, find out what postfix seems to think the problem is:
service postfix restart ; tail -f /var/log/maillog

The startup failure will appear at the end of the log along with any clues as to why you're having an issue.
Comment: checking maillog (on different path set up by the hosting provider) showed that port 25 is taken. Turns out xinetd was set to listen on the smtp port.
Answer: for starters look in /var/log/messages, it'll give you some clues on whats wrong and where to look, in most of the cases if you copy and paste error message into google you'll find either solution or some clues how to fix it
Comment: then try to put postfix into debug mode and try to start it like that
Comment: thanks. unfortunately there are no relevant messages
Answer: Was there a specific reason you installed from source?
Why not just: yum install postfix
Then you will have a postfix init script.
chkconfig postfix on
service postfix start
If you need to switch from sendmail to postfix: yum install system-switch-mail
and then run:
system-switch-mail
to switch to postfix.
Hope this helps.
Cheers
Comment: Did you run system-switch-mail?

Sendmail might be using some of the ports (e.g. 25). Run system-switch-mail. IIRC that will start postfix but you could issue a: service postfix restart to be sure.

Cheers
Comment: i've tried the method you suggested before - same result.  when I do start then stop the system tells me that postfix was not running.


Views calculations

Question: I'm playing around with views, and I am sure on how to calculate fields based on Views data.
I thought Views Calc would do this, but it seems to only give me sums and averages of the fields. For example, suppose I'm making a financial site, and I want to do a price to earnings ratio; I would take price and divide it by earnings. Is it possible to do this in Drupal?
I know I can do this creating a PHP file for page, but to complicate things more, I ultimately want to give users the ability to do this as well; so, if possible, I want to stick with doing this with Views.
I see the view queries in generating; is there a way to modify the queries myself?
Answer: There is two ways to do this:

If your column information resides in a node, you can use Computed Fields in your node to create some new CCK fields with all sort of operations inside (you code directly in php there with access to all others fields of the node. If you're adventurous enough you can also make queries and everything you can imagine.
There's a similar funcionality directly for Views, it's called Views Custom Field and it's basically a Computed Field for Views.

So to summarize, if you need to have this information appearing in a node then Computed Field, if not just use Views Custom Field.
Comment: I might need both.  Some results I would want to put in a blog or pages, while most of them will be in standard views and applied to the entire dataset.
Comment: Also, while using Computed Fields, don't forget to check the option "save field in database" if not it won't be available as a field in Views.
Comment: ok I'll try that.  I'll def need both.  Right now I am playing around with views custom field and its really amazing..looks like it'll get me going on what I want to do.  I'm having a problem giving it custom sql commands because not sure how to id external tables but i'm working on it.  Its really amazing..thanks again
Comment: To use external tables, have a look at this documentation [How to connect to multiple databases within Drupal](http://drupal.org/node/18429), but if you're writing custom SQL, you can juste make queries like this: `SELECT columns... FROM database2.table1...` granted your MySQL Drupal user have access to this db.
Comment: wow it works amazing.  I can finally do what I want to do with views.  Thank you so much.  eventually i'll want to allow users to create views like this..but somehow i suspect giving them access to query my database and execute php commands on my server is a bad idea.  That'll be another day.  I am really really thankful for your help Tostinni.
Comment: You're welcome, and yes it's the worst idea ever (worst than hacking core) to grant php commands to users, justs consider this code `Global $db_url; print $db_url;` and you'll get your MySQL username/password.
Comment: lol i know...i need to figure a way to grant users freedom with controls.

Views calculations


AJAX request json fail

Question: I have a problem with an ajax request, when I do the request with the property dataType: 'json', my response come with an error, parsererror, my function in PHP returns the data like json_encode(), pls, can you help me? when I do the request without property dataType: 'json' my data is ALL THE DOCUMENT HTML.
My request:
                var dataAr = {Latitude: Latitude, Longitude: Longitude};/
                console.log(dataAr);
                $.ajax({
                    data: dataAr,
                    dataType: 'json',
                    type: 'POST',
                    url: 'http://localhost/GPS/Server.php/GPS/Coords',
                    success: function (data, response) {
                        console.log('Data: '+data);
                        console.log('Response: '+response);

                    },
                    error: function  (textStatus, errorThrown) {
                        console.log('Status: '+textStatus);
                        console.log('Error: '+errorThrown);
                    }
                });

My function in PHP:
class GPS
{
    function Coords()
    {
        $Res=$_POST['data'];
        $Latitude=$_POST['Latitude'];
        $Longitude=$_POST['Longitude'];

        return json_encode($Res);
    }
}

Comment: Are you using echo to send the data back to your Ajax function?
Comment: @bobdye With the echo in my function PHP happens the same error
Comment: inspect actual request in browser console network tab. I suspect your routing isn't right either
Comment: @charlietfl are you talking about my URL? i don't think so but thanks for the comment, i tested my request just in a native code like 'server.php' without the class and function and... does not work
Answer: Try using content-type :
function Coords()
{
    $Res=$_POST['data'];
    $Latitude=$_POST['Latitude'];
    $Longitude=$_POST['Longitude'];

    header('Content-Type: application/json'); // <-- HERE
    return json_encode($Res);
}

Answer: The $_POST variables have the same names at what you send in, not 'data'. It's not clear what you are trying to return, so for example purposes the following just returns and array with the input values:
class GPS
{
    function Coords()
    {
    $Latitude=$_POST['Latitude'];
    $Longitude=$_POST['Longitude'];
    $result = array( $Latitude, $longitude );

    header('Content-Type: application/json');
    echo json_encode($result);
    }
}

AJAX request json fail


media server with sip functionality

Question: I tried using Voxpilot media server for sip request handling using vxml code , but lately voxpilot is not working well and the already running applications are not displaying expected behaviour.
I tried using Mobicents media server mms 3.0 , mss2.0 , mss1.5  but the approach doesnt seem to be working since my softphone reads no sample multimedia application as IVR or muticonf as given in user guide doc .
I tried exploring a little of SEMS ( sip express media server ) but then the website reads "This website/URL has been blocked until further notice either pursuant to Court orders or on the Directions issued by the Department of Telecommunications" hence no help ..

Can some one suggest me a workaround or a media server , open-source
that can handle sip requests using vxml script ?
Answer: There are some open source VoiceXML interpreters/browsers and some open source SIP media servers, but I am not aware of a good open source solution that supports both.  OpenVXI is a popular VoiceXML interpreter that many commercial IVR systems are based on.  VoiceGlue is an open source implementation that combines OpenVXI with Asterisk under the GPL license.  You could try integrating OpenVXI with an open source SIP media server. You can get a list of open source SIP solutions here. Integrating the two is not a small task. Nor is learning and supporting some of these open source solutions.
If you are not tied to open source I would look at Voxeo Prophecy. This is an excellent VoiceXML platform that uses SIP as main telephony interface. It is a software only solution that you can get two ports for development for free and the per port cost is very economical. Probably less than the time and effort to get an open source solution running.  It is extremely easy to install and get running and the support is excellent and free. Voxeo also offers this platform in the cloud as a service.

media server with sip functionality


Certificate problems when sending mail via smtp (tream_socket_enable_crypto(): SSL operation failed with code 1)


What is AuthServiceProvider in Laravel

Question: I have got a file called
<code>AuthServiceProvider.php
</code>
in the Providers directory in Laravel project.
I actually don't understand about how it works and why it's needed
Can anyone explain with details?
Thanks in advance.
Comment: You can learn about it in the docs here https://laravel.com/docs/5.7/authentication
Answer: AuthServiceProvider is the default guard that Laravel uses to give the service authentication in the system. But if you need you can make your own guards for specific situations, in that case you will have you own AuthServiceProvider.
For eg. In one system that we made, the customer had his own database with it's specific users table, we can't use the default Laraver AuthServiceProvider. Because the table have other fields. So we created our CustomAuthProvider. It's complex, but you need to declare the driver en config/auth.php
<code>...
'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
    'provider' => 'custom' // Our custom driver
],
...
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'custom', // Our custom driver
    ],
    ...
],
...
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Modules\Pickandroll\Entities\User::class,
    ],
    'custom' => [
        'driver' => 'pickandrolluser', //Our Custom Auth Provider
        'model' => Modules\Pickandroll\Entities\User::class,
    ]
],
</code>
and the custom module provider we register our custom auth provider
<code> public function register()
    {
        Auth::provider('pickandrolluser', function ($app, array $config) {
            return new PickandrollUserProvider($config['model']);
        });
    }
</code>
and the class PickandrollUserProvider that extends use Illuminate\Contracts\Auth\UserProvider;
I know it's complex but maybe it helps to understand this topic

What is AuthServiceProvider in Laravel


Problem with slow hard disk

Question: We bought some new PCs in my company with the new iCore 7 and 8GB memory and the following hard disk: WESTERN DIGITAL WD8000AARS 800GB CAVIAR GREEN SATA2
The problem we have is that after installing windows XP64 SP2 the write speed of the hard disk is extremely low!.
The windows system monitor shows that the Average Disk queue length is always at 100% and a winzip extract of 350mb takes about 8min.
Is there any idea on where to start looking for the cause of that?
Thanks
Answer: That drive isn't really compatible with Windows XP as it uses a larger 4K sector size - it should explain the performance problems.
There's a special alignment tool from WD for Advanced Format drives you need to use or set the correct jumper if it's only going to host one partition.
matrice of OS and how to get them to work http://www.wdc.com/en/products/advancedformat/images/WD-Align_chart_r2.jpg
It's really time to upgrade from Windows XP as this kind of workaround from drive makers probably won't be provided in the future.
Comment: What about Windows Server 2003? It's largely the same codebase as Windows XP, but with an longer planned lifetime, and in an environment where upgrading is harder (servers). How does it handle 4K sectors?
Comment: Good question, about the expected EoL cycle. Server 2003 doesn't handle 4K sectors, just as the old Windows Home Server doesn't either. They need the align utility or the one partition jumper trick right now and how the future will pan out, well, I have no clue - except for upgrading. I also saw someone saying the utility won't run on 2003 or WHS - if someone want to confirm or deny it, be our guest ^^
Answer: First of all: BIOS. How is the SATA controller configured? And, BTW, is the motherboard BIOS up to date?
Second: drivers. Did you install Intel's chipset and controller drivers?
Third: maybe you actually got a faulty drive; this can help diagnosing it.
Answer: I would certainly check to see what the sata mode is in the BIOS - with Linux certainly I have seen night & day performance differences between the modes. It MAY hose your install though - don't do this without a backup first.
I don't think this is one of the 4k blocksize drives, AFAIK they all have "EARS" in the model ID?
Edit: i'm right: http://www.pcper.com/comments.php?nid=8113
Comment: I think the new 800GB AARS is a 1TB EARS drive with 200GB of sectors disabled: http://support.wdc.com/product/kb.asp?fid=wdfDesktop_CaviarGreen_SATA64&wdc_lang=en
Comment: I think Oskar is right. I see WD8000AARS listed here: http://is.gd/bKAFC
Comment: Ah, apologies - my research inaccurate, I was on a train, and the pages were slow to load, so I only got as far as proving my theory, rather than disproving the other ;)

Problem with slow hard disk


Formula for conditional expectation in a binomial sample

Question: Let's take $N$ i.i.d. stochastic variables $X_i$, where $X_i \sim Bin(n,p)$.
Taking inspiration from here, we should have the following facts:

$Var(X_i)=np(1-p)$.
The sample statistics $M(X_1,...,X_n)=\frac{\sum_i X_i}{N}$ is a sufficient and complete statistics.
The MLE estimator for $np(1-p)$ is $T_{MLE}=nM(1-M)$.

Combining these points we have that the $T_{MLE }$ is also UMVUE by the Lehmann-Scheffe' lemma.
Now we have also the following fact:

The (corrected) sample variance $S^2=\frac{1}{N-1}\sum_i{(X_i-M)^2}$ is an unbiased estimate of $Var(X_i)$.

From Lehmann-Scheffe' we should have then by consistency:
$$E[S^2\mid M]=nM(1-M)$$
My questions:

Is my reasoning correct or am I applying some theorem in a wrong way ?
If the reasoning is correct, what would be a direct derivation of the final result ? Is the formula trivial for some reason I do not see now ?
Comment: Are you sure the MLE is umbiased for the variance? And I think your sample size is $N$ and not $n$ as in the very first line.
Comment: You are right there may be some prefactors but I hope this does not change the reasonings... let me check this...
Comment: Indeed the correct UMVUE would be equal to $E[S^2\mid M]$.
Comment: You are right I should change the notation like that... At the moment I am getting that to get something proportional to $npq$ I should have $n^2M-nM^2$ and in that case $E[n^2M-nM^2]=Var(X_i)(n^2-n/N)$ . At least for $n=1$ this formula is compatible with the link. But I should redo better than also the MLE estimate, even if the reasoning is there is any case, regardless of the estimator being suggested by maximum likelyhood or not... I think I will try tomorrow to fix things and make a proper question. Thanks a lot for the correction and for checking the reasonings in the meanwhile.
Answer: Your reasoning is correct except MLE is not the UMVUE of the population variance.
A complete sufficient statistic for $p$ is $T=\sum\limits_{i=1}^N X_i$, which has a $\mathsf{Bin}(nN,p)$ distribution.
Now $E_p[T]=nNp$ and $\operatorname{Var}_p[T]=nNp(1-p)$ for all $p\in(0,1)$.
Again, $$E_p[T^2]=\operatorname{Var}_p[T]+(E_p[T])^2=nNp(1-p)+n^2N^2p^2$$
Or, $$E_p[T^2-T]=nNp^2(nN-1)$$
That is, $$E_p\left[\frac{T(T-1)}{N(nN-1)}\right]=np^2$$
So you have an unbiased estimator of population variance based on $T$ (and hence UMVUE):
$$E_p\left[\frac TN-\frac{T(T-1)}{N(nN-1)}\right]=np-np^2=np(1-p)\quad,\forall\,p\in(0,1)$$
With $\overline X=\frac TN$, the sample variance $S^2=\frac1{N-1}\sum\limits_{i=1}^N (X_i-\overline X)^2$ is unbiased for population variance. So by Lehmann-Scheffe, $E\left[S^2\mid T\right]$ is also UMVUE of $np(1-p)$.
As UMVUE is unique whenever it exists, you can say
$$E\left[S^2\mid T\right]=\frac TN-\frac{T(T-1)}{N(nN-1)}\tag{*}$$
This can be rewritten in terms of $\overline X$ of course.

A direct way to obtain $(*)$ would be to proceed using linearity of expectation.
I think it should be something like
\begin{align}
E\left[S^2\mid  T=t\right]&=E\left[\frac{1}{N-1}\sum_{i=1}^N\left(X_i-\frac tN\right)^2\mid T=t\right]
\\&=E\left[\frac{1}{N-1}\left(\sum_{i=1}^N X_i^2-\frac{t^2}{N}\right)\mid T=t\right]
\\&=\frac{1}{N-1}\sum_{i=1}^N E\left[X_1^2\mid T=t\right]-\frac{t^2}{N(N-1)}
\end{align}
Now we only have to recall that $X_1$ conditioned on $T$ has a hypergeometric distribution.
Comment: No you are right. In fact I had asked a similar question here sometime back for Poisson distribution.
Comment: Thanks I will check better the computations and the hypergeometric distribution after conditioning .... but +1 for the moment! :) anyway isn't it interesting? The second proof has only algebraic manipulations, whereas the first one apparently derives from a different type of algebra and general principles...
Comment: I am not an expert in statistics so maybe I should not be so surprised I do not know...
Comment: Calculations get easily complicated in this question... For future readers, I just add why the hypergeometric distribution plays a role. First of all $p(x_1,t)=p(x_1)p(\sum_{i>2}x_i=t-x_1)$. The first term is simple. The second can be derived thinking that the binomial $Bin(n,p)$ distribution is the number of successes in $n$ Bernoulli trials. Therefore the probability  $p(\sum_{i>2}x_i=t-x_1)$ is the probability of having $t-x_1$ successes in $(N-1)n$ trials. Analogously one can compute $p(t)$ and the conditional $p(x_1|t)=p(x_1,t)/p(t)$, arriving at the already cited distribution.
Comment: Yes, it is this familiar result: https://math.stackexchange.com/q/575459/321264.


Finding (regex?) 10 digits in a row (PHP)

Question: I am facing a problem i am not capable to solve. I have a string consisting of not needed text and 10 digit numbers who always start with "2" or "6". I need to get those in 10digit numbers into an array. I thought of regex and found this article Regular Expression for matching a numeric sequence? which is pretty close to what i need (except the descending/ascending thing) yet, as i could never and will NEVER be able to understand regex, i cant modify to my needs. If anyone could help me out here i would highly appreciate it!
Here is a sample of my string:
".........693 7098469 - ZQH X Bop. Hrtepou 50 flerpoUrroXn ........210 5014166 - 0E000PA E KapaoAn Anpn-rPou 21
EAArivtg .....................................................210 9618677 - MAPIA KapaoAri Arpn-rptou 21 Elanvolo .. 210 9643623 - MAPIA E ...................................................... 210 9643887 - MAPIA 0 loucrrivou 8 HX.toOrran ..............210 9914534 AIPITAKHE APTEMIOE n Avrtnopou 22
Reptcrrept ....._.........._......._................697 7440896 , -10AN."

Thank you very much in advance!
Greetings from Greece!
Comment: Thanks for the edit... i couldnt get the damn code block in there! :-)
Comment: Okay.. what have you tried?  Show us what you've attempted and why it didn't work.
Comment: @anubhava, All the numbers like `693 7098469` , `210 5014166` , etc.. the numbers that start with `2` or `6`.
Comment: You CAN do this reg exp. It's almost simpler than logging into your OS... "I can't do regex" sounds like an excuse to have others do your work.
Comment: And what is your expected output?
Comment: So far, the only thing i was able to try out with regex was this ^(?=([0-9]))\1{10}$ and to be honest i dont know what exactly i was trying out! i really cannot understand regex....
Comment: Maybe you should learn about it then ;). If we just provide you with a regex, you won't learn anything from it.
Comment: For a start, you might look at [this](http://regex101.com/r/sS2rB3) (especially the explanation). The explanation should be clear enough to understand.
Comment: @Jerry Very good link! thank you very much!
Answer: As I see your string your digits have an space between, and if you want strictly make your selections this is the regex:
[62]\d{2}\s*\d{7}

Explanation:
[62]    # Start with 6 or 2
\d{2}   # 2 more digits
\s*     # any number of white spaces
\d{7}   # 7 more digits

Live demo
and PHP code which has preg_match_all to match all occurrences of those strings:
preg_match_all("/[62]\d{2}\s*\d{7}/", $text, $matches);

Output:
Array
(
    [0] => 693 7098469
    [1] => 210 5014166
    [2] => 210 9618677
    [3] => 210 9643623
    [4] => 210 9643887
    [5] => 210 9914534
    [6] => 697 7440896
)

PHP live demo
Comment: Thank you very much for the explanation! I really think regex will be my nemesis for ever....
Comment: @JimBadanis-Kapirnas *Beside its regular name - Regular Expressions - it's so nasty!*
Answer: Maybe like this:
<?php
$x=
".........693 7098469 - ZQH X Bop. Hrtepou 50 flerpoUrroXn ........210 5014166 - 0E000PA E KapaoAn Anpn-rPou 21     EAArivtg  ....................................................210 9618677 - MAPIA KapaoAri Arpn-rptou 21 Elanvolo .. 210 9643623 - MAPIA E ...................................................... 210 9643887 - MAPIA 0 loucrrivou 8 HX.toOrran ..............210 9914534 AIPITAKHE APTEMIOE n Avrtnopou 22
Reptcrrept ....._.........._......._................697 7440896 , -10AN.";
$x=str_replace(' ','',$x);
preg_match_all('/((2|6)\d{9})/',$x,$matches);
print_r($matches[0]);

And the result:
Array
(
    [0] => 6937098469
    [1] => 2105014166
    [2] => 2109618677
    [3] => 2109643623
    [4] => 2109643887
    [5] => 2109914534
    [6] => 6977440896
)

Answer: there is a pretty cool page, that visualize the regex code for better understading:
https://www.debuggex.com/
this should work
((?:2|6)[0-9]{2} [0-9]{7})


Como copiar conteúdo de uma div para um input?

Question: Estou tentando copiar conteúdo de uma div para um input. Eu já consegui copiar de um input para outro ou de uma div para outra, mas não consegui de uma div para um input.

  Exemplo

<input id="texto" />

O que eu consegui foi :

  Exemplo dasjkhd kdhasj khd askjh

Comment: input não tem a propriedade `innerHTML`, tente usar a propriedade `value`, aliás, coloque o tipo do input, text, por exemplo
Comment: pode colocar o script no evento `onchange` do div
Comment: Deu certo, agora teria como atualizar automaticamente sem precisar atualizar a pagina?
Comment: Deu certo muito obrigado
Answer:

// Elemento com o Texto
var elemento = document.getElementById('teste').innerHTML;
// Escrevendo em outro Elemento
var texto = document.getElementById('texto');
texto.value = "Texto Copiado: " + elemento;

  Exemplo

<input id="texto" />
Comment: Deu certo, agora teria como atualizar automaticamente, sem precisar atualizar a pagina? pois esta div se transforma em um textarea
Answer:
Deu certo, agora teria como atualizar automaticamente, sem precisar
  atualizar a pagina? pois esta div se transforma em um textarea

Você pode adicionar um listener que observa as modificações no elemento e atualizar o conteudo do input:

// Elemento com o Texto
var elemento = document.getElementById('teste');
var texto = document.getElementById('texto');
  elemento.addEventListener('DOMSubtreeModified', function () {
  var elemento = this.innerHTML;
  // Escrevendo em outro Elemento
  texto.value = "Texto Copiado: " + elemento;
})

  CLIQUE PARA EDITAR O TEXTO

<input id="texto" />

EDIT:
Vi que esse método está "deprecated", existem outras opções, uma delas é alterar o nome do listener de DOMSubtreeModified para input

// Elemento com o Texto
var elemento = document.getElementById('teste');
var texto = document.getElementById('texto');
  elemento.addEventListener('input', function () {
  var elemento = this.innerHTML;
  // Escrevendo em outro Elemento
  texto.value = "Texto Copiado: " + elemento;
})

  CLIQUE PARA EDITAR O TEXTO

<input id="texto" />


How can the number of connections be Gaussian if it cannot be negative?

Question: I am analyzing social networks (not virtual) and I am observing the connections between people. If a person would choose another person to connect with randomly, the number of connections within a group of people would be distributed normally - at least according to the book I am currently reading.
How can we know the distribution is Gaussian (normal)? There are other distributions such as Poisson, Rice, Rayliegh, etc. The problem with the Gaussian distribution in theory is that the values go from $-\infty$ to $+\infty$ (although the probabilities go toward zero) and the number of connections cannot be negative.
Does anyone know which distribution can be expected in case each person independently (randomly) picks-up another person to connect with?
Comment: "Rayleigh" maybe?
Comment: Clarification: Is the question about the "total number of connections for the whole group" or "the total number of connections for one person"? My answer implicitly assumes the latter.
Comment: *Riley* distribution? That's a new one on me. Do you have a reference or link?
Answer: When there are $n$ people and the number of connections made by person $i, 1 \le i \le n,$ is $X_i$, then the total number of connections is $S_n = \sum_{i=1}^n{X_i} / 2$.  Now if we take the $X_i$ to be random variables, assume they are independent and their variances are not "too unequal" as more and more people are added to the mix, then the Lindeberg-Levy Central Limit Theorem applies.  It asserts that the cumulative distribution function of the standardized sum converges to the cdf of the normal distribution.  That means roughly that a histogram of the sum will look more and more like a Gaussian (a "bell curve") as $n$ grows large.
Let's review what this does not say:

It does not assert that the distribution of $S_n$ is ever exactly normal.  It can't be, for the reasons you point out.
It does not imply the expected number of connections converges.  In fact, it must diverge (go to infinity).  The standardization is a recentering and rescaling of the distribution; the amount of rescaling is growing without limit.
It says nothing when the $X_i$ are not independent or when their variances change too much as $n$ grows.  (However, there are generalizations of the CLT for "slightly" dependent series of variables.)
Comment: @Andy Not people: the number of connections made.  The important thing is that there should be a good chance that the number of connections made by individuals actually varies and doesn't settle down to a constant.  When that happens, the limiting distribution (of the number of connections) is determined by the finite number of initial connections that do vary, so it's not possible to approach a Normal distribution asymptotically.
Comment: Note that I do not interpret the question to state that everyone chooses *exactly one* other person to connect to--that would lead to a sterile theory because the number of connections would be determined, not random.  Instead I have interpreted it to state that everyone when they enter the network chooses connections randomly among the n others, winding up with anywhere from 0 through n connections total.  The assumption on the variances is assured when there is a limit on the number of connections any newcomer will make *and* that number has some "minimal" randomness.
Comment: I'm a bit confused about $X_{i}$ and the variance. Does this suggest people have an intrinsic variance?
Answer: The answer is dependent on the assumptions that you are willing to make. A social network constantly evolves over time and hence is not a static entity. Therefore, you need to make some assumptions about how the network evolves over time.
The trivial answer under the stated conditions is: If the network size is $n$ then as  asymptotically (in the sense of 'as time goes to infinity')
$Prob(\mbox{No of connections for any individual} = n-1) =1$.
If a person selects another person at random to connect to then eventually everyone will be connected.
However, real life networks do not behave this way. People differ in several aspects.

At any time a person has a fixed network size and the probability of another connection being made is a function of his/her network size (as people introduce other people etc).
A person has his/her own intrinsic tendency to form a connection (as some are introvert/exterovert etc).

These probabilities change over time, context etc. I am not sure there is a straightforward answer unless we make some assumptions about the structure of the network (e.g., density of the network, how people behave etc).
Comment: @Srikant Could you explain how you derive the "trivial answer"?  (There must be some unstated assumptions behind it.)  And to what theorem do you refer when you conclude that "eventually everyone will be connected"?  That's not at all obvious!
Comment: @whuber I am assuming that the network size is fixed. The question states: A person picks another person at random to make a connection and presumably this is an ongoing process. Thus, as time goes to infinity everyone should be connected. No theorem, just intuition. Perhaps, I am using imprecise language.
Comment: @Srikant I am still confused, because after a long time, "Prob(No of connections=n)" equals 1 when n = 3 and otherwise is always zero.  After all, when "everyone should be connected" the number of connections equals n(n-1)/2.  I suspect you may have several different random processes in mind at the same time.  It could help to disclose the assumptions you are making and be a little more precise.


Multiple Devise controller overrides

Question: I'm trying to restrict Devise password resets for particular users. I found this thread which describes overriding PasswordsController:
Restrict Devise password recovery to only certain users
My problem is, I'm already overriding registrations with my own registrations controller:
devise_for :users, :controllers => { registrations: 'registrations' }
My registrations controller inherits from Devise::RegistrationsController, and according to the above thread my Password controller will need to inherit Devise::PasswordsController, and thus be a separate controller. How can I have multiple Devise controllers to facilitate these overrides?
Answer: The line
:controllers => {registrations: 'registrations' }

uses your custom registrations controller, so adding {passwords: 'passwords'} will use your custom passwords
The complete line should be
controller.devise_for :users, :controllers => { registrations: 'registrations', passwords: 'passwords'  }

Comment: :controllers => {registrations: 'registrations' } uses your custom registrations controller, so adding {passwords: 'passwords'} will use your custom passwords controller.

Multiple Devise controller overrides


Recurrence equation $T(n)=3T(\sqrt{n}) +1$

Question: I need to find an exact solution to the following recurrence using substitution (change of variables).
$$
T(n) =  3T(\sqrt{n}) + 1, \quad \text{ when } n > 2,
$$
and $$ T(2) = 1 .$$ I can't get it right. The best answer I came up with was $$
\frac 3 2  3^{\log_2 (\log_2 n)} - \frac 1 2,
$$ but when I try to prove it with induction, it doesn't seem to be the right answer.
Any help would be appreciated.
Comment: This recurrence only defines $T(n)$ for $n=2^{2^k}$. Prove using induction on $k$.
Comment: It means that either you define T(n) inductively on sets of iterated squares A^(2^n), starting from non-square values of A, where these sets are disjoint for different A and there is no relationship between the values of T on different sets; or you interpret $\sqrt{n}$ to be the square root rounded downward to an integer.
Comment: He didn't say $n$ ranges over integers...
Comment: Instructions say that I can assume that the value of n is suitable such that argument of T is an integer. What does that mean exactly?
Comment: Note that $3^{\log_2 t}$ can also be written as $t^{\log_2 3}$, and that for complexity a lot of people consider a function of the form $t^\alpha$ 'simpler' than the alternate form.
Comment: Like @Steven said. In this case, $(\log n)^{\log_23}$ or $(\log_2 n)^{\log_23}$, see my answer.
Answer: The inhomogeneous form of the recurrence, with its constant term of $+1$, can be reduced to homogeneous form where the constant term is $0$, by subtracting a particular (e.g., constant) solution of the inhomogeneous equation.  Here the constant solution is $T(n) = -1/2$ so that $S(n) = T(n) + 1/2$ is the natural function to examine, and satisfies the simpler recurrence $S(n)= 3S(\sqrt{n})$.
For the equation to be well-defined, an interpretation of what $\sqrt{n}$ means should be fixed. For an integer recurrence you probably mean the greatest integer $\leq \sqrt{n}$.  For a positive real-valued recurrence one would stipulate the values of $T(n)$ on an interval containing $1$ and define the function on the rest of $(0,+\infty)$ using the recurrence.
The formula with $\log_2 \log_2 n$ does satisfy the recurrence for $n>1$, if $n$ is real-valued and the square roots are exact.  Unfortunately this form of $T(n)$ is undefined at $n=1$ and has a limit of $-1/2$ as $n \to 1$, which is inconsistent with the requirement that $T(1)=1$.  The trouble is that the unlimited ability to iterate the square root operation forces $T(n)$ toward $-1/2$ at $n=1$.  One has to ground the induction by clearly defining the "base case" of the recurrence and how it is reached in finitely many steps.  Then, instead of using logarithms, one can write a solution in terms of the quantity "number of iterations of $\sqrt{n}$ necessary to reduce $n$ to the initial value (or interval)". The logarithms are still important for expressing the approximate value of that quantity and thus the size of $T(n)$ for large $n$, but they are not an exact description of any solution with $T(1) \neq -1/2$.
EDIT: I am leaving the above as originally written, but the boundary condition is $T(2)=1$ and not $T(1)=1$ as I had thought. For that condition the algebraic formula in the question is correct at powers $2^{2^n}$ and definition at other values is best done in terms of the number of iterations to reduce $n$ to $2$ or less.
Answer: One is looking for the behaviour of sequences $(T(n))_{n\geqslant2}$ defined for every integer $n\geqslant2$. For any given integer $a\geqslant2$, apply the recursive relation to
$$
t(k)=3^{-k}\cdot T(a^{2^k}).
$$
One gets $t(k)=t(k-1)+3^{-k}$ for every positive integer $k$ hence $t(k)=t(0)+3^{-1}+3^{-2}+\cdots+3^{-k}$ for every nonnegative integer $k$. Using the partial sum of the geometric series, this yields, for every nonnegative integer $k$,
$$
\color{red}{T(a^{2^k})=3^k\cdot T(a)+2^{-1}\cdot(3^k-1)}.
$$
For example, since one assumes that $T(2)=1$,
$$
T(2^{2^k})=2^{-1}\cdot(3^{k+1}-1).
$$
Note that the values $T(a)$ for every nonsquare integer $a\geqslant2$ are free since the relation one would get for $T(a)$ involves $T(\sqrt{a})$, which does not exist since $T(n)$ is only defined for (some) integer values of $n$.
It seems that the only way to get a single simple equivalent of $T(n)$ when $n\to\infty$ is to finely tune all these initial values of $T$ as follows. Assume there exists a constant $c$ such that for every nonsquare integer $a\geqslant2$,
$$
T(a)=c\cdot\left(\log_2a\right)^{\log_23}-2^{-1}.
$$
Then, for every positive integer $n\geqslant2$,
$$
T(n)=c\cdot(\log_2n)^{\log_23}-2^{-1}.
$$
Since the initial condition $T(2)=1$ imposes the value $c=\frac32$, one gets the convergence $\color{red}{R(n)\to\frac32}$ when $n\to\infty$, with
$$
\color{red}{R(n)=\frac{T(n)}{(\log_2n)^{\log_23}}}.
$$
For other initial conditions (that is, other values of $T(a)$ for $a\geqslant3$ non square), the sequence of ratios $(R(n))_{n\geqslant2}$ diverges in the sense that it oscillates without converging to a finite limit.
Comment: $T(1)$ is not determined by the recursion, which is given for $n > 2$ only, with $2$ being an initial value.  What happens at or near $n=1$ (with $1$ as the value where a boundary condition is imposed) is a more delicate question as explained in the other answer.
Answer: Try the simpler $R(m)=3R(m-1)+1$ when $m>0$ and $R(0)=1$.
Then you should be able to show by induction this is $R(m)=\frac 3 2  3^m - \frac 1 2$.
Now let $m=\log_2 (\log_2 n)$ or $n=2^{2^m}$.
Comment: So this basically means that my answer is correct and exact answer for the given recurrence? I just tried to prove it with wrong value of n?
Comment: What you said was correct for $n$ of the form $2^{2^m}$, as Thomas Andrews said in his comment.


Onsen ng-repeat and ajax

Question: I've a big problem in my app and I think it's caused by the asynchronous call.
The html part is:
<ons-list ng-repeat="item in newsEventi.items">
   <ons-list-header class="news_titolo_lista">{{item.categoria}}</ons-list-header>
       <ons-list-item class="news_titolo">
        ({{item.titolo}})
       </ons-list-item>
</ons-list>

The js part (the controller) is:
app.controller('NewsEventiController', ["$scope", function($scope)
{
  //--------------------//
  // private variables
  //--------------------//
  var _self = this;

  var _items = [];

  //--------------------//
  // private functions

  //--------------------//
  // constructor
  (function()
  {

    var url = "http://www.gaelico.net/app/test_json.php";
    // IT RETURNS -> [{"titolo":"test","categoria":"cat1"},{"titolo":"test1","categoria":"cat2"}]
    $.post(url, {data: JSON.stringify({regID: localStorage.getItem("regID")})},
      function(json)
      {
        _items = JSON.parse(json);
        $scope.$apply();
        console.log("After: " + _items);
      });
  })();

  //--------------------//
  // public properties
  //--------------------//

  this.items = _items;
  console.log("Before: " + this.items);

  //************************************************************************//
  // public methods
  //************************************************************************//

}]);

My problem is that the list never display the 2 elements. I used $scope.$apply() because I thought it was the right method to update the list, but it seems not to work.
Thank you in advance for every suggestion.

EDIT
I tried to change the script as suggested, and now the code is
app.controller('NewsEventiController', ["$scope","$http", function($scope,$http)
{
  //--------------------//
  // private variables
  //--------------------//
  var _self = this;

  $scope._items = [];

  //--------------------//
  // constructor
  (function()
  {
      // the url returns: [{"titolo":"test","categoria":"cat1"},{"titolo":"test1","categoria":"cat2"}]
      $http.get("https://www.gaelico.net/app/test_json.php")
        .success(function(response) {
          console.log(response);
          // it shows in the console, correctly: "Object, object"
          $scope._items = response;
        });

  })();

  //--------------------//
  // public properties
  //--------------------//

   console.log("Before: " + $scope._items);  // empty

}]);

(and in ng-repeat, I put ng-repeat="item in newsEventi._items")
But I still don't see any update in the list.
Answer: Declare items like this:
$scope._items = []

Your ngRepeat:
item in _items

You should not need to call apply and i recommend you look into angulars http module instead of using jquery.
Comment: Hi! Finally it worked! But I had to put also the $apply() method.  Thanks!

Onsen ng-repeat and ajax


Guessing strategy for a matching question

Question: I recently took a multiple choice test, with a triplet of questions that required matching the correct answer to the question.
In other words, let $Q=\{1,2,3\}$ and $A=\{a,b,c\}$, and $\phi:Q\to A$ be a function that maps each question to the correct answer. $\phi$ is bijective.
For these three questions, I decided to randomly guess different answers since I had no idea what the answers were, but it turns out that I got all three wrong. If I had chosen all three to be the same answer, I would have been guaranteed to get at least one of them correct. But this got me thinking, what choices would give me the biggest expected score?
Generalizing:
Let $Q=\{1,2,\cdots,n\}$ and $A=\{a_1,\cdots,a_n\}$ and $\phi:Q\to A$ be a random bijective function which maps each question in $Q$ to the correct answer in $A$. Assuming $\forall q\in Q$, I don't know what $\phi(q)$ is; how can choose a function $f:Q\to A$ to maximize the number of correct answers I get (i.e, maximize the number of $i\in\{1,\dots,n\}$ for which $f(i)=\phi(i)$)?
Answer: If you know literally nothing about $\phi$, then no matter what you do, your expected number of correct answers will be $1$. This is because of the linearity of expectation: let $X$ be the total number of correct answers you get, and let $X_i$ be $1$ when the $i^{th}$ answer is correct, and zero otherwise. Then $EX=EX_1+\dots+EX_n$, and each $EX_i=\frac1n$ since you will be correct with probability $\frac1n$, so $EX=\frac1n+\dots+\frac1n=1$ always.
In particular, this means no strategy can guarantee you get more than $1$ correct answer (since this would imply $EX>1$ when you use that strategy), so choosing guessing the same answer for all questions guarantees you the best score possible. What this strategy does is decrease the variance of your score without changing the expected value.
So, such a test can't really be "gamed" using clever combinatorics; a better strategy would be to study more.
Comment: Oh, these questions on the test were actually completely trivia questions of "match the story to the person who told it" and our professor specifically told us that there wouldn't be such questions. Extra studying would not have helped here.


How does $ 1 - \frac{1}{\sqrt{n+1}} + \frac{1}{(n+2)\sqrt{(n+1)} + (n+1) \sqrt{(n+2)}}$ reduce to $ 1 - \frac{1}{\sqrt{n+2}}\;$?

Question: $$ 1 - \frac{1}{\sqrt{n+1}} + \frac{1}{(n+2)\sqrt{(n+1)} + (n+1) \sqrt{(n+2)}}$$
Reduces to:
$$ 1 - \frac{1}{\sqrt{n+2}} $$
I have no clue how. What is the exact trick here and how can I practice this? I can't properly google the problem.
Comment: You could rationalize the denominator of the last expression, although it would take some effort. Consider rationalizing it, after factorizing out some common factor from the denominator. If you've made some progress along these lines, then consider editing your post to reflect the progress. Finally, use [Approach0](https://approach0.xyz/search/) to search for mathematical expressions ; the search results consist of posts on MSE or on the AoPS(Art of Problem Solving)website.
Comment: If you have $\frac{1}{a+b}$ you can rewrite as $\frac{a-b}{a^2-b^2}$ by multiplying top and bottom of the orginal expression by $(a-b)$. This is the standard approach to removing square roots from the denominator. After that, tidy up and re-assess.
Answer: $\require{cancel}$I'd us a combination putting over a common denominator and factoring.
Using that $foo = \sqrt{foo}^2$ we can factor $\sqrt{n+1}$ out of $(n+2)\sqrt{n+1} + (n+1)\sqrt{(n+2)}= \color{green}{\sqrt{n+1}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]$
So
$1 - \frac{1}{\sqrt{n+1}} + \frac{1}{(n+2)\sqrt{(n+1)} + (n+1) \sqrt{(n+2)}}=$
$1 -\frac 1{\color{green}{\sqrt{n+1}}} + \frac 1{\color{green}{\sqrt{n+1}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]}=$
$1- \frac {(n+2) + \sqrt{n+1}\sqrt{n+2}}{\color{green}{\sqrt{n+1}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]}+\frac 1{\color{green}{\sqrt{n+1}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]}=$
$1-\frac {(n+2) + \sqrt{n+1}\sqrt{n+2}-1}{\color{green}{\sqrt{n+1}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]}=$
$1-\frac {(n+1) + \sqrt{n+1}\sqrt{n+2}}{\color{green}{\sqrt{n+1}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]}=$
$1-\frac {\color{green}{\sqrt{n+1}}(\sqrt{n+1} + \sqrt{n+2})}{\color{green}{\sqrt{n+1}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]}=$
$1-\frac {\cancel{\color{green}{\sqrt{n+1}}}(\sqrt{n+1} + \sqrt{n+2})}{\color{green}{\cancel{\color{green}{\sqrt{n+1}}}}[(n+2) + \sqrt{n+1}\sqrt{n+2}]}=$
$1-\frac {\sqrt{n+1}+\sqrt{n+2}}{(n+2)+\sqrt{n+1}\sqrt{n+2}}=$
$1 -\frac {\sqrt{n+1}+\sqrt{n+2}}{\color{red}{\sqrt{n+2}}(\sqrt{n+2} + \sqrt{n+1})}=$
$1 -\frac {\cancel{\sqrt{n+1}+\sqrt{n+2}}}{\color{red}{\sqrt{n+2}}\cancel{(\sqrt{n+2} + \sqrt{n+1})}}=$
$1 - \frac 1{\color{red}{\sqrt{n+2}}}$
Comment: Thanks for taking the time to explain :)
Answer: HINT
Here is a different approach for the sake of curiosity (as suggested by Paul in the comments).
Precisely, we shall multiply the numerator and the denominator by the conjugate of the denominator:
\begin{align*}
\frac{1}{(n+2)\sqrt{n+1} + (n+1)\sqrt{n+2}} & = \frac{(n+2)\sqrt{n+1} - (n+1)\sqrt{n+2}}{(n + 2)^{2}(n+1) - (n+1)^{2}(n+2)}\\\\
& = \frac{(n+2)\sqrt{n+1} - (n+1)\sqrt{n+2}}{(n+1)(n+2)}\\
& = \frac{1}{\sqrt{n+1}} - \frac{1}{\sqrt{n+2}}
\end{align*}
Can you take it from here?
Comment: Thanks, I tried the conjugate trick but the problem was that to keep things tidy I did $n+2 = A$ and $n+1=B$ substitutions and then I didn't see how you could combine the denominator.
Comment: @bananenheld You are welcome ! I am glad I could help.


Convert PLC Modbus Signals to Float Value (pair of 16 bits integer into a 32 bit float)

Question: I am trying to convert values from Modbus addresses on a PLC to a float value on my program. Inside the PLC, the value is represented as 32 bit float, but to send it through Modbus, they convert it to pair of 16 bit integers. Now when I retrieve the value, I have to convert them back to 32 bit float. I already have working code (in the picture), but some low bit values are represented with '-' first and I can't convert them. Does anyone know how I should deal with this?
**For Example: -14.066963 in PLC is converted into low 16bit: 4680 and high 16bit: -16031. I can convert this back to its original value.
74.81565 in PLC is converted into low 16bit: -24163 and high 16bit: 17045. I can't convert this back to its original value.**
<code>public class HelloWorld{

 public static void main(String []args){
    short high = 17045; // the high 16 bits
    short low = -24163; // the low 16 bits
    int first_part = high << 16;
    int second_part = first_part | low;

    float num = Float.intBitsToFloat(second_part);
    System.out.println(first_part + " " + second_part + " " + num + '\n');

    //Working values
    short high1 = -16031; // the high 16 bits
    short low1 = 4680; // the low 16 bits
    int combined1 = (high1 << 16) | low1;

    float num1 = Float.intBitsToFloat(combined1);
    System.out.println(num1 + " " + combined1);
 }
</code>
}
Picture example
Comment: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/8967612)
Comment: Please avoid to share code and error as image, copy/paste them as code in your question, pay attention to the formattings
Comment: use unsigned int's and unsigned shorts for all your types so there is no sign extension issues
Comment: @franji1 Unfortunately, there is no unsigned in Java.
Comment: Thank you @franji1, that is exactly what I needed.
Answer: Change the short's to int's. Make their values be in the range of an unsigned short 0..65535 (instead of signed short -32768..+32767). You will need to change your negative short values to their unsigned equivalent (e.g. -24163 to 41373). I prefer to do all this stuff in hexadecimal, e.g. 0xA19D (instead of -24163 or 41373), since the integer values are meaningless - it's really the IEEE 754 32-bit bit pattern you are generating


Modify a custom block field value with hook_form_alter and validate

Question: I'm trying to modify a custom block form with hook_form_alter .In its validate function I have a case where one of the field value needs to be unset. For modifying its value I tried with
$form_state->setValue('field_name', '') /
$form['field_name']['#default_value'] = '' /
$form['field_name']['#value'] = ''
But none of these approach seems to work.
Below is my code -
function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    //create or edit form
    if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
      $form['#validate'][] = 'coolblockvalidate';
    }
}

function coolblockvalidate(array &$form, FormStateInterface &$form_state) {
    //trying to unset the field value here, which is not working.
    $form_state->setValue('field_mycoolfield', '');

    //tried these approach too with no luck.
    //$form['field_mycoolfield']['#default_value'] = '';
    //$form['field_mycoolfield']['#default_value'] = '';

}

I'm very interested in knowing why the field value can't be changed. I tried the same with a custom form alter and it works.
Any ideas/ suggestions would save me.
Thanks.
Comment: see https://drupal.stackexchange.com/questions/268160/custom-entity-form-submit-handler-not-being-invoked
Comment: @4k4 Based on your hint, I tried setting the values on submit handler rather than validate. Updating my answer.
Answer: Got this working by adding a submit handler.
Below is the code -
function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  //create or edit form
  if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
    //extra submit handler that will execute after default submit
    $form['actions']['submit']['#submit'][] = 'coolmodule_coolblocksubmit';
  }
}

function coolmodule_coolblocksubmit(array &$form, FormStateInterface &$form_state) {

  $entity = $form_state->getFormObject()->getEntity();
  // unset field.
  $entity->set('myfield', '');
  // Saving the entity.
  $entity->save();
}

Answer: You can unset the field using the Hook_preprocess_hook
something like the following.
/**
 * Implements hook_preprocess_HOOK().
 */
function coolmodule_preprocess_block(&$variables) {
  if (
    isset($variables['elements']['content']['#block_content'])
   && $variables['elements']['content']['#block_content']->bundle() == 'your_custom_block_type'
  ) {
    if (isset($variables['content']['field_custom_field_test'])){
      //- set field to empty value
      $variables['content']['field_name'] = [];
      //- Or Unset the field totaly
      unset($variables['content']['field_name']);
    }
  }
}

Comment: Thanks for the suggestion. But I would like to change the value on submit rather than preprocessing the values.
Answer: You does not need to saved entity multiple time.
function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  //create or edit form
  if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
    //extra submit handler that will execute after default submit
    array_unshift($form['actions']['submit']['#submit'] , 'coolmodule_coolblocksubmit');
  }
}

function coolmodule_coolblocksubmit(array &$form, FormStateInterface &$form_state) {

  $entity = $form_state->getFormObject()->getEntity();
  // unset field.
  $entity->set('myfield', '');
}