What is the normal convention for naming and using iterators in C++?

Question: I feel like I'm unprofessional in the way I name and use iterators. What I mean by that is that I "feel" like I should be calling them something else, but I always name them based on the "it_" prefix, and after a while, in a long function, the names start to all look alike.
Additionally, I always wonder if I'm doing things a "strange" way that I learned just because I didn't know better. For instance, if I were iterating through a map to display all its key/value pairs, I would do this:

map<int, int>::const_iterator it = layout.begin();
for (; it != layout.end(); ++it)
{
   cout << it->first << ":\t" << it->second << "\n";
}
I see some people calling their iterators "iter" - I see other ways of doing loops. Is there any kind of convention that transcends style and is just good practice?
Comment: nearly all my loop variables are called `loop` (unless there is a double nesting).
Comment: @Martin: my iterators are usually `it` and `end`... but then using `BOOST_FOREACH` consistently now, I don't bring them out often.
Comment: I a;ways try and replace a loop with an algorithm. Not a fan BOOST_FOREACH because of the all caps name (makes the code look ugly).
Answer: I try to declare the iterators inside the for loop as much as possible, so that the scope of the iterator identifier is minimized.
First, I typedef the "long" type names to "shorter" and re-usable ones:
typedef std::map< int, int > IntMap;
typedef IntMap::const_iterator IntMapConstIter;

Then, I do
for( IntMapConstIter it = layout.begin(); it != layout.end(); ++it ) {
    ....
}

Comment: One of the best parts of C++0x is `auto it = layout.begin();`.
Comment: I don't like to use typedefs just for the sake of abbreviation, it increases complexity of otherwise simple code for not much benefit.
Comment: @ArunSaha: 1 answer: `auto` distinguish between `iterator` and `const_iterator` by type inference, if the container is `const` it'll be a `const_iterator` otherwise an `iterator. 2 remarks: the second *typedef* obscures the code more than it helps it, the first *typedef* should have a **functional** name, the exact type is an implementation detail that may evolve.
Comment: I hadn't even considered that - and one of the things I was worried about *was* scope. How do you deal with the incredibly long "for" statements that tend to result? The best I can think of is making a typedef for the datatype to shorten it.
Comment: @Adam: my thought too.  Hence, it's only for reduced redundancy, ease of changing container type, and readability that I use typedefs like IntMap above, but I'd then use IntMap::const_iterator as I don't see IntMapConstIter being remotely more understandable, it's only minimally smaller, loses information re the relationship to IntMap, and abstracts nothing as it can't be changed to any other type of iterator later without needing to be renamed and have client usage reexamined.
Comment: Just wrap it, see my answer. I find it more readable than declaring a variable outside of the loop.
Comment: i personally typedef the datatype, then separate the for statement into its 3 pieces on 3 different lines.
Comment: This is extremely readable, and I also hadn't ever considered using a typedef for the const_iterator. Makes a *lot* of sense, and its easy to deal with.
Comment: @Brendan: Good point. However, I don't (yet) understand how `iterator` versus `const_iterator` is resolved. [+1]
Comment: @Matthieu M: +1 Thanks for the answer. On your remark: (a) I incline to include the container type in the typedef, more so after reading "Beware the illusion of container-independent code" in Effective STL, Scott Meyers [http://www.aristeia.com/estl/index.html]. (b) If there is a map in a class, there freqeuntly is more than one method where I need the iterator. So, typedef'ing it once saves me typing :) I follow a naming convention which helps me immediately recognize what a type means.
Answer: I do that as follows
for (map<int, int>::const_iterator it = layout.begin();
     it != layout.end(); ++it)
{
    cout << it->first << ":\t" << it->second << "\n";
}

Thanks to that the iterator is scoped only inside the block, which makes it safer to give it a shorter name.
Comment: Great! I saw ArunSaha give the same answer before, and this entire time I hadn't even thought of breaking the "for" loop into several lines to deal with the length. Thanks!
Comment: You're welcome, sometimes the simplest solution is the hardest one to notice.
Answer: I am pretty sure no convention transcends style for this matter. I believe the most important part of iterator naming is on the second part (considering you decide to add a prefix, should it be "it" or "iter_" or anything else). Choose the second part carefully as you would for any other variable and you'll be fine.
Answer: I haven't seen a single canonical loop.
The cost of creating an iterator is specified to be O(1) (wrt the size of the container), but it may cost, especially when specific debugging options are activated.
Therefore, calling end at each iteration of the loop is wasteful.
The canonical way to write a for loop is therefore to compute both it and end in the first statement.
typedef std::map<int,int> LayoutType;

for (LayoutType::const_iterator it = layout.begin(), end = layout.end();
     it != end; ++it)
{
  // ...
}

I usually typedef my container, but honestly there isn't much point in typedefing the iterator, it's already available within the container and introducing too many synonyms does not help.
Also, it may be a personal quirk, but I prefer stating the function rather than the type when I introduce my typedef. The type may change in later refactoring, the function will not (at least, it won't be the same thing at all if it does, so it'll call for a complete rewrite).
For example what if you suddenly preferred: typedef std::unordered_map<int,int> LayoutType ? It still matches your need, and you can probably drop it in at no rewriting cost (providing you have used a typedef).
Comment: +1 for a lot of good points, though I think the whole end precomputation issue is way overblown - only extreme circumstances or bad design result in a slow end() ;-).  Further, some ugly operations may change end() during the iteration: nasty enough by itself, but worse still with a cached end() value.  All up, not a big deal either way I'd say.
Comment: @Tony: I never said it was the only way, it is however the canonical one I think. Though this loop is advantageously replaced by `BOOST_FOREACH` or the new *range for* expression of C++0x which neatly hide the iterator things.
Comment: Yes, was just trying to note my disagreement over that "canonical" claim: if anything I'd say `for (Iterator i = x.find/begin/?(); i != x.end(); ++i)` was canonical, for better or worse (after all, canonical doesn't mean best practice). It's a relief that auto, ranges, foreach etc. are on their way.
Comment: @Tony: definitely a relief :)
Answer: Would it be totally unreasonable for me to suggest the use of BOOST_FOREACH and for you to (mostly) forget about iterators ?
Comment: Not at all, I just haven't used Boost yet - even though I know in general all the cool things it offers
Comment: I've not used boost's foreach (have used project-specific implementations). Still, thinking at the iterator level is good when you're inserting or deleting during iteration, tracking multiple iterators concurrently etc.. I don't think boost foreach offers anything for those circumstances...?
Comment: @Tony: it doesn't but modifying the underlying structure of the container while iterating over it... it tricky to do right. I much prefer to either use `algorithm` for the task OR use an alternate temporary data structure that I'll switch with the current one at the end of the loop.
Comment: @Matthieu: tricky - yes; good alternatives where viable.  Cheers.
Answer: The name is the least important thing to me as long as it's clear and chosen appropriately.
This falls into the endless debate of variable naming

m_ for members
trailing underscore for members
etc...


Pontryagin dual of the multiplicative group of a local field.

Question: Let $K$ be a local non-Archimedian field.  Let $K^{\times}$ be the group of invertible elements of $K$.
Is there an explicit description of the Pontryagin dual of $K^{\times}$?
Comment: Assume first $k$ is a $p$-adic field. Then $k\$k^\times$ is $\mathbb{Z} \oplus \mathbb{Z} / (q-1) \oplus \mathbb{Z} / p^a \mathbb{Z} \oplus \mathbb{Z}_p^d$ for $a \geq 0$ and $d = [k : \mathbb{Q}_p]$. On the other hand, if $k$ has characteristic $p$, then $k^\times$ splits as $\mathbb{Z} \oplus \mathbb{Z} / (q-1) \oplus \mathbb{Z}_p^N$ for some $N$. This is Proposition II.5.7 of Neukirch's Algebraic Number Theory.
Answer: Assume first $k$ is a $p$-adic field. Then as topological groups $k^\times$ is isomorphic to $\mathbb{Z} \oplus \mathbb{Z} / (q-1) \oplus \mathbb{Z} / p^a \mathbb{Z} \oplus \mathbb{Z}_p^d$ for $a \geq 0$ and $d = [k : \mathbb{Q}_p]$. On the other hand, if $k$ has characteristic $p$, then $k^\times$ splits as $\mathbb{Z} \oplus \mathbb{Z} / (q-1) \oplus \mathbb{Z}_p^N$ for some $N$. This is Proposition II.5.7 of Neukirch's Algebraic Number Theory. It should thus suffice to consider each of these components. The only difficult part here is $\mathbb{Z}_p$, whose dual is the Prüfer group $\mathbb{Z}[
p^{-1}]/\mathbb{Z}\cong\mathbb{Q}_p/\mathbb{Z}_p$.


Send EMAIL via PL/SQL script

Question: I have the following procedure which I received from Internet
CREATE OR REPLACE PROCEDURE send_email (
p_sender IN VARCHAR2,
p_recipient IN VARCHAR2,
p_message IN VARCHAR2
)
AS
mailcon UTL_SMTP.connection;
BEGIN
mailcon := UTL_SMTP.open_connection ('localhost');
UTL_SMTP.helo (mailcon, 'localhost');
UTL_SMTP.mail (mailcon, p_sender);
UTL_SMTP.rcpt (mailcon, p_recipient);
UTL_SMTP.DATA (mailcon,
'From: '
|| p_sender
|| UTL_TCP.crlf
|| 'To: '
|| p_recipient
|| UTL_TCP.crlf
|| 'Subject: SMS From Database'
|| UTL_TCP.crlf
|| p_message
);
UTL_SMTP.quit (mailcon);
END;

This procedure is being successfully compiled.
While executing the procedure
exec SEND_email('firstname.lastname@example.com', 'firstname.lastname@example.com','My first EMAIL');

I receive the following error message
ERROR at line 1:
ORA-29279: SMTP permanent error: 554 Can not connect to e-mail server. Error:100502
ORA-06512: at "SYS.UTL_SMTP", line 17
ORA-06512: at "SYS.UTL_SMTP", line 98
ORA-06512: at "SYS.UTL_SMTP", line 138
ORA-06512: at "PERFECT.SEND_SMS", line 9
ORA-06512: at line 1

Please help
Comment: Are you sure you have a mail server running locally (i.e. `localhost`)? Do you manage to send simple email?
Comment: Do you mix "SMS" with "E-Mail"?
Comment: @J.Chomel yes its in Local server
Comment: Did you check [ducumentation](https://docs.oracle.com/database/121/ARPLS/u_smtp.htm#ARPLS71460): *The invoking user must have the connect privilege granted in the access control list assigned to the remote network host to which the user must connect.* See https://docs.oracle.com/database/121/DBSEG/fine_grained_access.htm#DBSEG99981
Comment: @WernfriedDomscheit I wanted to but Now I need only to send SMS... So removing that email id will help?? But sender would be from a registered email id and receiver id would be number@
Comment: `SMS` = `Short eMail Service` ? Also clearly you are using `Oracle`. Please remove the `SQL Server` tag
Comment: No, "SMS" means `Short Message Service`, completely different to "SMTP" `Simple Mail Transfer Protocal`
Comment: @Squirrel No SMS is short messaging service. Yes iam using oracle
Comment: Have you tried using UTL_MAIL instead?  It's usually much simpler.
Comment: The error indicates that your localhost mail server is accepting the connection, but it's getting SMTP error 554 which is fairly vague one that probably means it's not allowed to connect to the recipient mail server.
Answer: Test it first
Test first if your SMTP server works. You need telnet utility (or similar, nc netcat may work too) for it.
ip-172-31-3-158:~$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 ip-172-31-3-158.eu-west-1.compute.internal ESMTP Exim 4.86_2 Ubuntu Thu, 09 Nov 2017 10:55:59 +0000
MAIL FROM: email@example.com
250 OK
RCPT TO: firstname.lastname@example.com
250 Accepted
DATA
354 Enter message, ending with "." on a line by itself
From: email@example.com
To: firstname.lastname@example.com
Subject: SMS From Database

message body
.
250 OK id=1eCkVW-00018X-Ak
QUIT
221 ip-172-31-3-158.eu-west-1.compute.internal closing connection
Connection closed by foreign host.
ip-172-31-3-158:~$

Then check if you receive 250 OK and finally if your message arrives to destination email.
Why it fails
Please note you are sending through localhost an email advertising himself as originating from gmail.com account. The most probably it will be a problem because your localhost SMTP server is not authorized to send emails as gmail.com. The email might be instantly rejected or queued and finally dropped.
So it means, the pair: SMTP server and mail domain, are important. Use smtp.gmail.com to send as email@example.com and use smtp.acme.org to send as firstname.lastname@example.com. This mechanism is to avoid faking email addresses. This statement is kind of simplification but you get the idea.
Send as Google
What do you need to do to send as Google user? Connect to Google SMTP server itself  (port 25 will not work, SSL connection is required to smtp.gmail.com:465), authenticating yourself and then send an email. Test it with raw SMTP protocol first. It is more complicated than it looks at the first sight - extra db setup is required to reach external SMTP (not localhost one) and SSL might be an issue for Oracle. Look for more practical solution below.
Practical Solution
Another, better option is to send the email from your organization's SMTP server (or indeed your localhost) with your SMTP domain in the email address. Usually organization allow to send email without an authentication, from clients within the organization's IP address range.
So assumming you want to stay with the localhost, just provide the real email address (assuming you're acme.org and the database runs from oracle user, use from: firstname.lastname@example.com). "Test it first" - if it works with telnet and the email is delivered, focus on PLSQL part then.

Send EMAIL via PL/SQL script


Strange behaviour with ng-model binding and checkbox

Question: I'm trying to intercept a checkbox change so I can put a confirmation stage in the middle and I am experiencing strange behaviour.
When I click the checkbox preventDefault is stopping the UI from changing the checkbox, except the bound model will change once and then no longer be changeable.
Any ideas on how I can fix this? Am I approaching this wrong?
$scope.change = function(selected, $event){
      $event.preventDefault();
    };

https://jsfiddle.net/tcVhN/197/

edit: Answers to JB's questions below:

I am trying to intercept the checkbox change so I can put a confirmation step in the middle IE "Are you sure you want to change
  this text box?"
Just updated to 1.47 (and updated jsfiddle link).
I'm using ng-click because ng-change doesn't pass the event
  through which means I can't cancel the ui change via
  $event.preventDefault.
See above.
Comment: Btw, you have a typo. Change `event.preventDefault()` to `$event.preventDefault()`.
Comment: 1. explain why you need to prevent default, 2. explain why you use an oooold version of angular, 3. explain why you use ng-click and not ng-change, 4. explain why you need the change function in the first place. The automatic model change should be sufficient to achieve what you want.
Comment: Hey JB added answers to you're questions to the main question.
Answer: I have modified your Fiddle to make it work:
https://jsfiddle.net/masa671/8qrct4y2/
Notice the change in HTML: ng-model="x.checked" to ng-checked="x.checked".
JavaScript:
$scope.change = function(selected, $event){
    $event.preventDefault();
    $timeout(function () {
        if (window.confirm('Are you sure?')) {
            selected.checked = !selected.checked;
        }
    });
};

The key problem for me was to find out, how to prevent the checkbox status from changing until the user has confirmed the change. I don't know the best/right solution, but I resolved this so that the event handler just prevents the default behaviour, and the actual change is handled outside the event handler with the help  of $timeout.
At least the Fiddle seems to work in a sane manner... :-)


HTML - checkbox conditionally checked

Question: I have written this simple jsp page: I want to show a simple list of object (Person), with a label (showing the name of the person) and a checkbox (that shows if the person is at least 18 yo).
I also write the corresponding Java class 'Person', with a String (name) and a boolean (isAdult).
Here is my jsp (personList is a List of Person objects)

     NAME
     IS ADULT
        <c:forEach var="person" items="${personList}">

             ${person.name}

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

        </c:forEach>

This portion of code shows me a list in which all checkboxes are not checked (names are correct.
How could I obtain that every checkbox in the list is checked (or not), referring to the boolean attribute 'isAdult' of the Person object?
Answer: You can use EL ternary operator like this:
 <input type="checkbox"  ${person.adult ? 'checked' : ''}>

${person.adult} will invoke isAdult method that encapsulating adult attribute.

HTML - checkbox conditionally checked


Hidden div appearing and backgrounditems dissapear/unvisable

Question: My project is a content based Website for my mother and her Children-daycare.
You can see the project on the domain: Diekleinenfreun.de
Now, as you see on the Website I have the navbar on the left.
And what I did is I used a simple javasyriptcode to make a div set to display:block; on mouseOver and none when mouseOut again.
I want to fill the div with content later. as a preview or an image or so.
My problem with this div is the alignment. As you can already see on the Page login, the div in making problems with any other content in the middle.
I first had the div set to relativ, wich solves the problem if the browserwindow's size is changed, but it pushes all other items in the middle down obviosly.
So what I need is this div not changing any other item in the middle, but rather blurring them out and laying over them if you understand what i mean.
The code I use:

<input onMouseOver="toggle_visibility('login');" onMouseOut="toggle_visibility('login');" type="button" class="nav_login" value="Login" />

a

.login_middle {
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  width: 760px;
  height: 70%;
  top:243px;
  position: absolute;
  bottom: 0;
  overflow: hidden;
  border: none;
  font: normal 16px/1 Georgia, serif;
  color: rgba(255,255,255,1);
  text-align: center;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  background: rgba(18,50,145,0.85);
  text-shadow: 1px 1px 1px rgba(0,0,0,0.2) ;
  display:none;
}

Or the original CSS class, which messes with the items in the middle, but is resized automaticly:
.login_middle {
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  width: 760px;
  height: 100%;
  position: relativ;
  bottom: 0;
  overflow: hidden;
  border: none;
  font: normal 16px/1 Georgia, serif;
  color: rgba(255,255,255,1);
  text-align: center;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  background: rgba(18,50,145,0.85);
  text-shadow: 1px 1px 1px rgba(0,0,0,0.2) ;
  display:none;
}

Comment: The intended behaviour seems to be unclear. So you have default content on the page, but if the user hovers a menu item, an additional element should cover the original content and show something else?
Comment: Yes, a div box should cover it and not mess with the positions of the original content
Comment: Right now, your site features a table-based layout (which is not the best option anyways) and all the content divs for your menu items are inside the middle column. By hovering a menu item, one of these content divs is shown while the others are hidden. I don't see a problem right away.
Answer: In my opinion, it would be much better if you stuck to conventional web design practice, and used a separate .html page for each page of content, instead of doing this Javascript mouseover as you are.
You could easily transform this layout into a responsive three column design template, which you could use for each page of your site.  Doing it this way, your site can be displayed nicely on mobile, which is now important.  As it is, display on mobile is not looking good.
Rgds
Comment: The actual content for each site will be a different html page or outsorced, but what i want is just a div over the content that is shown right now while hovering ofer the navbar
Answer: If I understood your question, you are having an issue with the middle container (it's located inside a TD in your website) when it's resized.
To stop that just remove width: 760px; from the .login_middle{...} and other css classes such as .home_middle{ ...}, etc. or you could set width: 100%;.
To fix the issue of content pushing to the bottom, change/add css as below.
.table_mid{
  ....
  position: relative;
}

and every css class you use for middle content for example, kontakt_middle
(according to your .kontakt_middle class at the time of writing, just set the position attribute)
.kontakt_middle{
  .....
  position: absolute;
}

Also, I noticed in other css classes you used; for example, .links_middle{} - remove top attribute and set height to 100% as you have already done to .kontakt_middle{}.
I hope this helps.
Comment: not only the TD is resized, the content of the TD is pushed under the Div, thats the main problem
Comment: What is the browser, it's version and OS you are using? I cannot generate that issue from my end.
Comment: I use Chrome and im on Windows 10 64bit. But try clicking on login, there is already some content and the problem i mean you see if you hover over the button "Kontakt"   -> The div is pushing the content down
Comment: Ok, I managed to generate the issue. I will add the solution for it in to my answer above.
Comment: As you can see now, i changed it like you said. it dows work, but the size of the div is the whole screen now   EDIT: Nevermind, my mistake, i mispelled relative. THANK ALL OF YOU ALOT!


Detailed description/scripts of mathematical models for Coronavirus

Question: Pretty much the title, I am looking for some more in-depth explanation of the models used in the papers from Imperial College and The Lancet. In the second one, they are using something called a branching process model, but they are sampling from strange distributions (like serial interval
distribution), which I have never heard about.
If anyone has a good resource, or better even a working R, Matlab or Pyhton scripts, any help would be much appreciated. I would like to put the models on my Shiny dashboard, which my team uses for reporting/creating graphs for my bank.
Edit:
I am mainly interested in this graph:

So my colleagues could play around with the parameters and create different scenarios.
Comment: It sounds like you are looking for an epidemiologist. Who is your team if you don't mind me asking?
Comment: https://mathoverflow.net/questions/354082/relevant-mathematics-to-the-recent-coronavirus-outbreak/354911#354911
Comment: If you'd like a popular science book, theres this one https://www.goodreads.com/book/show/48475750
Answer: The lancet article
The method from the article in the Lancet is very straightforward. They model the spread of the virus by simulating the transmission on the level of each single infected individual. For each infected person they compute (randomly) how many other people they will infect and how long it will take for those others to infect others (or how likely it is that the others get contained due to policy measures like quarantaine).
They use this model to estimate the variation of the potential number of new cases after some given time, by computing the random model a thousand times for each particular set of model parameters. If the number is large then they consider the outbreak uncontrolled and then this stochastic model can be used to express the probability to control the outbreak for a given set of parameters.
So the difference between a deterministic model and stochastic model is the following:

deterministic The virus spreads with a constant number and and speed. For instance each person passes on the virus to two others in a given specific time interval and then the growth will be like 1,2,4,8,16,etc.

stochastic The spread of the virus is random. By how many it increases is random and not every time the same factor. Some people spread a lot others only a little. For instance sometimes a person passes it on to three other people, and sometimes only one (but on average the same namely two). And then the growth will be random it may be high (when it triples a lot) it may be low (when only one person gets it). This randomness is expressed by repeating the model several times and then see how it ends up in all those cases.

The serial interval distribution is explained in Figure 2 a . I haven't read the article in detail, but after a quick scan it seems to me that the serial time is the time between the moments that a person infects another person. The serial time distribution is the distribution of those times. It is not the name for a specific distribution.
Note that the code of the Lancet article is available online. https://github.com/cmmid/ringbp/tree/master/R
The imperial college article
The infections will not continue exponentially. This is only in the very beginning. The reason why the infections rate decreases is because you can't infect a person that is already infected before. So the probability to spread the virus becomes less in time. (also, the infection rate depends on the weather/season as well, sometimes called respiratory season, that is I believe not incorporated in those models)
A well known model that takes this decrease of infection rate into account is the SIR model (and this will already produce graphs like the ones you are looking for). However that model assumes homogeneous mixing which is not very realistic. So the model that they use at imperial college uses many smaller compartments which are schools, workplaces, households and probably some more. Then the spread occurs differently at different levels/distances. You can not infect your housemates when they are already sick, so often it is only one person that infects all the others members in the family (and that person has a relatively high transmission) and the others will spread relatively less (but they can pass on the virus in other places, like school work church etc. If these are not saturated yet.
This is not easy to replicate. What you need to do is model the spatial structure realistically. Like age distribution in households and the networks of who is going to which work/school/church etc. A description of this work is given in one of the references. The model is normally used for influenza. https://www.pnas.org/content/suppl/2008/02/28/0706849105.DC1

I have made a toy model that sort of showcases these effects (but not with realistic distributions). What you get is not exponential growth but instead more something like a power law. The distribution grows in space and spreads at the edge of the infected population. It is a bit like the growth of area of a circle as function of it's circumference. $dA/dt = \text{constant} \times \text{circumference}$ but then for a fractal dimension structure.
The result of the toy model is a curve that is in the beginning exponential (homogeneous mixing growth), but then changes into a power law relationship (growth at the edge of some geometric figure). In any case the growth is not exponential with a continuous rate, but instead the dynamics is changing (in this example the growth is only exponential for the first 5 generations).

# create 500x500 people in matrix
set.seed(1)
L <- 5*10^2
people <- matrix(rep(0,(L)^2),L)

# trackers for the locations of the people that got sick:
# we start with index patient in the middle
orderx <- c(round(L/2))
ordery <- c(round(L/2))
generation <- c(1)
spread <- 0
R0 <- 3
R1 <- 0.25  # a probabiliy to spread the virus on long distance, e.g. due to travel.

##### run the virus ######

# compute probability density function
# for probabilty of spreading out to nearby locations
Lr <- 7
Lspread <- 1+Lr*2
# targets will be in a cube of LrxLr around the patient
targets <- matrix(1:Lspread^2,Lspread)
xt <- matrix(rep(c(1:Lspread)-(Lspread+1)/2,Lspread),Lspread)
yt <- t(xt)
# ps is some probability to get infected as function of distance
ps <- c(exp(-c(Lr:1)*0.2),0,exp(-c(1:Lr)*0.2))
probs  <- ps[xt+(Lspread+1)/2]*ps[yt+(Lspread+1)/2]

### plot for visualization of the spread

plot(orderx,ordery,xlim=c(1,L),ylim=c(1,L),
     xlab = "", ylab= "",
     col=1,bg = 1,cex=0.2,pch=21)

# itterate all the patients untill all have been dealt with
# during this loop the number of patients increases
while (spread < length(generation)) {
  spread <- spread + 1
  x <- orderx[spread]
  y <- ordery[spread]
  g <- generation[spread]

  # selecting Rn people in the neighbourhood of the patient
  # Rn is sampled from a Poisson distribution with mean R0
  Rn <- rpois(1,R0)
  if (Rn>0) {
    sel <- sample(targets,Rn, prob = probs)
    xt[sel]
    yt[sel]
    ## this loop picks out the R0 people
    ## these are gonna become new patients if they are susceptible
    for (i in 1:Rn) {
      #the modulo is to patch left with right and top with bottom
      xq <- (x+xt[sel[i]]-1)%%L+1
      yq <- (y+yt[sel[i]]-1)%%L+1
      # if the 'target' is not sick yet then add it as new patient
      if  (people[xq,yq] == 0) {
        generation <- c(generation,g+1)
        orderx <- c(orderx,xq)
        ordery <- c(ordery,yq)
        people[xq,yq] <- g+1
        colv <- (g+1)/30-floor((g+1)/30)
        points(xq,yq,
               col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21)
      }
    }
  }
  ### additionally make R1 random people from far away sick
  nfar <- rpois(1,R1)
  ifar <- 0
  while (ifar<nfar) {
    ifar = ifar +1
    xq <- sample(1:L,1)
    yq <- sample(1:L,1)
    if  ((people[xq,yq] == 0)*(rbinom(1,1,0.1)==1)) {
      generation <- c(generation,g+1)
      orderx <- c(orderx,xq)
      ordery <- c(ordery,yq)
      people[xq,yq] <- g+1
      colv <- (g+1)/30-floor((g+1)/30)
      points(xq,yq,
             col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21)
    }
  }
}

# ratio of people that got sick
spread/L^2

# plot the spread in colours
colv <- (generation+1)/40-floor((generation+1)/40)
plot(orderx,ordery,xlim=c(1,L),ylim=c(1,L),
     xlab = "", ylab= "",
     col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21)

# plot the epidemiological curve
I <- sapply(1:50, FUN = function(x) sum(generation == x))
plot(I, log = 'xy',
     xlab = "x, generation", ylab = "number of infectious people", type = "l",
     ylim = c(1,5*10^4), xlim = c(1,70))
gen <- 1:50
colv <- (gen+1)/40-floor((gen+1)/40)
points(I,pch=21,col = 1, bg = hsv(colv,1,1))
lines((R0+R1)^c(0:50), lty=2)
sm <- 4:50
lines(sm,0.5*sm^3.5, lty = 3)
lines(sm,0.002*sm^6, lty = 4)

legend(1,5*10^4, c(expression((R[0]+R[1])^x),expression(0.5*x^3.5),
                   expression(0.002*x^6)), lty = c(2,3,4),
       xjust = 0, cex = 0.7)

Answer: I know answers aren't supposed to be just links, but this is the best I can do.
This page links to a number of public covid 19 studies done in R.
https://refind.com/znmeb/r-tools-for-coronavirus
This one Focuses in-depth on epidemiology models.
https://timchurches.github.io/blog/posts/2020-02-18-analysing-covid-19-2019-ncov-outbreak-data-with-r-part-1/
Direct link to some of the cool stuff.
https://www.statsandr.com/blog/top-r-resources-on-covid-19-coronavirus/


entity reference as attribute, is it possible in commerce v2?

Question: User story:
The end-users should be able to pick an image from an image gallery and attach that image to a product before adding it to cart
In Commerce v1 this was possible via line items by defining an entity reference field, along with a couple of other modules e.g. entityreference view widget. A sample, although not 100% finished, can be found in d7demo when you click on the 'add item' button.
I used entity reference since the images are actually nodes with a file field, so that i could also categorise them via term references.
Is the above functionality somehow possible on commerce v2? I cannot find  'line items' as used in v1, but only attributes and variants. However i cannot seem to find the way (configuration or contribs) to achieve the above functionality.
Any pointers to the above issue are very much appreciated.
Comment: Line items are named "Order items" now, and work in a similar way as commerce_customizable_product worked in D7 (attach fields to an order item type, expose them on the add to cart form by using the the "manage form display" tab).
Comment: You should clarify your question. Reading it, I am unsure whether you want to select an attribute using an image (fancy attributes) or allow the customer to upload an image before adding the product to cart (exposed line item field, nothing to do with product attributes).
Comment: Bojan thanx for your reply. I rephrased my initial question making it hopefully more clear.
Answer: Since product attributes are entities in CommerceV2, the following module should cover your needs => https://www.drupal.org/project/entity_browser
Some points to consider:

It is still in alpha
It is strongly supported at the moment by the community and especially the Drupal Media Team
It has more than 5K downloads.

There is also a recent presentation available from DrupalCon Dublin 2016 => https://www.youtube.com/watch?v=VXor-HZiYrs
Update:
Following the documentation, you may also need to look into "Product Variations Fields", http://docs.drupalcommerce.org/v2/product/products.html.
This CV2 functionality seems to allow you to expose specific fields to the end-user for e.g. uploading images in order to modify/configure a product.
Good luck!
Comment: Another relevant page might be http://docs.drupalcommerce.org/v2/product/product-attributes.html, but reading the question it does sound like the OP needs an exposed line item field, not a product attribute.


How to use entityform and ajax_form_entity in a modal window?

Question: Just getting started with the entityforms module (and it looks sweet!).  I want to create a 'contact us' link that displays the form in a modal window, submits and then closes the window.
There is a related module, ajax_form_entity, that looks like it would help make a clean submission.  The demo site has a 'Views popup integration' section, but that doesn't look useful (or relevant, actually).
Anyone know how I can do an ajax submit of an entity form from a popup?
Answer: There is a sandbox module called Modal Entity Forms https://drupal.org/sandbox/andreymaximov/2058521
It depends on the Modal Forms module and will work in the same way, but for entity forms. I have tested the module and it works fine for now, although I want to submit 1 or 2 patches to extend it's functionality.
EDIT:
There is now a new module called Modal operations: https://www.drupal.org/project/modal
It's currently dev only (still better than sandbox) and so far it seems to work fine.


Counting North-East Lattice Paths

Question: I have been assigned the following homework problem:

Let $f(m,n)$ be the number of north-east lattice paths which exist from $(0,0)$ to $(m,n)$.
(i) Show that $f(m,n) = f(m-1,n) + f(m,n-1)$.
(ii) Show by induction that $f(m,n) = \binom{n+m}{n}$.

I've been reading around (the concept of north-east lattice paths is entirely new to me), but still cannot seem to wrap my head around an approach to this problem. Any help would be greatly appreciated!
Comment: At each step, you either go north or you go east. If you're at $(m,n)$ with $m,n$ both being positive, how many ways are there to get there, if your last step was north? How many ways if your last step was east? What do you do with these numbers?
Answer: Assuming $m,n >0$, we have the picture below. The only ways to
get to $(m,n)$ are to start at $(m-1,n)$ and go east
or start at $(m,n-1)$ and go north.
Since the last segment of the path is distinct, for $m,n>0$ we have
$f(m,n) = f(m-1,n)+f(m,n-1)$.

If $m=0$ and $n>0$, we see that there is only one path
and $f(0,n) = n$.
Similarly, $f(m,0) = m$.
Using induction, we see that once we specify the south west boundary values, that
all the other values are uniquely defined.
It is easy to check that $f(0,n) = \binom{n}{n}$ and $f(m,0) = \binom{m}{m}$,
and since $\binom{n+m}{n} = \binom{n+m-1}{n} + \binom{n+m-1}{n-1} $,
we see that $g(m,n) = \binom{n+m}{n}$ satisfies the difference
equation and the boundary conditions, hence $f=g$.

Counting North-East Lattice Paths


Solution of second order DE as a ratio of sinh

Question: I have the following second order DE:
$\xi'' - k^2\xi = 0 $
$\xi(a) = 0$
I've managed to bring it as far as $\xi = -c_2[e^{k(x-2a)}+e^{-kx}]$, by writing the solution as $\xi = c_1e^{kx}+c_2e^{-kx}$, using the given condition and solving for $c_1$.
The problem is, my book gives the solution as $\xi = c\frac{sinh[k(a-x)]}{sinh(ka)}$.
I guess it's not a difficult problem, but I just don't see it. Does anyone have any ideas?
Thanks!
Answer: The denominator is just a constant
$$\xi = c\frac{\sinh[k(a-x)]}{\sinh(ka)}=K{\sinh[k(a-x)]}$$
Then mutliply by $e^{-ka}$ and $\sinh(x)=\dfrac {e^x-e^{-x}}2$
$$\xi =\frac R2({e^{[k(a-x)]}-e^{-ka+kx}})e^{-ka}$$
$$\xi =\frac R2({e^{-kx}-e^{-2ka+kx}})$$
Substitute $\frac R2=C$
$$\xi =-C(e^{k(x-2a)}\color{red}{-{e^{-kx}}})$$
Are you sure you don't have a sign mistake somewhere ?
Comment: You're right, should've been a "-" sign before the second exponential in my solution. Thanks for pointing this out! So it seems the results are equivalent, but I still have no idea how one would ever think of getting to the one in the book.
Comment: @Bogdan_C  your answer is correct except for the sign...so it dosent matter what the book says as long as your answer is correct...You can keep the exponential in the solution or use hyperbolic function dosent really matter...It's just for convenience..


State the domain of $f^{-1}$

Question: $$f(x)=\sqrt{2x+5}$$
$$x \geq -2.5$$
State the domain of $f^{-1}$
\begin{align}
\ x & = \sqrt{2y+5} \\
\ \Rightarrow f^{-1}(x) & = \frac{x^2-5}{2} \\
\end{align}
The Mark Scheme  says that the domain is $x\geq0$
Is the Mark Scheme wrong or am I?
Let $x=-3$
$$\frac{(-3)^2-5}{2}=2$$
I thought the domain was the values of $x$ you can put into the function without getting an "error".
Answer: Note that when you're dealing with inverse function of $f(x)$, say $g(x)$, your range of $f(x)$ typically will be your domain for $g(x)$.
In your case, your $f(x)= \sqrt{2x+5}$, and hence, has a range that takes on values from $[0, \infty)$. This implies that, your domain for $f^{-1}(x) =g(x)$ is $[0, \infty).$
Comment: You may find this helpful: https://cims.nyu.edu/~kiryl/Precalculus/Section_2.7-One-to-One%20Functions%20and%20Their%20Inverses/One-to-One%20Functions%20and%20Their%20Inverses.pdf
Comment: Why? It makes sense why $f(x)= \sqrt{2x+5}$ is restricted but not $f^{-1}$
Comment: It makes sense because $f(x)$ is a one-to-one function, you can show this using the horizontal line test. The definition for an inverse function for $f(x)$, is given by $f^{−1}(y)=x \iff  f(x)=y$. Now, say the domain for $f(x)$ is given by A. Precisely, by the preceding definition, each value of $y$ in the domain of $f^{−1}$ has exactly one $x$ in A.
Comment: Does it have to be one-to-one because $f(x)= \sqrt{2x+5}$ is restricted? Are you essentially inversing the domain as well the function?
Answer: any x in the domain must satisfy the equality
$$x = \sqrt{2y + 5}$$
therefore $x\geq0$.
Answer: Hint:
squaring $x=\sqrt{2y+5}$ you must have $x\ge 0$
Comment: $x^2=2y+5$ What am I missing?
Comment: You have missed the condition $x\ge 0$ because $\sqrt{2y+5}$ is a positive number.

State the domain of $f^{-1}$


Cox Regression - Output at Individual (observation) Level

Question: I am building an attrition model. I was able to run the following cox regression. The rate of attrition looks very low, but I am only basing that on the plot I ran below. I would like to get a prediction for each case if they will attrit* and when**. Is that possible with the coxph function?
cox3 <- coxph(Surv(Raw_months, Attrit) ~ Raw_age + Ethnicity_dummy + Interim_grade + Retirement_dummy, data = Copy_of_fake_data_V2)
summary(cox3)
cox_fit3 <- survfit(cox3)
plot(cox_fit3,main = "cph model", xlab="months")

In the table below, * and ** are the new columns I want for each person in the data set

Unique Id
Raw_months
Attrit
var. 1
var. 2
Will they attrit?*
When(months)**

1
324
0
0
6
1
5

2
14
0
1
4
0
67

3
62
1
1
3
N/A
N/A
Comment: Your data seem to be internally inconsistent. For the first row, you have `Attrit=0` but also `Did they attrit?=1`. For the second row, both values are 0. For the third row, it's not clear why you have N/A for `Did they attrit?` when you have `Attrit=1`.
Comment: EdM the Attrit columns is historical. Did the person attrit in the span of data. The Did they attrit is the person going to quit and the next column is when. If a person already attrited, those columns wouldn't make any sense because the person already left.
Comment: In other words, what you want in the new columns is a prediction for each individual about whether there will be attrition and, if so, when?
Comment: Yes that is exactly correct.
Answer: This follows up on a related question that states an interest in predicting attrition over the next 5 years. The Cox model in this question is for time to attrition, starting from the date of hire into a firm.
This starts with an answer to the question as posed, even though that might not be the best way to approach the overall attrition-prediction problem. At the end will be a brief discussion of a better approach.
Outline of solution
First, you need to get a survival-time estimate for each individual based on covariate values and your model. With your model, the survival-time estimate will be relative to the date of hire. Functions with names like predict() or quantile() can make such estimates. We'll discuss below what to use as a survival-time estimate.
Second, to predict attrition over the next 5 years, you need to convert the survival-time estimates to put them in a scale of months from a new fixed reference time shared by all. For simplicity, use the date of the last data pull mentioned in the related question, 11/2020, as that reference. For example, if the survival-time estimate for an individual is 180 months from date of hire and that individual had 140 months of service as of 11/2020, then the estimated survival beyond the new reference time would be 40 months. That can give you estimated survival beyond the new reference for all individuals, filling in your When(months) column.
Then, if you are interested in 5-year survival beyond 11/2020, your prediction for the Will they attrit? column would be whether the predicted survival beyond that date is less than or greater than 60 months.
Handling predictor variables
Your model implicitly is based on predictor values that were known at date of hire. For example, Ethnicity_dummy and Raw_age (which I take to represent age at hire) fit that requirement. The Interim_grade and Retirement_dummy, in contrast, seem to be predictors that aren't fixed at the date of hire and that could change over time.
If you nevertheless include the current values of Interim_grade and Retirement_dummy in your model, (1) you are effectively assuming that those values held throughout the time since hiring and (2) you are running a big risk of survivorship bias. If you want to include such predictors you need to set up and analyze the data to accommodate time-varying covariates. Your outcome value would then be Surv(startTime, stopTime, event), potentially with multiple rows per individual, where startTime and stopTime represent the period over which a certain set of predictor values hold for an individual. Note that this might complicate your predictions for the next 5 years, as you will then need to estimate future changes in those covariate values.
Consider adding other predictors to your model and more flexible modeling. The year of hire, for example, could be included to see whether there were changes over calendar time in the attrition tendency. For that, Raw_age, and other continuous predictors you should consider something beyond a simple linear predictor form; restricted cubic splines, as implemented for example in the R rms package, allow the data themselves to help determine the proper relationship between the predictor and outcome. You also could incorporate interaction terms between predictors, to allow for the influence of one predictor on outcome to depend on the value of another predictor. With about 2000 events you might be able to include up to 100 predictors (including their interactions) in your model without overfitting, so think big in terms of what to include.
Model-type and survival-time choice
The considerations above hold regardless of the type of survival model that you choose. Your work will probably be easier if you use a parametric survival model (e.g., survreg() in the survival package or psm() in the rms package) instead of a Cox model.
With a properly fit parametric model, things like estimated mean survival for a set of predictor values can be determined analytically. You also aren't constrained by the proportional-hazards assumption of a Cox model, as some parametric forms like the log-normal don't require that, modeling accelerated failure times instead.
A Cox model is best for evaluating relative hazards, as the baseline hazard is purely empirical. If the observations at the longest survival times are censored (which seems to be the case with your data), you can't even get a true mean survival time estimate. (You can get a "restricted mean," calculated out to a specified time before the last event.) Provided that your data go out far enough in time (as yours seem to) you can nevertheless get estimates of predicted median survival from a Cox model, so you could continue with the Cox model if its assumptions are met and a median estimated survival or a restricted mean survival are suitable for your predictions. I'm not sure whether median or mean survival-time estimates would be best from your perspective of 5-year predictions going forward, but with 2000+ events you should be able to play around with the data from the prior 5 years to see what works.
A better approach
The above attempt to provide a specific survival time for each individual leads both to a false sense of precision and to some predictions that won't make sense. All individuals with the same set of covariate values will have the same predicted survival after hire, even though there is a wide distribution (over decades, in this case) of survival times for any given set of covariate values. Furthermore, you will find a lot of individuals whose predicted survival time will be earlier than their survival to date. So their predicted times-to-attrition will be negative!
What you really want to know is the probability that an individual will survive for 5 more years, given survival up to the present.  Pooling that information over all individuals of interest, you will get the overall survival (or attrition) for the next 5 years. The considerations above for building the model still hold, but your application of the model is more likely to be useful if you use this approach.
The survival model provides the probability of survival as a function of time from the date of hire. You should take advantage of those probability estimates. Instead of estimating a particular survival time for each individual, use the survival model to estimate his or her probability of having survived from hire through the time of the data pull at 11/2020. Then estimate the probability of survival for that individual from hire through 11/2025. The ratio of the second probability to the first is the probability of surviving 5 more years, given survival through 11/2020. The 5-year attrition probability is 1 minus that value.


All the ways to return 3 if you get 7 and vice versa – interview question

Question: This is a question that I was asked in an interview:
Implement a function that gets an integer n and does the following:
1. if n is 3 -> return 7.
2. else if n is 7 -> return 3.
3. otherwise return any number you like (undefined behavior).
Also describe what's the runtime and space complexity of each way.
So first I gave the trivial way of using if-else statement - and said it's O(1) run-time + space complexity. Then the interviewer said: "what if you can't use if statements (including switch-case and other if statements similarities)?"
So I suggested using bitwise operations: return n^=4. Said that it's O(1) run-time + space complexity. Then the interviewer said: "what if you can't use bitwise operations?"
So I suggested using an array like this:
int mem[8] = {-1, -1, -1, 7, -1, -1, -1, 3};
return mem[n];

Said it's O(1) run-time + space complexity, how ever it might be non-efficient if we have large numbers instead of 3 and 7.
Then the interviewer said: "what if you can't use arrays?" - and here I got stuck.
It seems like there is a fourth way... any suggestions?
Comment: Did the interview not ask `what if you can't use +,-,*,/,%`?
Comment: @vivek_23 lol, added 2nd solution without using math operation
Answer: how about
def foo(n)
  return 10 - n
end

foo(3) => 7
foo(7) => 3

Answer: How about this

function myfunc(n) {
   return 21 / n
}

console.log(myfunc(7))
console.log(myfunc(3))

UPDATE: #2 Solution

function myfunc(n) {
   return "37".replace(n, "")
}

console.log(myfunc(7))
console.log(myfunc(3))
Comment: Nice one , +1. However I have a preference for the subtraction way, since this one will cause an error when n is 0.
Comment: You're right.
Idk why did I think about division first rather than substraction lol
Comment: @ChristhoferNatalius Nice +1.
Answer: Another one is. (n + 4) % 8.
"All the ways" is surely infinite.
Answer: Memo Solution:
function myFunc(x){
 const memo = {7:3,3:7}
 return memo[x]
}
console.log(myFunc(3))
console.log(myFunc(7))

Answer: The fourth way:
def foo(n):
    return 10-n

For n=7, foo(7) returns 10-7=3.
For n=3, foo(3) returns 10-3=7.
For any other value of n, I can return any number I like, so I return 10-n.

So, time complexity: O(1) and space complexity: O(1).
Disclaimer: I'm not the interviewer. :P
Answer: XOR Solution

function XorSolution(n) {
  return n^4
}

console.log(XorSolution(7))
// 3
console.log(XorSolution(3))
// 7

Why does this work?
The truth table for XOR (Exclusive OR) is:
0^0 = 0
0^1 = 1
1^0 = 1
1^1 = 0

3 in binary is 011
7 in binary is 111
4 in binary is 100

XOR is a bitwise operation (performed on each pair of corresponding bits)
So 3 XOR 4 is 7 because:
011
^
100
=
111

And
7 XOR 4 is 3 because:
111
^
100
=
011


want to call one phtml file in another phtml file using anchor tag

Question: I'm using Magento.
I want display and call one phtml file as a link in another phtml file…
I have the new.phtml file on the home page. On that I put one link CHECK ALL which display all new products as category page.. It looks like category page. For that I create another phtml file named newproductpage.phtml which has same code of new.phtml. Now I try to call this newproductpage.phtml file @homepage as CHECK ALL link for that I write this code....
<a href="<?php echo $this->getUr('newproductpage.phtml')?>">CHECK ALL

But its not working....
thnx..
Comment: Check this link here = http://stackoverflow.com/questions/13263663/magento-call-cms-page-through-anchor-tag-from-phtml-file
Answer: you call newproductpage.phtml in any phtml file using below code
<?php echo $this->getLayout()->createBlock('core/template')->setTemplate('custom/newproductpage.phtml')->toHtml(); ?>

Answer: Use the below code for rendering your phtml file in another phtml file.
<?php echo $this->getLayout()->createBlock('core/template')->setTemplate('templatefolderpath/filename.phtml')->toHtml(); ?>

For more refinement of your code, you can use the block name and block file name instead of core/template because core/template use the core resources.
Answer: You can not call directly one phtml file to another phtml file.
But there are two way to call your phtml file either create one controller and create one action and call action from your anchor tag or create one cms page which call your phtml file.
if you create one module, so in your layout file something you can write
<modulename_controllername_controlleraction>
    <reference name="content">
        <block type="catalog/product_new" template="custom/newproductpage.phtml" />
    </reference>
</module_controllername_controlleraction>

Or you can directly put this code in your cms page content area
{{block type="catalog/product_new" template="custom/newproductpage.phtml"}}

and in anchor tag give cms page link.
Comment: if i want to display addnewproduct.phtml in new.phtml as link...what to do?
Comment: i want to say that in the new.phtml file i give anchor tag named CHECK ALL and clicking on that newproductpage.phtml file will open..i am confusing with this. And ya.. new.phtml has no XMl file. new.phtml file call as block in the homepage.
Comment: Just add your cms page link to your anchor category link in check all and in cms page put this code `{{block type="catalog/product_new" template="custom/newproductpage.phtml"}}`
Comment: Bro, i dont want to call this block on home page...i already put the block of New.phtml and new.phtml = newproductpage.phtml, both have same feature to see new products. difference is that new.phtml is used as a one block on homepage with other blocks with slider. while newproductpage.phtml is a whole page looks like a category page with left sidebar which shows shop by,compare products,community poll,populartag etc and main has all new products... so can u give me any suggestion for this...!
Answer: <?php echo $this->getLayout()->createBlock('core/template')->setTemplate('catalog/product/new.phtml')->toHtml(); ?>

you can also check the link.
Display .phtml page in another .phtml page
Answer: I believe you and I want to do precisely the same thing.  I'm creating a modal from bootstrap and I need to call in a partial using the href attr.
So far, I think this might be possible by creating a page in the CMS and then using something like this:

<a href="<?php echo $this->getUrl("page-name-in-CMS") ?>">Home

But honestly, I'm just starting out with Magento and know very little.
Comment: thnx bro..we can create the same code cms page and call it using anchor...!!
Comment: Does that mean my answer helped you resolve your problem?  If so, please vote my answer up and select it! :)
Answer: you can use iframe for same and load this another page content using AJAX call
Comment: iframe and ajax will make the things more complicated, instead directly define the block and template file using this code. getLayout()->createBlock('core/template')->setTemplate('custom/newproductpage.phtml')->toHtml(); ?>


Does shared hosting hold some benefits over a VPS?

Question: I was looking a for a windows host for my ASP.NET MVC app and the prices in softsyshosting looked very decent. However i fail to understand, why do they offer codename "Enterprise" Shared hosting at the same price point as the codename "Economy" VPS ?
Enterprise Shared:     http://www.softsyshosting.com/windows.aspx
The First Economy VPS: http://www.softsyshosting.com/windows-vps.aspx
Why would someone be willing to pay the same amount of money for 350GB less bandwith, less database storage, less disk space, no RDP control .. ?
Answer: Generally speaking, the main benefit of shared hosting is that you are not responsible for operating system maintenance, library/application server patches, security, etc.
Conversely, VPS hosting offers more flexibility in configuration, and depending on the provider, offers higher performance. (though this may not always be true)


CentOS Directory Owner

Question: I have a dedicated CentOS 5.6 Server for our webhost. I've setup FTP account in PLESK to access our website. Once I migrated joomla over I can not change/modify or upload new files via: FTP. I've chmod'ed all necessary directory to 777 and 755 but still can't change or modify files.
I then noticed that the directory owner is displays nothing or 48 48.  How do I change the directory's ownership so I can upload and modify files to the FTP users account or did I do something wrong something completely.
Comment: `chown`.  Research also reveals that you might need to contact support if you're using a hosting company.
Answer: <code>$ chown -R <username>:<group> /path/to/directory
</code>
Comment: Note that using a dot as delimiter is deprecated to allow for usernames to have a dot. You should instead use a colon (chown -R user:group /path/to/dir   - the dot still works on e.g. RHEL, but it does not on SLES.
Comment: Good point. Fixed.

CentOS Directory Owner


Adicionar campos em um select

Question: Como que coloca o idautor e o idobra nesse meu SELECT:
CREATE TABLE Obra_Assunto (
            idassunto INTEGER NOT NULL,
            idobra INTEGER NOT NULL,
            PRIMARY KEY (idassunto, idobra),
            FOREIGN KEY (idobra)REFERENCES Obra (idobra),
            FOREIGN KEY (idassunto)REFERENCES Assunto (idassunto)
            );

CREATE TABLE Obra_Autor (
            idobra INTEGER NOT NULL,
            idautor INTEGER NOT NULL,
            PRIMARY KEY (idobra, idautor),
            FOREIGN KEY (idobra)REFERENCES Obra (idobra),
            FOREIGN KEY (idautor)REFERENCES Autor (idautor)
            );

CREATE TABLE Assunto (
            idassunto INTEGER NOT NULL,
            descricaoAssunto VARCHAR(50) NOT NULL,
            PRIMARY KEY (idassunto)
            );

CREATE TABLE Autor (
            idautor INTEGER NOT NULL,
            nomeAutor VARCHAR(50) NOT NULL,
            PRIMARY KEY (idautor)
            );

CREATE TABLE Obra (
            idobra INTEGER NOT NULL,
            titulo VARCHAR(50) NOT NULL,
            ano_publicacao INTEGER NOT NULL,
            quantidade INTEGER NOT NULL,
            ideditora INTEGER NOT NULL,
            PRIMARY KEY (idobra),
            FOREIGN KEY (ideditora)REFERENCES Editora (ideditora)
            );

select nomeAutor,titulo,descricaoAssunto
  from autor a , obra_autor oa , obra o , obra_assunto os, assunto ass
Where a.idautor= oa.idautor AND oa.idobra= o.idobra AND o.idobra= os.idassunto AND os.idassunto= ass.idassunto;

Comment: só colocar `select o.idobra, a.idautor` ... group by você só usa quando trabalhar com função de agregação
Comment: Bom dia, como assim função de agregação ?
Comment: funções de agregação: `max`, `sum`, `min`, `avg` entre outras....
Comment: Mas tipo assim , só vale para duas tabelas ?
Comment: oi ? leia / assista: https://www.devmedia.com.br/sql-funcoes-de-agregacao/38463
Comment: Mas em uma tabela só é simples, eu quero saber como que faz em várias tabelas ?
Comment: da mesma forma... 1 ou n tabelas, só muda os joins, o que você faz com as colunas, é o mesmo... a resposta do lacobus deu certo ?
Comment: deu sim , inclusive boa resposta.
Comment: então marque-a como resposta da questão, e se achar válido, avalie-a como +1
Comment: acesse o [Tour] por favor
Answer: Já tentou algo como:
SELECT
    a.idautor,
    a.nomeAutor,
    o.idobra,
    o.titulo,
    ass.descricaoAssunto
FROM
  autor AS a
JOIN
  obra_autor AS oa ON ( a.idautor = oa.idautor )
JOIN
  obra AS o ON ( oa.idobra = o.idobra )
LEFT JOIN
  obra_assunto AS oas ON ( o.idobra = oas.idobra )
LEFT JOIN
  assunto AS ass ON ( oas.idassunto = ass.idassunto );

A consulta acima vai recuperar somente os Autores que possuam Obras cadastradas. Se as Obras não possuirem Assuntos cadastrados, o campo contendo a Descrição do Assunto virá NULL.
SQLFiddle: http://sqlfiddle.com/#!15/69101/5
Comment: Oi bom dia, nunca tentei fazer algo assim , usando joins.
Comment: você está usando e não sabe, só que com outra sintaxe rs

Adicionar campos em um select


background image zoom in firefox

Question: While I was working on the project I faced with the problem of scaling in firefox under an operating system windows. If you change the scale of the browser page with a 100% up to 90% (for example), cut off the background-image, the problem appears only in firefox and only in windows or ubuntu, on mac os is working correctly. Possibly someone faced and will suggest how you can fix this bug.

example: http://jsfiddle.net/uL53nd7z/1/
div {
    background-image: url(http://oi60.tinypic.com/jal5wh.jpg);
    background-repeat: no-repeat;
    height: 23px;
    width: 23px;
}

Answer: You can add relative units to your height and width with background-size: cover so your image take all the content of your div. Depending on your target audience you can use em or rem so they gonna "follow" the modification of a page.
My code :
html {
    font-size: 12px;
}

div {
    background-image: url(http://oi60.tinypic.com/jal5wh.jpg);
    background-repeat: no-repeat;
    height: 1.916666666666667rem; /*23/12*/
    width: 1.916666666666667rem;
    -webkit-background-size: cover;
    background-size: cover;
}

Result jsFiddle
Comment: I opened Your example and zoomed up to 90%, bug is still there. I`m using the actual version of firefox – 32.
By the way it doesn`t depend of the size of the unit, even if I set the width and height of 35px when I`m zooming the picture is still cut off.
By the way, this problem is present on many sites, for example http://www.apple.com/choose-your-country/ if you set the scale to 80% are cropped language`s icons.
Comment: Got ya, i saw the same problem in firefox. I know this not gonna be an answer but who is zooming back ? :) Nowadays people design for zoom up, just saying. And i saw just now if you zoom back at stackoverflow logo is cropped at bottom...

background image zoom in firefox


React : using nothing but functions?

Question: I am a beginner in developing with React. I learned with the Facebook documentation. I practice with the "Thinking in React" example (go to it). But I tried to change the solution by using nothing but functions.
Here is the result :
function ProductCategoryRow({category, key}) {
    return
{category}
  ;
}

function ProductRow({product, key}) {
    var name = product.stocked ? product.name :

        {product.name}
      ;
    return (

        {name}
        {product.price}

    );
  }

function ProductTable({products, filterText, inStockOnly}) {
    var rows = [];
    var lastCategory = null;
      products.forEach((product) => {
        if (product.name.indexOf(filterText) === -1 || (!product.stocked && inStockOnly)) {

          return;
        }
       if (product.category !== lastCategory) {
          rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
        }
        rows.push(<ProductRow product={product} key={product.name} />);
        lastCategory = product.category;
        });
    return (

            Name
            Price

{rows}

    );
}

function handleFilterTextInput(event) { filterText = event.target.value; refresh() }

function handleInStockInput(e) { inStockOnly = e.target.checked; refresh()}

function SearchBar({filterText, inStockOnly, onFilterTextInput, onInStockInput}) {
    return (
      <form>
        <input
          type="text"
          placeholder="Search..."
          value={filterText}
          onChange={onFilterTextInput}
        />

          <input
            type="checkbox"
            checked={inStockOnly}
            onChange={onInStockInput}
          />
          {' '}
          Only show products in stock

      </form>
    );
  }

var filterText = "";

var inStockOnly = false;

function FilterableProductTable({products}) {
    return (

        <SearchBar
          filterText={filterText}
          inStockOnly={inStockOnly}
          onFilterTextInput={handleFilterTextInput}
          onInStockInput={handleInStockInput}
        />
        <ProductTable
          products={PRODUCTS}
          filterText={filterText}
          inStockOnly={inStockOnly}
        />

    );
  }

var PRODUCTS = [
  {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

function refresh() {
  ReactDOM.render(
    <FilterableProductTable products={PRODUCTS} />,
    document.getElementById('container')
  );
}

refresh();

It works well but :

could I go on this way ?
is there any method to refresh de document in a better way that re-render from the root of the tree ?

Any other comment would be appreciated
Answer: You are using functional components in your implementation. These are fine to use for 'stateless' components. However, if a component has properties that will change, for example, the text in your search bar, then you will want to use React state to handle these changes. Changes on state and props of a component are the two main ways that React intelligently manages re-rendering/ refreshing.
There is no need to re-implement a refresh() function, since the power of React comes from its ability to automatically handle re-rendering based on changes to the state of our components.
Hopefully this information helps. I would recommend watching the Intro to React video and to get a grasp of what React does and why developers use it
Answer: Thanks for the informations.
I have played the video "Intro to React". It is useful for me.
But when I see the Facebook documentation that says :
ReactDOM.render() controls the contents of the container node you pass
in. Any existing DOM elements inside are replaced when first called.
**Later calls use React's DOM diffing algorithm for efficient
updates**.

I wonder why I could not go on with my "refresh" method.
Indeed I am reluctant to dive into Class (that are not real classes !) component, state (that seam's very hard to define correctly) and all that constructor, super, props, this, lifecycle ....... carrying all the this.props. and this.state. notations  ....
Certainly I will encounter some situations were it's mandatory but I would be very please to delay this as much as possible !!!
Comment: You could go on with this method - but, you are missing out on the performance wins of React! The various concepts in React can be quite intimidating when you start learning - but they are there for a reason! React intelligently manages changes to your Components (via `state` and `props`) and **updates only the parts that have changed** - rather than refreshing the entire application! Your `refresh()` function is re-rendering the entire application, and this will cause very poor performance once your app gets bigger.
Comment: I found this https://www.bignerdranch.com/blog/destroy-all-classes-turn-react-components-inside-out-with-functional-programming/?utm_campaign=React%2BNewsletter&utm_medium=email&utm_source=React_Newsletter_78
I am not the only one !
My refresh() will be replace by the renderComponent() method

React : using nothing but functions?


How do I show the "Your Cart" link in my Rules message

Question: I have a created a rule in drupal commerce.  I want to include a link to the users cart in that message, just like the link that appears when you add a product to the cart.  When I use the url token, the message displays like this: This item has been removed from http://dcomm/user/3/orders/6.
I want it to be --This item has been removed from your cart. and you click on the "your cart" and be taken to your cart view.
How do I do this?
Answer: Just add a link to
your cart

It will show the user's shopping cart.
Comment: Grief - talk about over thinking something.  Thank you!!!!


Include and then edit included android

Question: i need to include drawer toolbar, it includes whole layout with text. But i want to the same toolbar on all activites but with different text, how should i do it?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<include
    android:id="@+id/layout"
    layout="@layout/toolbar_final">
</include>

this is toolbar_final.xml
Main Layout is what i need to edit,
i need to include whole layout and get to the Linearlayout with MainLayout TextView and add my own things (buttons and stuff) into it, i hope u get what mean.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.Info">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/layout"
    android:orientation="vertical">

    <include
        layout="@layout/navigation_action"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="Main Layout"
        android:textAlignment="center"
        android:textSize="24dp" />

</LinearLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view_id"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/nav_header"
    app:menu="@menu/navigation_menu">

</android.support.design.widget.NavigationView>

navigation_action.xml
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/toolbarColor"
app:titleTextColor="@android:color/toolbarTextColor"
app:title="myApp">

and nav_header.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="300dp"
android:layout_height="140dp"
android:gravity="center"
android:background="@color/colorPrimaryDark"
>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:text="Header Text"
    android:textSize="20dp"/>

Comment: you mean you want to a use 1 actionbar for all activity but different title ??
Answer: You can do this easily by setting tittle on toolbar at runtime.
Use the same toolbar in every class and in which you want to change the text , use setTitle of toolbar and set the tittle according to that class.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // get the reference of Toolbar
setSupportActionBar(toolbar);
toolbar.setTittle("Class name")

Include and then edit included android


Entity select Dropdown

Question: I'm working on a Drupal 8 view that is going to be a page.
How can I make an exposed entity filter a dropdown? The entity is not a content type, but rather a custom entity with it's own module.
I can't seem to find any documentation about it.
Answer: Views on Drupal 8 are slightly different, but you might consider this answer (given for Exposed filters with dropdown selections), which gives you a quick module way of creating a custom node-based exposed filter drop down for a Drupal 7 view. This is essentially what I would suggest for your use case.

Entity select Dropdown


Normalizing Features for use with KNN

Question: Suppose that I have two features: age and income.
I'm told that I need to normalize features before modeling with KNN. What's the difference between scaling to 0 and 1, taking a unit norm, or z score? I've been taught all of these to "normalize" data, but don't know how or why each apply.
Comment: please check this http://stats.stackexchange.com/questions/71787/using-knn-for-prediction-how-should-i-normalize-my-data/234216#234216
Comment: and this http://stats.stackexchange.com/questions/223289/standardizing-some-features-in-k-means/223355#223355
Answer: RESCALING attribute data to values to scale the range in [0, 1] or [−1, 1] is useful for the optimization algorithms, such as gradient descent, that are used within machine learning algorithms that weight inputs (e.g. regression and neural networks). Rescaling is also used for algorithms that use distance measurements for example K-Nearest-Neighbors (KNN). Rescaling like this is sometimes called "normalization". MinMaxScaler class in python skikit-learn does this.
NORMALIZING attribute data is used to rescale components of a feature vector to have the complete vector length of 1. This is "scaling by unit length". This usually means dividing each component of the feature vector by the Euclidiean length of the vector but can also be Manhattan or other distance measurements. This pre-processing rescaling method is useful for sparse attribute features and algorithms using distance to learn such as KNN. Python scikit-learn Normalizer class can be used for this.
STANDARDIZING attribute data is also a preprocessing method but it assumes a Gaussian distribution of input features. It "standardizes" to a mean of 0 and a standard deviation of 1. This works better with linear regression, logistic regression and linear discriminate analysis. Python StandardScaler class in scikit-learn works for this.
Comment: "standardizing" is also called z-scaling sometimes, and is used for neural networks

Normalizing Features for use with KNN


Product of independent random variables property

Question: I need to prove that the joint distribution function of a vector random variable is equal to the product of distribution functions if and only if the random variables are independent
$$\xi_1, \xi_2  \text{- discrete random variables. } \vec{\xi} = (\xi_1, \xi_2). \text{ Prove that } F_\vec{\xi}(a_1,a_2) = F_{\xi_1}(a_1)F_{\xi_2}(a_2),\ a_1, a_2 \in \mathbb{R}\iff\ \xi_1, \xi_2 \text{ - independent.}$$
Answer: It follows immediately from the definition of independence.  $X_1$ and $X_2$ are independent if $P(X1\in S_1 \cap X_2\in S_2)=P(X1\in S_1)\times P( X_2\in S_2)$ where $S_1$ and $S_2$ are arbitrary.
For your case $F_{X_k}(a_k)=P(X_k\le a_k)$ is given where $S_k$ consists of all possibilities $\le a_k$.
For the other direction, use let $S_k$ be a particular vale of $X_k$ and $T_k$ the next lower value of $X_k$. Then $P(S_1\cap S_2)=F(S_1,S_2)-F(S_1,T_2)-F(T_1,S_2)+F(T_1,T_2)$
where $F$ is the joint distribution.  Using $F(a_1,a_2)=F_{X_1}(a_1)\times F_{X_2}(a_2)$, we get $P(S_1\cap S_2)=P(S_1)\times P(S_2)$.
Comment: Okay, one way proven. And how to prove the other way (from right to left)?
Comment: Answer supplement for your question.


How to mic an upright piano to record singing and playing?

Question: I have a pretty standard upright piano and I'd like to move some of my playing+singing from guitar to piano as a way to get more comfortable playing chords.
I like to record myself - just for fun or getting feedback, nothing more serious - and I wondered how to position microphone(s). Well - a vocal mic is simple enough but whereabouts would a mic go to record the piano? Just somewhere near the piano, inside it? I obviously wouldn't want to get too much vocal bleed into a piano mic which makes me think I need to somehow position it far away from my mouth but close to the piano sound?
Or, is a single vocal mic (or smart phone, etc) actually a decent approach since it will tend to get a good vocal/piano balance?
I'm probably after two levels of answer:

If I just use my phone to record a rough copy, where should I put it?
If I am trying to get a half-decent recording what should I do?
Comment: very quick answers 1. Experiment, you've only got about 3ft of movement to play with. 2. Record them separately - spill off a piano is serious.
Comment: Here's a link to an [article](http://www.soundonsound.com/sos/jan08/articles/pianorecording_0108.htm) I posted for a similar request.
Answer: "Just for fun or getting feedback" -- don't attempt to mic the vocal and the piano separately. Mic the room.
This is the only easy way to get a natural sounding recording. If you close-mic any instrument, you'll get a recording without any of the natural effects added by the room, and you'd have to compensate with artificial reverb, EQ and so forth.
Studio recording with multiple mics, and subsequently mixing, is a topic worthy of a whole book, because of all the complexities that arise.
Of course this means that you don't have separate piano and vocal tracks, so you can't play with levels afterwards. You'll probably find that for your "just for fun/feedback" purposes this isn't an issue.
It also means that you need a room that sounds nice -- but if it doesn't sound nice, why are you practising there? If you like how it sounds; good. If it's too lively, add some curtains/rugs/etc. If it's too dead, add some hard surfaces.
When you record you'll need to achieve something close enough to silence in the background -- so turn off or remove noisy radiators, fridges, computer fans, etc.
For a mono recording, you want an omnidirectional mic, positioned where a listener would be.
For a stereo recording "X-Y" placement is good, in which two mics imitate human ears. Use two cardioid mics, and place them as close together as possible, pointing 90 degrees apart.

There are lots of nice, reasonably cheap, stereo recorders on the market with built-in microphones in the X-Y arrangement.
How much of this matters for "fun/feedback" is up to you. Plenty of people record themselves using their smartphone's built-in mic, and put the result on YouTube.
Comment: My smartphone mic is pretty good. Would you suggest putting the phone on the piano - maybe on the music stand - or somewhere else? It can basically rest on the keyboard, on top of the piano, on the music stand - if it's behind me the vocals will suffer.
Comment: Put it where you would want an audience to be.
Comment: I agree with slim.  If you put a mic - even your smartphone too close to the source (ie the piano) you will get too much of the piano. Music stand might work if you can position it right.  Also the mic stand clips to hold i-phones have multiple adjustable parameters and with a boom mic stand and smart phone mount, you may be able to get the optimum position to get a good balance between voice and instrument.
Comment: Well yes, for an opera singer.  But most of us are 'microphone singers'.  I'd position the mic to favour the vocals.
Comment: @LaurencePayne I guess the question is, if you were performing on piano/voice to a guest in that room, would you mic and amplify your voice, or would you just sing and play acoustically? I'd guess the latter -- so record what they would hear by putting a mic where that guest would be.
Comment: @LaurencePayne ... and if you really would amplify your voice for that performance; I'd still say the easiest way to get a usable performance is to record the room, including the speaker your amplified voice is coming from.
Answer: A useful trick with upright pianos: take the bottom panel off!  Then you can put your "piano mic" underneath the piano stool (maybe on top of a box or something, not directly on the floor).  You'll get plenty of sound off the soundboard, well isolated from the vocals.
Answer: For this, and the other recording you asked about, and obviously any future recordings you will be doing, a better solution will be to arm yourself with an extra mic. This may well involve a small mixer as well, but lots of gear = lots of fun. One mic is really too much of a compromise, but with two, balancing signals is a doddle.Proper mics will always give far better quality sound anyway. You may well be put off the idea trying to use only one mic, because you want to play and sing rather than spend time trying to find the optimum position for that one mic, which is probably at the end of a rainbow...
Then, your other part of the question - open the lid, and try the mic centally placed pointing towards the gap. Or under the keyboard. Or behind the piano, where probably the best sound is found, usually masked by a wall.
Comment: @Mr.Boy On TV, it'll likely be a contact microphone, or a well hidden one, or an EP, or a playback, ...
Comment: @Mr.Boy  The problem with dangling a mic inside the piano is that most mics that can be dangled may tend to emphasize the sound coming from the part of the strings/soundboard closest to the mic.  Unlike a guitar which has 6 - 12 strings within a 2" span, a full sized piano has strings spread over more like four feet. Also, inside the piano you will pick too much of the mechanical noise of the hammers and other moving parts. Contact mics used inside pianos  react to vibration of the wood verses the actual sound wave pressure. So they don't "hear" the mechanical noises. They only feel vibration.
Comment: Got one (a mini-mixer) already... although it's not in the same room as the piano :) But yes - for q 2. a 2-mic solution is welcome, I just wasn't sure if it was common since on TV you can't see a piano mic.
Comment: @Mr.Boy - as indicated by yo', we wouldn't see the pno mic/s usually. Your SM58 will do a good job for pno or vox, even though it's essentially a live stage work mic.You can experiment, and decide which job it does better for you. Then splash out on another mic - stereo recordings now!!
Comment: So is just dangling a mic inside the piano (closing the lid to hold the cable so it's not too loud in the room) OK? Or would it be echo-y?
Comment: @Mr.Boy - that'd work. It's only going to be as echoey as if you put your head inside - don't! If the dampers work, it'll be fine, but bear in mind the top octave or so have no dampers.Mechanical noise may feature.
Comment: I think close micing/internally micing a piano is reasonable in a few circumstances (1) in live situations where feedback and sound leaks must be avoided (2) if you want to experiment with the effected sounds that come from close-micing (3) if you're recording the piano from loads of mics and intend to painstakingly mix the result to get the effect you want (and in this case you'd also mic the room). If you want a natural sounding piano, though, with the least hassle, just mic the room.
Answer: the phase cancellation / comb filtering from using multiple mics is not worth the effort or the cost or the time if you are doing this just for fun. Not getting into it here but in short the combination of complex waves from the same source at two different points in time (distance and time are related) (the speed of sound 1 foot = 1 millisecond) when the two sources combine it can have unpredictable effects by unevenly cancelling or strengthening the waves at different frequencies)
Use only one mic, and after each take do a listen test and alter the balance using placement.  This can be done using common sense here are some examples...

I don't hear enough piano!  - place the mic farther from your voice closer to the piano
I don't hear enough voice!  - place the mic closer to the mouth and further from the piano
Answer:
On top of the piano's (closed) lid, pointing at you.
Normal close vocal mic.  Second mic behind the piano, pointing at the soundboard probably about 2/3 towards the treble end. But experiment.  If the piano's against a wall, you might just have to drop a mic down behind it.  Probably won't sound as bad as it ought to.  You can try opening the lid and pointing a mic (or two) in, but action noise might be a problem.

The 'mic the room' technique can work for singers who would normally work without a mic.  Are you that sort of singer?  No, I thought not!   Keep your vocal mic close.  You won't keep all of the piano out of it, but there should be enough separation to let you add some reverb etc. without putting the piano underwater too.
Comment: I don't think I agree with the idea that most people are more used to singing with a mic than singing without. Using a close mic adds extra technique to singing, like modulating the distance, avoiding pop, moving away to breathe, that most people have no experience in.
Comment: Most people, in the popular music world at least,  when asked to sing, ask for the mic.  I agree, they don't all know what to do with it!
Comment: In "the popular music world", you're competing with a drum kit; and everything else amplified to match. Or you're gigging somewhere where you want to be heard over background chatter. But the question is about singing at a piano at home.
Comment: Yeah.  But singers like microphones.  They like that it does half the work for them.  Even the ones who DO 'sing out' like some reverb added, and that means close-micing.


Interpretação do Dive into Python sobre exceções

Question: Segue um trecho da página 47 do livro 'Dive Into Python' sobre exceptions:
"...You don't need to handle an exception in the function that raises it. If one function doesn't handle it, the exception is passed to the calling function, then that function's calling function, and so on "up the stack." If the exception is never handled, your program will crash, Python will print a "traceback" to standard error, and that's the end of that. Again, maybe that's what you want; it depends on what your program does."
Eu não entendi exatamente o que ele quer dizer com o So on, up the Stack e com o processo que antecede esta afirmação. Como assim a "Exceptions is passed to the called Function..."?
Outra coisa:
Na PEP 20 há a seguinte nota: "Explícito é melhor do implícito". Isto serve na hora de levantarmos as exceções de maneira específica? Usar apenas o except genérico não garante uma maior abrangência do problema? Então por que não usá-lo?
Answer: Você precisa ler: O que são e onde estão o "stack" e "heap"?. Portanto as funções vão sendo chamadas e organizadas como uma pilha, e quando uma exceção é lançada, até que ela seja capturada por alguma função, ela vai encerrando as funções que estão na pilha de chamadas, até que se nenhuma função faça nada com ela acaba quebrando a aplicação (o que é bom em muitos casos porque é erro de programação). O que vai acontecendo é o que chamamos de borbulhamento da exceção.
Chamada:

Se o tratamento só está na main():

E se é tratada logo na primeira função em cima da pilha:

A exceção é uma forma de controle de fluxo que manda buscar o primeiro except dentro do escopo dinâmico (diferente do escopo léxico que todo mundo conhece), ou seja, dentro do fluxo de execução que efetivamente ocorreu. Alguma função que está em execução deve ter esse comando que captura a exceção, pode ser até a própria.
O mais comum é que a função que chamou a outra que lançou a exceção é quem vai capturar, pelo menos quando a exceção é usada de forma correta. Em alguns casos acontece corretamente de passar para dois ou três níveis de chamada.
Exceção é um controle de fluxo que você não sabe onde vai parar só olhando o código, somente durante a execução é que acontece conforme ocorrem as chamadas de funções.
Ser explícito nada tem a ver com o assunto, ser explícito não é ser específico, são coisas muito diferentes.
Também é útil ver como lidar com exceções e porque deve tratar com exceções específicas. Portanto ser o mais específico quanto faça sentido em cada caso é o mais correto.
Answer: Respondendo a primeira pergunta, considere que você possui um programa em Python com N funções F1 até FN. Em que F1 lança um exceção. Suponha também que em seu programa, F1 é chamada dentro de F2, F2 dentro de F3 e assim por adiante... E que FN é chamada na thread principal. O que o autor está fazendo é referenciar-se a este conceito, explicando que todas essas chamadas formam uma pilha de execução em que a exceção lançada em uma dada função Fi e não tratada por ela é automaticamente passada para a função Fi+1 inserida anteriormente na pilha, até chegar em seu programa principal (up the stack), fazendo-o "crashar".
Em relação à segunda pergunta, acho que o Maniero já deu a melhor resposta.


Allowing anonymous users to contact node authors

Question: I want anonymous users to send messages to node authors. Also I want the sent messages to be visible to node authors in their user account. Here is what I have tried so far:

Private message - Solves what I am looking for but does not work for anonymous users
Webforms - New to it but I don't see a way for node authors to access the sent messages within their account
Answer: I'm pretty sure this can be done by combining the core Contact module with the Contact Storage module.
Steps to implement

Enable the Contact module and give anonymous the permission Use users' personal contact forms.
Enable the Contact Storage module and create a view showing Contact message. Configure a contextual filter with the user ID so that only messages to the logged-in user are displayed.


Image views in horizontal scrollview?

Question: I have a requirement wherein i need to have a horizontal scrollview with images loaded . There is no fixed number for images as i am getting content from server .
Gallery is deprecated and  ViewPager is supposed to be used ( As in android docs)
How do i use unlimited number of images in horizontal scrollview ?
Answer: Try out this project from Github. This should satisfy your need. Here is the link to pakerfeldt / android-viewflow
Comment: Thanks for your suggestion . It displays just one image right and you have to scroll to view the others . I want to display 3 - 4 images in the page and when the user scrolls i need to load the other images
Answer: <code> String RecentBooks="http://";

 ArrayList<List<String>> arrrecentbooks= new ArrayList<List<String>> ();
//HorizontalScrollview created programaticallly

HorizontalScrollView scollviewh = new HorizontalScrollView(this);

    View v1=null;

    LinearLayout linear_pmain = new LinearLayout(this);

        linear_pmain.setOrientation(LinearLayout.HORIZONTAL);
        //      linear_pmain.setBackgroundDrawable(getResources().getDrawable(R.drawable.topshelf));bottomthumbnail
</code>
//arrrecentbook contains images parsed fron uri
<code>    int length=arrrecentbooks.size();

 for(int j=0;j<length;j++)
    {
        LayoutInflater vii =     (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        v1=vii.inflate(R.layout.thumbnailrowlayout, null);

        List<String> listitem=arrrecentbooks.get(j);

        String  rimageurl=listitem.get(13);

        String  rbookprice=listitem.get(10);

  img=(ImageView) v1.findViewById(R.id.imgg);
        TextView txt=(TextView) v1.findViewById(R.id.txtg);
        txt.setText("Rs."+rbookprice+"/-");
        txt.setTypeface(tf,Typeface.NORMAL);

    img.setTag(new String[]{listitem.get(0),listitem.get(1),listitem.get(2),listitem.get(3),listitem.get(4),listitem.get(5),listitem.get(6),listitem.get(7),listitem.get(8),listitem.get(9),listitem.get(10),listitem.get(11),listitem.get(12),listitem.get(13),listitem.get(14),listitem.get(15),listitem.get(16),listitem.get(17),listitem.get(18),listitem.get(19),listitem.get(20),"recentbooks"});
//image loaded to image view

        {

            imageLoader=new ImageLoader(this);

            imageLoader.DisplayImage(rimageurl, this, img);
        }
        img.setOnClickListener(myIItemClickListener);

        linear_pmain.addView(v1);
    }

    scollviewh.addView(linear_pmain);

    lrecentbooks.addView(scollviewh);
//imgeview on itemclick listener
</code>
public OnClickListener myIItemClickListener = new OnClickListener() {
<code>@Override

public void onClick(View v) {

    try{

     RelativeLayout borderlyt=(RelativeLayout)findViewById(R.id.Booklyut);

        borderlyt.setBackgroundResource(R.drawable.bgorange);

        String[] Qtag = (String[]) v.getTag();

        Log.d("myItemClickListener", Qtag + "");

        //v.setBackgroundResource(R.drawable.bgorange);

        Intent itemintent = new   Intent(cxt,NoolDashboardDetailPage.class);

        Bundle b = new Bundle();

        b.putStringArray("iarray", Qtag);

        b.putInt("mflag", 0);

        itemintent.putExtra("android.intent.extra.INTENT", b);

        startActivityForResult(itemintent,2);

    }
    catch (Exception e) {

        // TODO: handle exception
    }
}
};
</code>

Image views in horizontal scrollview?


Automatically redirect user depending on its device screen size?

Question: In a custom module (amap), I have two forms with the same final purpose: handle (create, update, delete) a custom content entity (distribution_inscription).
The first one (DistributionInscriptionTableForm) is for "mass" update, designed as a table form and needs a "large" screen:

The second one (DistributionInscriptionForUserForm) is for "small" screen (smartphone):

With the same menu option, I'd like the user automatically redirected to the relevant form depending on the size of the device he currently uses.
How can I do that?
Answer: I can think of a couple of ways to do this:

Render the table version as a list of (list of) items (e.g. ul / li / ul... ), not an html table, and then use CSS media queries to adjust the display between the two formats. That is, traditional responsive design. Optionally, include some JS to "load more" items when there is space to fill.
Render the page furniture and some JS that will inspect the device dimensions and load the wide/narrow  element (as html) from the server in an AJAX callback. Once loaded, the page can be submitted as normal.

Of the two, the first would be my own preference. Be aware that there are a wide range of device sizes, including 5" phones with Full HD and wider screens, so don't rely on absolute pixel numbers - you need to account for dpi. On mobiles, I would definitely lose the sidebar, too.
I would not try to use page redirection - bad user experience - flickering screen, general horribleness :-)


Drupal Field API - Settings List

Question: I'm trying to create a 'link_field' in Drupal through a module, I've got the following code but I'd like to configure the field settings to do the following:

Not require title
Update the number of values to unlimited

I'm struggling to find any information around what setting key/pair values you can pass through for these, anyone able to offer some guidance on these?
<code>    <?php
/**
 * Implements hook_enable().
 *
 * Create a field. Fields can be created without any needs to attach them to
 * entities.
 */
function youtube_carousel_enable() {
  $field = array(
    'field_name' => 'ytcarousel_field',
    'type' => 'link_field',
  );
  field_create_field($field);

  /**
  * Bind field to a entity bundle.
  */
  $instance = array(
    'field_name' => $field['field_name'],
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video'
  );
  field_create_instance($instance);
}

/**
 * Implements hook_disable().
 *
 * Remove field from node bundle (content type) and then delete the field.
 */
function youtube_carousel_disable() {
  $instance = array(
    'field_name' => 'ytcarousel_field',
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video'
  );
  field_delete_instance($instance);
  field_delete_field($instance['field_name']);
  print 'Removed ' . $instance['field_name'] . "\n";
}
?>
</code>
Cheers
Answer: After viewing the HTML source to get key/value pairs I've managed to do something similar to the above with the following code:
<code><?php
/**
 * Implements hook_enable().
 *
 * Create a field. Fields can be created without any needs to attach them to
 * entities.
 */
function youtube_carousel_enable() {
  $field = array(
    'field_name' => 'ytcarousel_field',
    'type' => 'link_field',
    'cardinality' => -1
  );
  field_create_field($field);

  /**
  * Bind field to a entity bundle.
  */
  $instance = array(
    'field_name' => $field['field_name'],
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video',
    'settings' => array('title' => 'required')
  );
  field_create_instance($instance);
}

/**
 * Implements hook_disable().
 *
 * Remove field from node bundle (content type) and then delete the field.
 */
function youtube_carousel_disable() {
  $instance = array(
    'field_name' => 'ytcarousel_field',
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video',
    'settings' => array('title' => 'required')
  );
  field_delete_instance($instance);
  field_delete_field($instance['field_name']);
  print 'Removed ' . $instance['field_name'] . "\n";
}
?>
</code>
The cardinality controls have many instances the value can have, "-1" is unlimited.
<code>'cardinality' => -1
</code>
The title attribute is controlled via the instance not the field itself, I believe, and it uses text based values rather than numeric.
<code>'settings' => array('title' => 'required')
</code>

Drupal Field API - Settings List


How to achieve complete control of printing on print server

Question: windows 2008 r2 server is configured as a print server.around 150 ip printers have access to the server.
how can i restrict users from printing and only authorized users can print.
what approach should be used. can complete print control be achieved. .
Answer: Yes you can control access to the printers. I am going to assume that since you have 150 printers attached to your print server that you are using Windows Active Directory. When you go into the printer properties on your print server you should have a security tab that will allow you to assign either groups or individual users to use the printer.