How do I add a date picker that is rendered from most the browsers?

Question: I am migrating from Drupal 7 to Drupal 8. In forms I use '#type' => 'date_popup' for date fields, which Drupal 8 replaces by '#type' => 'date' and uses HTML 5.
I'm finding it most unsatisfactory because:

It has poor browser support; Internet Explorer 11 doesn't provide a popup.
I can't find anyway to change the input format from 'm/d/yyyy' to either 'd/m/yyyy' or 'yyyy-mm-dd'.

I have ensured that my browser language setting is English (Australian) which has a default date format of 'd/m/yyyy'.
Does anyone have a solution that provides a date picker for most the browsers and a text input format that can be controlled by the server, not the client?
Answer: I had a similar issue just recently within a client's intranet application, after Firefox added HTML5 date field support. (FF is their corporate browser of choice.)
You can still use any JavaScript based datepicker that suits your needs. (E.g. jQuery UI's datepicker.)
In your JavaScript bind this datepicker to all input fields of type date and then change the type of the input fields to text. This prevents the browsers from using their own datepickers.
PS.: It's not exactly a Drupal specific question, but tomorrow when back in my office I might add a code example that works for Drupal 8.
Comment: Thats the solution that I have decided to use and have it working with Drupal 8. I was hoping there might be a native Drupal solution, rather than having to reinvent the wheel.


How rails is handling the inheritance concept, parent accessing child

Question: This raises an error "undefined method hi":
class A
  def bla
    hi
  end
end

class B < A
  def hi
    puts "Hii"
  end
end

a = A.new
a.bla

I have a Rails application that does this:
class BlaParentController < ApplicationController
  before_filter :setting

  def create
    @random_obj = ParentRandom.create(permitted_params)
  end
end

class BlaController < BlaParentController
  private

  def setting
  end

  def permitted_params
  end
end

A method call BlaController#create goes to BlaParentController#create. But BlaParentController is accessing methods permitted_params and setting from its child BlaController. How this is possible?
Comment: Your second example makes no sense. What is `ParentRandom`? It would also be easier if you had classes that are intuitive as examples, e.g. `Animal`, `Dog`, `GermanShepherd`, where it is clear how inheritance works.
Comment: I am sorry it had to be this way .. but you can get the idea of parent class using the methods `permitted params and settings` of child class
Answer: For ordinary methods, what matters is whether it is defined for the receiver. Other kinds of contexts (such as, from which method it is called) does not matter. (The few exception to this are methods like Kernel#__dir__, Module#nesting, Exception#backtrace.)
In the first example, the receiver is an instance of A, but not B. Hence it can access methods in A, but not those in B.
In the second example, the receiver is an instance of BlaController, which is a subclass of BlaParentController. Hence it can access methods in BlaController  as well as those in BlaParentController.


Link não envia parâmetros e redireciona para Servlet

Question: Coloquei na minha pagina index em que tenho três links um com nome de Camisetas,Bermudas e Calças em que no href coloquei para que  quando clicasse no link fosse redirecionado para a servlet e enviasse os  parâmetros de acordo com o link, mas isso não acontece.
Pagina JSP

<%
  String camisetas="Camisetas";
  String bermudas="Bermudas";
  String calcas="Calças";
%>

Camisetas

 Bermudas

Calças

Answer: Suas urls estão incompletas. Teria que ser algo assim:

 Camisetas

No lugar de 'app' coloque o contexto que está usando na sua aplicação. Se não estiver usando um, deixe sem.
Comment: romarcio agora ele é redirecionado para servlet, mas ele não envia o parametro olha como fica o https quando eu clico no link http://localhost:8080/EccomerceJSP2/ListarProdutosPaginada?tipo=
Comment: Então o parâmetro `${camisetas}` deve estar vazio. Se você está recuperando esse valor daquelas variáveis que declarou na pagina como String, então deve usar ser assim: `?tipo=<%=  camisetas %>`
Comment: era isso mesmo vlw


What's the name of the "dual voice" effect in hip hop music?

Question: I would like to know the name of the effect that can be heard in pretty much every rap song on earth. It's an effect that sounds like a dual voice, like there's 2 people with the same voice rapping at once. You can hear it everywhere, especially when it's used to emphasize rhymes. What is this effect called (and maybe how can it be done in programs like Pro Tools and Audacity unless it's done using some kind of hardware)? I've searched everywhere but I can't find anything.
Any help will be greatly appreciated.
Comment: I think it's usually achieved by actually overdubbing the part. I.e. performing it several times, often with different people doing the part. Doubling the exact same sound clip will give a different effect.
Comment: Can you provide an example?
Comment: The process is called overdubbing or double-tracking. It has nothing to do with hip-hop. It has been used in all forms of music recording going back to the 1920s, so it is almost 100 years old.
Comment: I should have said "it has nothing to do with hip-hop *per se*" or perhaps "it is not exclusive to hip-hop". My point is that as it has existed for about 90 years, it predates hip-hop by many decades.
Comment: An example would be great here. Even if it's an effect used on "every rap song on earth" a specific song with a specific time/passage listed would help a lot.
Comment: @WheatWilliams: It has something to do with hip hop, since the technique is used there. The asker did not know what it was, and the context is quite important for the question, don't you think?
Comment: One example from the top of my head would be Fight the power with Public Enemy. The first verse starts with a doubling of "1989".
Answer: Not just in hip hop, this is called a double-tracked vocal. It is simply two vocal takes, recorded onto two tracks. Alternatively it could be two people performing in unison. On sung vocals, double-tracking thickens the sound, and hides a certain amount of pitch imperfection. In rapping, the thickening is still there.
You could try to approximate it using a short delay - known as a slapback echo (you can hear it on early Elvis rock'n'roll songs) or with chorus. But if you're recording, getting two vocal takes is easy and conventional.
Comment: It's just not very easy with two vocal takes, it's also very hard to achieve the effect of an overdub with anything else than an overdub.
Answer: The most common way this is done is by having members of the crew join the lead in rapping certain words. Sometimes the entire crew.
In the studio it may be just the rapper over dubbing his own vocals, as per Meaningful's comment.
You could try using a chorus effect on the vocals, and pan the wet and dry mixes - this will expand the sound stage a bit, but it won't sound like the real thing.
Comment: It could also be [ADT](https://en.wikipedia.org/wiki/Automatic_double_tracking) or a very short delay, or simply duplicating and offsetting the track.
Answer: Dont know if this is what you are referring to, but a sample delay helps spread the vocals out and make the sound more present in your mix. Its called sample delay in logic, in PT i think you can use a slap or short delay. Use the stereo version even if you are in a mono track...25-30 ms is all you should need.if you want more separation between the main vocal and the delay try 150ms and dial it in from there.


Want to append colored images to a list and convert that list to grayscale using OpenCV

Question: So basically I'm trying to convert a set of RGB images to grayscale using cv2.cvtColor and python is throwing the following error:
Traceback (most recent call last):
  File "MCG.py", line 53, in
    gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
TypeError: src is not a numpy array, neither a scalar.
This here is the code:
import numpy as np
import cv2
import dlib
import sys
import skimage
from PIL import Image
import os
import glob

folderpath = sys.argv[1]
cascPath = sys.argv[2]

imageformat = ".tif"
path = folderpath
imfilelist = [os.path.join(path,f) for f in os.listdir(path) if f.endswith(imageformat)]
data = []
for IMG in imfilelist:
   print IMG
   image = cv2.imread(IMG)
   data.append(image)
   cv2.imshow('Image', image)
   cv2.waitKey(0)

faceCascade = cv2.CascadeClassifier(cascPath)

predictor = dlib.shape_predictor(PREDICTOR_PATH)

gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.05,
    minNeighbors=5,
    minSize=(100,100)
)

As you can see, I'm trying to append all these images to a list, which will then be converted using the cv2.cvtColor function. However, that error is thrown. What am I doing wrong? Thank you.
P.S if anyone is wondering why I imported modules that don't seem to be used in this code, this code is just a segment of the whole thing and all of those modules have are being utilized in one way or the other.
Answer: You are collecting the images into a list with
data = []
for IMG in imfilelist:
    ...
    data.append(image)
    ....

and then trying to convert the list with
gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)

This is why you are getting the error - the error is telling you that data is not an image (numpy array) but is a list. You need to convert one image at a time with cv2.cvtColor().
You could try
gray = []
for img in data:
    gray.append(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))

This would give you a list of greyscaled images, which is what I think you want to do.
Comment: Hello, thank you for the response! It didn't work I'm afraid. The outcome is the same. The images that have been "converted" are still colored. I used cv2.imshow('Grayed Image', img to check.. Oh and the exact same error persists.
Comment: If you have used `cv2.imshow('..', img)` following the `gray.append...` line, then yes the image will be coloured because you are displaying the colour image.
Comment: By "the exact same error", do you mean the error referenced to the line `gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)`?
Comment: Yes, that's the one
Comment: The code segment `gray = [], for img in data: ...` should replace the `gray = cv2.cvtColor(...)` line
Comment: It worked, but only partially. It now throws the same error (src is not a numpy array, neither a scalar), but for the detectMultiScale function for the line that says minSize = (100,100). So it advanced further down the code, but threw the same error for a different line of code (mentioned above in this comment).
Comment: Same as earlier, the error is telling you that `gray` is not an image. This is because it is a __list__. _You still need to process one image at a time, you __cannot__ throw a list at it and hope for it to work._ You still need to iterate over the list.
Comment: Yeah, did that alongside the thing that the guy below recommended. It no longer throws that error and everything moved ahead. Appreciate the help
Answer: If you read the cv2.cvtColor documentation, you can see that the first parameter is the Src 8-bit single channel image. However, in your case you are giving an entire list of images.
So change the code as
gray = []
for j in range(0,len(data)):
    gray.append(cv2.cvtColor(np.array(data[j]), cv2.COLOR_BGR2GRAY))

I guess this should work.
Comment: I've tried your method and it didn't work I'm afraid. Thank you though. It still throws the same error. I decided to display the gray images by using cv2.imshow('Grayed Image', data[j]),  but they remained colored. And as I said, the exact same error persists.
Comment: Another thing you can try is cast it to a numpy array. So change the code line I have posted above to `gray.append(cv2.cvtColor(np.array(data[j]), cv2.COLOR_BGR2GRAY))` . Mayb its not in the array format
Comment: It worked. Appreciate the help. casting all the arrays to numpy arrays in the above code (meaning mine) worked.
Comment: Great to hear. Since I am still new to answering questions.. sorry If my suggestion was wrong. Please do vote if you feel my answer is correct now. Happy coding.


Access to Distribution groups

Question: Is it possible to block access to an AD Distribution group for a user?
Such that he does not see the group, even if he is a member of that group.
Answer: You can hide a DL from the Global Address list.  This would prevent any user from seeing it.
Edit the DL, and on the Exchange Advanced tab select the "Hide group from Exchange Address lists" check box.

Access to Distribution groups


How to create an enum with map as a field in Java?

Question: I need to create an enum in Java having a field of the type Map. How do I initialize the map field? Is there a way without creating an anonymous object or using Guava (or similar) library?
public enum Day {
  Sunday(new HashMap<>()); // TODO initialize the map

  private Map<String, String> map;

  Day(Map<String, String> paramMap) {
    this.map.putAll(paramMap);
  }

  public getMap() {return map;}
}

Comment: suppose you refer this [example](https://codereview.stackexchange.com/questions/46175/java-enum-containing-a-hash-map-for-look-up)
Comment: @RajithPemabandu That example is a bit different. I don't need a commong map, but a different map for each of the enum values.
Answer: Since the key and value of the map are both String, you can make the constructor take a varargs and let it build the map for you:
public enum Day {
    SUNDAY("Foo", "Fooz",
           "Bar", "Barz",
           "Hello", "Hi");

    private final Map<String, String> map;

    Day(String... keysAndValues) {
        if ((keysAndValues.length & 1) != 0)
            throw new IllegalArgumentException("keysAndValues has odd size: " + Arrays.toString(keysAndValues));
        this.map = new HashMap<>();
        for (int i = 0; i < keysAndValues.length; i += 2) {
            if (keysAndValues[i] == null || keysAndValues[i + 1] == null)
                throw new NullPointerException();
            if (this.map.put(keysAndValues[i], keysAndValues[i + 1]) != null)
                throw new IllegalArgumentException("keysAndValues has duplicate key named '" + keysAndValues[i] + "': " + Arrays.toString(keysAndValues));
        }
    }

    public Map<String, String> getMap() {
        return this.map;
    }

}

If you print the map for SUNDAY, e.g. System.out.println(Day.SUNDAY.getMap()), you get:
{Bar=Barz, Hello=Hi, Foo=Fooz}

Answer: This is how it could be done with jdk8 and using functional interface
import java.util.Map;

public interface MapProducer<K,V> {

  Map<K,V> getMap();

}
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public enum EnumWithMap {
    //empty map
    TEST1(HashMap::new),
    //default map
    TEST2(EnumWithMap::getDefMap),
    //enum instance map
    TEST3(()->{
        Map<String,String> map = new HashMap<>();
        map.put("key1","val1");
        return map;
    })
    ;

    private final Map<String,String> map;

    EnumWithMap(MapProducer<String,String> mapProducer) {
        this.map = Collections.unmodifiableMap(mapProducer.getMap());
    }

    private static Map<String,String> getDefMap(){
        Map<String,String> map = new HashMap<>();
        map.put("keyDef","valDef");
        return Collections.unmodifiableMap(map);
    }

    public Map<String, String> getMap() {
        return map;
    }
}

$Result of foreach Loop:
for(EnumWithMap en:EnumWithMap.values())System.out.println(en.getMap());

will be:
{}
{keyDef=valDef}
{key1=val1}


Relationship between cdfs

Question: Suppose we have random variable $X$ and two observers. For observer one cdf of $X$ is $F(.)$ and for observer two, it is $G(.)$. For some particular value of $x$ I am looking conditions/relations for $F$ and $G$ that guarantee $F(G^{-1}(x))\neq x$. Equivalently, $F(G^{-1}(x))<x$ or $F(G^{-1}(x))>x$. If, for instance, there is a first order stochastic dominance between $F$ and $G$, one of the inequalities are satisfied. I am looking other relevant relations. Thanks for any help.
Comment: Assuming both CDFs are continuous and strictly increasing, don't you need $F(x) \gt G(x)$ or $F(x) \lt G(x)$ for all $x$ ?  Wouldn't that be a stronger condition than first order stochastic dominance?
Comment: Yes, but what I am looking a weaker one, if there is. Your suggestion is stronger, but it is hard to claim that this relationship is valid for a large class of distributions.
Comment: Essentially you are asking that $F^{-1}(x) \not = G^{-1}(x)$. Here $x$ is not a possible value of $X$ but something from $0$ to $1$.
Comment: That's true. That is, $x\in[0,1]$ and I am looking whether there is any way of obtaining those inequalities.
Comment: Monotone likelihood ratio property. But it's stronger than first order stochastic dominance (in fact implies it).
Answer: It is impossible to get some condition weaker than first-order stochastic dominance if $F$ and $G$ are continuous. The condition $F^{-1}(x)\neq G^{-1}(x)$ for all $x\in[0,1]$ imply that $F^{-1}$ and $G^{-1}$ never cross so $F$ and $G$ also never cross so you have FOSD.
If we allow some finite number of points with mass so $F$ and $G$ are have a finite number of discontinuous points (not necessarily the same) than the condition you want is that in each region of continuity either $F$ is above or below $G$ but I'm not aware that this condition has a name. Does anyone else wants to chip in?
Comment: Well actually. I am not saying the condition holds for all $x\in[0,1]$. In different context the value of $x$ changes. I thought the set of intersection points of $F$ and $G$ would be measure zero. Than, as you suggested either $F$ and $G$ would be above between two consecutive intersection point. The thing is whether there is a name for this condition or a concept related with this property.
Comment: @user64066: Why don't you clarify **in the question** what is being assumed about x? If $x$ is only one point then the question may have some reasonable answer. If the only requirement you have is that $\left\{x:F(x)=G(x)\right\}$ is a set of measure then any two "generic" CDFs will satisfy this property.
Comment: Given your interest thinking $x$ as mixed strategy NE probability for a particular strategy,say strategy $2$ might shed light on the meaning of $x$. As the game changes, clearly $x$ will change. Hope this makes sense, since my game theory knowledge is really limited.

Relationship between cdfs


Comparison of logit and probit estimations

Question: There are a lot of questions concerning logit and probit relations (led by 20523), but I'm still confused with a seemingly simple issue.
On the one hand, often we see that for 'rule-of-thumb' correction of $\beta$ in logit and probit people use $1.6$ scalar (in example, Wooldridge, 5ed., ch. 17, p. 586).

In the typical case that $g$ is a symmetric density about zero...
For example, in the probit case with $g(z) = \phi(z)$, $g(0) = \phi(0) = 1/\sqrt{2\pi} \approx .40$.
In the logit case, $g(z) = exp(z)/[1 - exp(z)]^2$, and so $g(0) = .25$.

And a bit later (Wooldridge, p. 593):

Still, sometimes one wants a quicker way to compare magnitudes of the
different estimates. As mentioned earlier, for probit $g(0) \approx .4$ and
for logit, $g(0)\approx .25$. Thus, to make the magnitudes of probit and logit
roughly comparable, we can multiply the probit coefficients by $.4/.25
> = 1.6$, or we can multiply the logit estimates by $.625$.

On the other hand, I read in (Train, 2009, p. 24):

... the error variances in a standard logit model are traditionally
normalized to $π^2 /6$, which is about $1.6$. In this case, the
preceding model becomes $U_{nj} = x'_{nj} (β/σ) \sqrt {1.6} + ε_{nj}$
with $Var(ε_{nj} ) = 1.6$. The coefficients still reflect the variance
of the unobserved portion of utility. The only difference is that the
coefficients are larger by a factor of $\sqrt{1.6}$ - standard deviation of extreme values distribution of errors.
...
As stated earlier, the error variance is normalized to $1.6$ for logit.
Suppose the researcher normalized the probit to have error variances
of 1, which is traditional with independent probits. This difference
in normalization must be kept in mind when comparing estimates from
the two models. In particular, the coefficients in the logit model
will be $\sqrt{1.6}$ times larger than those for the probit model, simply due
to the difference in normalization.

The question. So we see that usually logit estimate should be divided by approx $1.6$ to match probit estimate of the same data (and this value is approxiation of $1 / \sqrt{\pi /8}$), but Train suggests to correct by approx $\sqrt{1.6}$, which is derived from $\sqrt{\pi^2 /6}$.
What is the difference come from? How do those approaches relate to each other? Is it the same correction after all?
Comment: I think the key is the $\pi^2 / 6$ variance assumed by Train. It implies a scale parameter $s=\sqrt{1/2}$ for the logistic distribution, instead of the (more common, I think) $s=1$ assumed by Wooldridge.
Comment: @suckrates , I think you are right, but the difference is relatively big, so it would be nice to understand the comparative reasoning.
Comment: Does this answer your question? [Difference between logit and probit models](https://stats.stackexchange.com/questions/20523/difference-between-logit-and-probit-models)
Comment: @kjetilbhalvorsen, thank you by pointing to the thread, but it doen't answer the question. One of answers mentions 1.7 to be right correction.
Answer: Just some background first:
For the probit model the estimated parameter $\beta$ and the error term $\epsilon$ within the context of $Pr(\frac{\epsilon_i}{\sigma} < x_i \frac{\beta}{\sigma})$ is assumed to have a standard deviation $\frac{\epsilon}{\sigma} = 1$, on the other hand for the logit model the same standard deviation  $\frac{\epsilon}{\sigma} = \frac{\pi}{\sqrt{3}}$; this $\frac{\pi}{\sqrt{3}} \approx 1.8$ is indeed the standard deviation of the unit logistic distribution.
That being said, pretty much empirically, the logit will fit better on the normal if we scale it by 1.6 instead of 1.8 across pretty much the whole of the curve. (Personally I think the approximation is underwhelming but potato potahto...)

Now coming back to why $\sqrt{1.6}$ instead of $1.6$. Andrew Gelman had exactly the same question with you, talked with Dr. Train and got the following answer: "These are not two different parameterizations of the same model, with one parameterization being more common than the other. They are two different models, each with its own parameterization that is common for that model." His whole process is outlined in his 2006 blog-post on "Take logit coefficients and divide by approximately 1.6 to get probit coefficients". In short, Train referred to a model with error term $N(0,2)$. Therefore there was an approximate difference of $\sqrt{2}$ in the standard deviations;  $\frac{ \frac{\pi}{\sqrt{3}}}{\sqrt{1.6}} \approx \sqrt{2}$. This is the root of the difference. The correction is essentially the same just the model utilities functions are different.
Comment: In the case of Gelman, I agree about the use of *mlogit*. In the case of Train, I suspect that you are also correct, i.e. it refers to *clogit*, but that is never explicitly mentioned in the text; that said, Ch. 3 does make the case of estimating a probability "*conditional on the subset of alternatives selected by the researcher*" which fits *clogit*.
Comment: thank you! Do you have an understanding of what two types of models they have in mind? Am I right to think that Train is about *clogit* and the like models (different $X_j$) while Gelman deals mostly with *mlogit* (same $X_j$ for all alternatives)?


ssl certificate clash with other ssl certificates

Question: I have windows 2008 vps used for webhosting. The main compnay website sits at https://www.fakehostingcompany.com and uses a ssl certificate from rapidSSl. All has been working fine so far.
A few clients have bought ssl certificates for there domains, lets say, sitea.com and siteb.com using the normal csr route to obtain a certificate.
When adding the new certificates to the sites and adding the https bindings, all other ssl are invalid.
if i view the certificate information in the browser it will show fakehostingcompany.com and sitea.com's certificate name points to siteb.com's ssl certificate and is invalid.
Basically the last certificate I bind into iis overwrites the other certificate information.
So if i had to add sitea.com's certificate last, fakehostingcompany.com and siteb.com would be invalid.
I've been struggling for the past few days now trying to get this right, and i hope someone can help me on this or point me in the right direction.
Comment: Can you upgrade to IIS8? You could use SNI then. Else you will need to assign a separate IP for each site/cert binding.
Comment: You have a couple of options, you will need to use a combination of internal and external IPs (messy) or setup something like https://www.nginx.com/ to act as a proxy for the other server
Answer: Historically a given IP address could support exactly one SSL certificate.  This is because the point in the communication where the HTTP 'Host' header is provided is after the entire SSL handshake has occurred.
A SSL/TLS extension called 'SNI' allows a server to select which SSL certificate to present based on the client request, however this was introduced into IIS in 8: https://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-server-name-indication-sni-ssl-scalability
For IIS7 you'll need to get a single certificate that has Subject Alternative Names for all the clients you support, and update this certificate as new clients come on:  https://en.wikipedia.org/wiki/Subject_Alternative_Name
Comment: so each site on the server cannot have there own ssl certificate ?
Comment: @Bradley With a single IP and lacking SNI, yes -- one cert only. You can have one 'cert' that is valid for all of the different domain names, but as a provider you'll have to procure that cert as your clients won't be allowed to create certs for other clients.
Comment: `Historically a given IP address could support exactly one SSL certificate` -- it is incorrect. Single IP always supported multiple SSL certificates. IP/Port combination is where only single SSL cert binding was allowed.


6 finger Flute hole placement formula

Question: I like to experiment on plastic flutes.
Is there a mathematical formula for placing holes in a flute?
Is it same for all kinds of flutes for example western flute,6 hole flute or 8 hole flute?
Comment: Yes there is - what scale, or intervals, do you want to be able to generate?   Do you want to be able to generate pitches in the overtone series?
Comment: Let's say I want to make an E scale 6 hole or eight hole flute. I know for present that an eight hole Indian flute can generate about 2 and a half octaves.
Comment: Two and a half octaves is a lot and requires overblowing. I'm somewhat sceptical, whether a non-expert player on a home-made instrument can achieve that.
Comment: I'm sorry I meant 1 and a half octave.
Answer: There are mathematical formulas for placing flute holes. You will need different ones for each different style of flute. A Google search for "flute hole calculator" turns up about ten sites that provide the calculations. Several good ones:

flutomat
Bracker Whistles
a description of the calculations

6 finger Flute hole placement formula


How to calculate average time in service

Question: We want to work out a value for "Average time in service" for our users.
However, as we have many subscribers still active, how can we do that? If we just look at average time of deactivated subscribers, that won't show the picture.
Is there some "correct" way to do this?  We know our churn rate by month, so maybe we need to work out from those still on the service, when they're likely to leave? and use that?
Comment: A little bit more detail would be ideal to get the question. At least, how does your data look like, who are the subscribers, what do they have to do with average time, and how is 'average time in service' defined?
Comment: I agree with Henrik. The more precise your question is, the better the answer will be.
Comment: Average time in service is simply the number of days from when they first appear in our system, to when they choose to leave.  The data available is the subscriber identifier, the current state (i.e. whether or not they've left yet) and the date they joined (and also the date they left if applicable)
Answer: Sounds like Survival analysis to me. The still active subscribers have censored times.
Comment: Is there any software around to assist in the analysis?
Answer: onestop is right, you're looking to do survival analysis. In general, you can use a nonparametric Kaplan-Meier estimator to plot the survival curve and then derive the "average time in service".  The area underneath the survival curve works if you don't have any censored data (i.e. subscribers who are still active).  Michael Berry had a nice and clear explanation of this in a blog post for a business scenario similar to yours:

Why is the area under the survival curve equal to the average tenure?

In your case, where you have censored data, the median time (0.5 quantile) is available as the "average time in service" -- as noted by @onestop.
Harvey Motulsky's book has a nice discussion of this:

Survival Curves
Comment: That is great thanks, the graphpad page was perfect - Fig 6.4 gave me what I needed to know.  We havent yet got 50% dead, so technically it's not possible to work out, but i did some forecasting to get to that point.
Comment: Note that it's often not possible to calculate the mean (without making parametric assumptions about the distribution) as the longest observed time is usually too short for the survival curve to reach zero, often it's not even close. You can estimate some of the quantiles, such as the median time, however, though which ones depends on the proportion who experience the event.
Comment: @onestop: thanks, I fixed my answer to note the mean/censored issue.
Comment: As @ars points out there is the notion of the "truncated mean" which is the area under the survival curve. Michael Berry discusses it and also mentioned as "Mean survival restricted to time L" at the following: http://support.sas.com/resources/papers/proceedings10/252-2010.pdf


How can I resize on time-series data on python

Question: I'm trying to do deep-learning on time-series data.
There are 12 features for each data, but every series data don't have the same amount of data.
Some shape is [48,12], and some is [54,12], I'm trying to resize them into [50,12].
All I know until now is using resize in skimage.transform, but I don't know if it works well or not.
Is there any other solution for doing this?
For example, one of the features in the data looks like below.
The shape is [55, 1] I would like to reshape it to [50, 1].
a = np.array[-5.529309, -4.6293,   -3.068647, -4.897388, -4.39951,  -4.753769, -3.729291,
 -4.973984, -5.060155, -4.686748, -4.696322, -3.939932, -3.470778, -6.209103,
 -5.586756, -4.466532, -3.193116, -5.337818, -5.596331, -4.006954, -3.499502,
 -3.413331, -6.304848, -4.322914, -4.246317, -5.759098, -5.893142, -6.381444,
 -4.52398,  -4.198445, -5.634629, -6.276124, -5.17505,  -4.322914, -4.198445,
 -4.600576, -4.39951,  -4.945261, -5.759098, -4.677173, -3.623971, -5.692076,
 -6.563361, -5.462287, -4.868664, -5.941015, -6.400594, -5.692076, -4.591002,
 -6.027186, -5.960164, -6.256975, -5.414414, -5.730374, -6.726129]

If I using resize, the data will look like below.
Before resize and after resize:
Comment: You need to know what the time axis on your data is. If every series is 12h long but you have different number of timepoints, then skimage.transform.resize will work fine. But if every time series is data sampled every hour for some different number of hours, then you need to truncate to the shortest series, or extrapolate the shorter series.
Answer: One choice will be using TimeSeriesResampler in tslearn.  This resizes a given time series to a fixed size you specified, by resampling data by (linear) interpolation.
https://tslearn.readthedocs.io/en/stable/gen_modules/preprocessing/tslearn.preprocessing.TimeSeriesResampler.html
Example:
from tslearn.preprocessing import TimeSeriesResampler
ts = np.arange(5)
new_ts = TimeSeriesResampler(sz=9).fit_transform(ts)
final_ts = np.squeeze(new_ts)
print(ts)   # [0 1 2 3 4]
print(new_ts)  # [[[0. ] [0.5] [1. ] [1.5] [2. ] [2.5] [3. ] [3.5] [4. ]]]
print(final_ts)  # [0. 0.5 1. 1.5 2. 2.5 3. 3.5 4.]


Selenium Java POM

Question: I've created a framework in selenium with design pattern "page object model"
But I want all classes to be executed in the same web browser and what is happening is each class is run and the browser window closed then another one is opened for the next class
I need all classes to be run in the same browser.
Comment: If you are using TestNG, check the methods with the annotations - '@BeforeClass' and '@AfterClass' or '@BeforeMethod' and '@AfterMethod'. Those methods contain the code to launch the browser before each test case and quit the browser after that test case. Modify that according to your requirement.
Answer: You need to implement before and after test method which launch the browser before every test and kill it afterwards.
Something like this:
<code>    @BeforeAll
    static void beforeAll() {
        WebDriverManager.chromedriver().setup();
    }

    @BeforeEach
    void beforeEachTest(TestInfo testInfo) {
        driver = new ChromeDriver();

    }

  @Test
 void yourTestLogic(){
Actual test here
}

    @AfterEach
    void afterEachTest() {
        driver.quit();
    }
</code>
This is JUnit 5 example. The same is possible with TestNG with very small differences.

Selenium Java POM


What are the Reggae Chords

Question: I' am a DJ, I want to make Reggae Remixes but what is actually Reggae Chords. I really don't understand. How can bands like UB40 make such a awesome reggae tracks. I asked few of my friends and they said its Piano Reggae Chords needs to match with the song.
But what is actually Reggae Chords? Are Chords and Notes same thing?
Comment: Reggae is more about rhythm than it is about harmony.
Answer: The best way to understand how bands make reggae tracks is to listen to lots of reggae, paying attention to what each instrument is doing.
The most basic analysis of reggae is this:

the bassline is prominent, slightly weighted towards the third beat of each bar.
some other mid-to-high range instrument plays staccato chords on the second and fourth beat of each bar. Sometimes it's guitar, sometimes organ, sometimes piano, sometimes something else. This is sometimes called the "skank", because it sounds  like that.

If you play a song like "Twist and Shout" emphasising the first and third beats, it will sound like rock. Emphasise the second and fourth, with a skank as above, and it will sound like reggae. There are lots of reggae versions of "Twist and Shout" you could check out to demonstrate this.
Follow this format exactly and you'll end up with a disappointing, lumpen version of reggae. Listen to good reggae and you'll notice how other touches, and simply the swing of it, lift it and improve it.
I suspect when your friends say "reggae chords" they are referring to the skank. Since you mention DJing, I wonder whether you are trying to make reggae by putting skank from one record on the singing from another. This can only work if the two songs have the same chord progression. It's no use having a bass playing E, a piano playing an F chord and a singer singing F sharp; pitches need to sound nice together.
Comment: That should work, considering how the local music business uses "dub plates" where one musical groove serves as backing of several songs.
Answer: I'll start with explaining the basics:
A note is the name of a pitch. (i.e. A, B, C, D, E, F and G)
A chord is a group of 3 or more notes.
There are no actual reggae chords, but any chord can be played with a reggae feel. In fact, most reggae songs only use a few basic chords. The best example of this is Three Little Birds only has three basic chords in A major, D major and E major. These three chords make up countless songs including Here Comes the Sun and Rock and Roll All Night. The difference is the laid back feel of Three Little Birds makes it reggae.
What your friends meant was either the piano was playing the wrong chords for the song or the feel did not go with the song.
Here is a good chord primer if you want to learn more about chords.
Comment: @ Dom -George will be turning in his grave - Here Comes the Sun - 3 chords ??
Comment: @Tim I meant that A major, D major and E major were all in Here Comes the Sun. I know there are more chords I just wanted two contrasting examples to show how different those three chords sound.

What are the Reggae Chords


Convert a list of list to list of Maps with a value

Question: I am trying to convert the folowing input to the desired output using Jolt
[
  {
    "scores": [
      [
        4,
        1
      ],
      [
        2,
        1
      ],
      [
        8,
        5
      ],
      [
        7,
        3
      ],
      [
        5,
        10
      ]
    ]
  }
]

Desired Output
[
  {
    "value1": 4,
    "value2": 1
  },
  {
    "value1": 2,
    "value2": 1
  },
  {
    "value1": 8,
    "value2": 5
  },
  {
    "value1": 7,
    "value2": 3
  },
  {
    "value1": 5,
    "value2": 10
  }
]

I want to convert the list of list to the map. The elements in the input list should be the values of the keys.
Can anyone help with the Jolt Spec.
Thanks in advance.
Answer: You can use the following shift transformation spec which incurs  indexes 0 and 1 respectively as looping through in the scores array it such as
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "scores": {
          "*": {
            "0": "[&1].value1", // the first component of the subarray
            "1": "[&1].value2"  // the second component of the subarray
          }
        }
      }
    }
  }
]

the demo on the site http://jolt-demo.appspot.com/ is :
Comment: Yes, I asked a new question https://stackoverflow.com/questions/75965881/convert-a-list-of-list-to-a-list-of-maps
Comment: Yes, It works and gives the desired output.
Thank you so much.
Comment: I have a follow-up question on this.
What if we have two maps in the first list?
Comment: Would really like to know your thoughts on the question :)


Recoding insignificant factor levels in linear regression model

Question: Suppose I have a linear model:
model.lm2 <- lm(df$SalesPrice ~ df$SqFeet + df$Garage + df$Year + df$Quality + df$Style + df$Lot)
summary(model.lm2)

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -2680.9219   397.1155  -6.751 4.04e-11 ***
df$SqFeet     105.8539     6.8433  15.468  < 2e-16 ***
df$Garage       9.6069     4.9504   1.941  0.05286 .
df$Year         1.4262     0.2011   7.092 4.50e-12 ***
df$Quality2  -133.4846    10.4911 -12.724  < 2e-16 ***
df$Quality3  -149.4913    13.9734 -10.698  < 2e-16 ***
df$Style2     -25.2898     9.0856  -2.784  0.00558 **
df$Style3     -13.4706     8.7225  -1.544  0.12313
df$Style4      11.6082    18.0938   0.642  0.52145
df$Style5     -26.8263    14.8151  -1.811  0.07077 .
df$Style6      -4.6575    14.9504  -0.312  0.75553
df$Style7     -40.5276     8.5626  -4.733 2.88e-06 ***
df$Lot          1.2919     0.2312   5.589 3.75e-08 ***

As you can see the factor variable Style has four insignificant levels(3,4,5,6).
The question is: Does in make sense to recode insignificant levels of factor variable(3,4,5,6 into the level 1)? Would this transformation make predictions of this model better? if yes why/is no why?
Answer: No, I do not think it makes sense to recode insignificant levels into the same category.
First, is the omnibus test for Style significant? A comparison of nested models will tell you this:
mod0 <- lm(SalesPrice ~ SqFeet + Garage + Year + Quality + Lot, df)
mod1 <- lm(SalesPrice ~ SqFeet + Garage + Year + Quality + Style + Lot, df)
anova(mod0,mod1)

It looks like from your output that the omnibus test for Style would be significant. What your output is telling us is that Syle2 is different from Style1, and Style7 is different from Style1.
That means that levels 3, 4, 5, and 6 of Style are not different from 1. However, I would still not collapse these into one.
One reason is theoretical: Are the different levels really qualitatively different forms of Style? If so, it does not make sense to recode them as the same and consider them as the same construct.
Another reason is statistical: You are not looking at all the possible pairwise comparisons. Looking at the output, it is likely that—while the levels 4 and 5 are not different from 1—they are significantly different from one another.
You can test this by using the glht() function from the multcomp package. All possible pairwise comparisons can be formulated as linear combinations of the coefficients from the output you have. For instance, to test the difference between Style4 and Style5, you could run the following code:
summary(glht(model.lm2, c(0,0,0,0,0,0,0,0,1,-1,0,0,0)))

What this will do is see if the 9th coefficient in the summary (11.61) minus the 10th coefficient (-26.83) is different from zero:
$H_0$: $b_9$ - $b_{10}$ = 0
Which can be re-written as:
$H_0$: $b_9$ = $b_{10}$
This tests if there is a difference between levels 4 and 5 of Style. How? Think of what the beta weights represent:
$b_9$ = Style4 - Style1
$b_{10}$ = Style5 - Style1
Plug this into the null hypothesis and you have:
$H_0$: Style4 - Style1 = Style5 - Style1
When you add Style1 to both, you get:
$H_0$: Style4 = Style5
And bingo, that tells you if the difference between levels 4 and 5 of Style is statistically significant.
So no, do not recode the insignificant levels into the same category. You are (a) implicitly treating those levels as if they were conceptually the same (which they likely are not) and (b) it is very likely that some of the pairwise comparisons between levels 2, 3, 4, and 5 are significantly different from one another, meaning you wouldn't want to collapse across those anyways.


Meu site não aparece nos buscadores do google

Question: Olá, tem uma pergunta semelhante aqui, porém não tem uma resposta válida e acredito que o motivo do site dele não aparecer no rank talvez pode ser diferente do meu.
Enfim, o site http://cursodeimersao.com.br/ já está online a alguns meses.
Fiz alguns testes de SEO nele e ele está com SEO regular.
http://www.seomaster.com.br/ferramentas/analise-seo-gratis/592725
https://www.woorank.com/pt/www/cursodeimersao.com.br
O problema não é o SEO, o problema é que não acho ele no rank do google. (nem  na 20º página e nem em nenhuma).
Porém no bing está logo no topo da pesquisa.
http://www.bing.com/search?q=curso+de+imers%C3%A3o&go=Enviar&qs=n&form=QBLH&pq=curso+de+imers%C3%A3o&sc=8-14&sp=-1&sk=&cvid=e33d41efd45d4003989c6e98baefd59a
Como eu faço para este site aparecer no rank do google? Possuo outros sites, mas este é o único que não aparece.
Comment: No Google com certeza ele está, basta procurar por [site:cursodeimersao.com.br](https://www.google.com.br/?gfe_rd=cr&ei=j5NLVdWjFeeU8Qeb34H4Dw&gws_rd=ssl#q=site:cursodeimersao.com.br). Agora, se ele não está na posição ou página que você esperava, talvez seja questão mesmo de melhorar ele de tal forma que o *rankeamento* seja melhorado, até mesmo o tempo de vida dele, que pelo *whois* me parece que tem pouco mais de 3 meses.
Answer: Tente adicionar a URL junto ao Google manualmente.

Google Add URL
Google Webmaster Add URL

Neste segundo link você deve logar com sua conta Google.
Comment: O primeiro link está quebrado (404).
Comment: @MarcusVinicius, se você estiver logado com seu gmail,você conseguirá acessar. Ou senão, acesse: https://www.google.com/webmasters/ e crie seu cadastro no webmaster tools para adicionar URL
Answer: O Google, via de regra, "segura" o ranking dos novos sites, impedindo eles de aparecer nos resultados de busca. Pelo menos por algum tempo. Ou seja, mesmo que você trabalhe seu SEO e obtenha um alto ranqueamento em pouco tempo, seu site não consegue aproveitar todo seu ranqueamento durante um tempo. A liberação é gradual.
O Google faz isso no intuito de preservar a relevância de seus resultados, e combater práticas "SEO black hat".
Segue abaixo uma estimativa de quanto o Google "segura" seu ranqueamento de acordo com o tempo de vida do site:

Até 1 mês: segura 100% do ranqueamento
Até 2 meses: segura 75% do ranqueamento
Até 6 meses: segura 50% do ranqueamento
Até 1 ano: segura 25% do ranqueamento
Até 2 anos: segura 10% do ranqueamento
Até 3 anos: segura 5% do ranqueamento
Até 4 ano: segura 0% do ranqueamento

Esses números são apenas estimados, mas dão uma idéia do comportamento do seu site nos resultados de busca.
Comment: Tem referências desses dados?
Comment: Muito interessante, você tem alguma fonte sobre o assunto?
Comment: é fácil de achar no google, mas eu indicaria o livro Outsmarting Google: SEO Secrets to Winning New Business (Que Biz-Tech), ele é bem completo sobre o assunto
Comment: Conforme livro citado acima


Using arrays and structures within functions in c++

Question: I am trying to create a program that randomly generates the position of "ships". I'd like a structure to keep track of multiple aspects of the ships including their positions and an array to keep track of multiple ships.
The error I'm getting seems to be occurring in the first for loop within "main" at the line fleet[i] = ship_position (fleet[i], i); The error reads:

error: cannot convert 'ship_stats' to 'ship_stats*' for argument '1' to 'ship_stats ship_position(ship_stats*, int)'

Also, previously, I did not think the second "i" within the brackets of that line was necessary, but when I tried compiling without it the error I received was:

error: expected primary-expression before ']' token

#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

int rand_range (int low, int high) {
    return rand() % (high - low + 1) + low;
}

struct ship_stats {
    int x_coordinate;
    int y_coordinate;
    int weapon_power;
};

ship_stats fleet[5]; // Create fleet of 5 ships linked to the structure

ship_stats ship_position (ship_stats fleet[], int ship_num) {
    //Randomly generate a starting position for each ship
    int low_x = 0; //Set max and min ranges for ship position
    int high_x = 1024;
    int low_y = 0;
    int high_y = 768;

    fleet[ship_num].x_coordinate = rand_range (low_x, high_x);
    fleet[ship_num].y_coordinate = rand_range (low_y, high_y);
    return fleet[ship_num];
}

int main () {
    int num_ships = 5;

    for (int i = 0; i < num_ships; i++)
        fleet[i] = ship_position (fleet[i], i); // <-- error is here
}

Comment: Why are you declaring the `ship_stats fleet[5]` in global space then trying to pass it to a function?
Comment: The error message is quite clear - you are trying pass in a single `ship_stats` while the function expects an array of them (which decay to pointers in C++) => `ship_position (fleet[i], i);` should be `ship_position (fleet, i);`
Comment: I think you should look up more about arrays in C (and C++). Here is a good tutorial: https://www.tutorialspoint.com/cprogramming/c_arrays.htm (there is also another reference where an array as parameter is covered)
Answer: The mechanical point you have been given is that if you want to pass "raw" arrays as parameters in C++ (or C), you can't say fleet[].  That will not compile, as you noted.  But don't just put a random index value in the brackets--that gets you an array element, not the array itself.
It's a somewhat gross oversimplification to say you pass the "whole raw array" just by saying fleet.  You're really passing the address of the first element, e.g. fleet ends up being equivalent to &fleet[0].  Crude though that is, it comes from C's heritage...and it means that if the function you're calling knows the size of the "raw" array, then that address can be meaningfully used as a means of accessing any subsequent value in it.
But in "idiomatic" C++, one rarely wants to use a "raw" C-style array.  The std::vector solves several weak points of raw arrays, and is a good choice for beginners.
You can choose to pass vectors "by value" (which makes a copy) or "by reference" (which is a bit like passing by pointer, the only choice for a raw array).  Vectors don't have to know their size in advance, and their size can change over the course of your program.  Not only that, the size comes along with the vector when it's passed as a parameter.  And very importantly, vectors speak an abstract "collection protocol", which means they're usable with #include <algorithm>.
But there are several other points.  You have made a ship_position() function that "constructs" a ship.  This oddly shaped function returns a value (the instance of a constructed ship), yet also mutates your "fleet" so that the ship is in that position.  Why would you need to return the value and assign it to the location in the fleet...if that mutation of the fleet was already part of the function?
And in C++, the best mechanism for "constructing" something is...a constructor.  ship_position() is what we would call a "free function"--it doesn't live within ship_stat's definition, yet it seems to have an eerie knowledge of how to manipulate ships.
(Supporting Note: Where does weapon_power fit into all this?  Whose job is it to initialize it, or not?  This is where a single point of responsibility of a "constructor" comes into place, to say that a constructed ship has all its fields covered.)
If this is to be a proper C++ program, you shouldn't think of ship_stats as a struct that is operated on by "free functions".  Instead, you need to think of Ship as a class with some data, and some code.  The randomization of a ship should be inside your class... the act of putting a random ship into a collection should be using push_back into a vector (or emplace_back, but that's very much skipping ahead).
Try not to use raw C arrays in C++ programs unless you really know what you're doing.  (Or don't use C++ features and instead tag your question C, the answers will be very different.)
Comment: Thank you for such a detailed answer. The fix was simple (changing "fleet[]" to "fleet"). But going off of the other points you mentioned, I'm still a bit confused as to what you're saying is the proper way for my function to be written.

For clarification, I'm working through an intro to C++ book and I'm only about a third of the way through (Pointers are next chapter). The author gave an example function

EnemySpaceShip getNewEnemy ()
{
    EnemySpaceShip ship;
    ship.x_coordinate = 0;
    ship.y_coordinate = 0;
    ship.weapon_power = 20;
    return ship;
}
Comment: However, he did say that

"This function will actually make a copy of the ship local variable that it returns. This means that it will copy every field of the structure into a new variable, one by one."

but that this issue would be addressed in the next chapter.
Comment: @mcjack32 There's a lot of variance in quality in C++ books, and it sounds like you might *(read: almost certainly)* need a better one.  There's a good [book list here on StackOverflow](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and I most recently was sent a review copy of the updated C++ Primer, which I thought was laid out pretty well.
Answer: Like already stated in the comments you are trying to pass one ship_stats to function thats waiting for an array of them , so for the function to work it should look like this
ship_stats ship_position (ship_stats fleet, int ship_num) {
    //Randomly generate a starting position for each ship
    int low_x = 0; //Set max and min ranges for ship position
    int high_x = 1024;
    int low_y = 0;
    int high_y = 768;

    fleet.x_coordinate = rand_range (low_x, high_x);
    fleet.y_coordinate = rand_range (low_y, high_y);
    return fleet;
}

Answer: Try
#include <string>
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

int rand_range(int low, int high) {
return rand() % (high - low + 1) + low;
}

struct ship_stats {
int x_coordinate;
int y_coordinate;
int weapon_power;
};

ship_stats fleet[5]; // Create fleet of 5 ships linked to the structure

ship_stats ship_position(ship_stats IndividualShip, int ship_num) {
//Randomly generate a starting position for each ship
int low_x = 0; //Set max and min ranges for ship position
int high_x = 1024;
int low_y = 0;
int high_y = 768;

IndividualShip.x_coordinate = rand_range(low_x, high_x);
IndividualShip.y_coordinate = rand_range(low_y, high_y);

return IndividualShip;
}

int main() {
int num_ships = 5;

for (int i = 0; i < num_ships; i++) {
    fleet[i] = ship_position(fleet[i], i); // <-- error is here
}

}

In the above code, I've changed the function parameters of ship_position to accept an individual ship rather than the array as a whole. Your code should compile. Also, if this is C++ rather than C, consider using the for loop
for (ship_stats& j : fleet)
    std::cout << j.x_coordinate << " " << j.y_coordinate << endl;

to output the results of your program, using <   iostream   > of course.
Comment: While I appreciate the spirit of wishing to help, why would you take an individual ship (uninitialized) as a copied parameter, and then return a mutated version of that copy?  Why correct code without removing an unused ship_num parameter?  If you are going to mutate the ship, it should be passed by reference.  It's much more important when trying to guide people from the C to C++ mindset to talk about constructors vs. syntactic sugar on `for` loops that does not address the problem.  See [my answer](http://stackoverflow.com/a/42602465/211160), as you might benefit from it.


ERRO: Função para inserir palavra em cadeia de caracteres

Question: Escrevi uma função para receber uma cadeia de caracteres, um carácter e uma posição .
<code>  /**
    * Funcao para inserir um simbolo em certa posicao valida ENTRE outros
    * em dada cadeia de caracteres.
    * @param a - cadeia de caracteres
    * @param b - character a inserir
    * @param c - posicao de insercao
    * @return cadeia de caracteres com character inserido.
    *
    * Teste:
    *   Para a = "palvra", b = 'A' e c = 3
    *   retorna palAvra
    *
    *   Para a = "algorimos", b = 'T' e c = 6
    *   retorna algoriTmos
    */
  public static String original (String a, char b, int c){

    String nova;
    int tamanho;
    int i;

    if (a == null) {

      nova = ("Erro: string nula.");

    } else {

      tamanho = a.length();

      // e' necessario que a string tenha ao menos duas letras para inserir
      // caracteres entre a cadeia de caracteres
      if (tamanho < 2) {

        nova = ("Erro: tamanho da palavra invalido.");

      } else {

        // para que a posicao seja valida ela precisa estar entre o
        // primeiro e o ultimo caracter da cadeia de caracteres.
        if (c > 0 && c < tamanho) {

          nova = ("Erro: posicao invalida.");

        } else {

          nova = "";

          for (i = 0 ; i < tamanho ; i++) {

            if (i != c) {

              nova = nova + a.charAt(i);

            } else {

              nova = nova + b + a.charAt(i);

            } // fim do if else

          } // fim do for

        } // fim do if else

      } // fim do if else

    } // fim do if else

    return (nova);

  } // fim do original

  /**
    * metodo para testar a funcao original
    */
  public static void teste_01(){

    String n;
    String a;
    char b;
    int c;

    a = IO.readString("\nPalavra: ");
    b = IO.readchar("Caracter: ");
    c = IO.readint("Posicao: ");

    n = original(a, b, c);

    IO.println("\nString: " + n);

  } // fim do teste_01
</code>
A função esta funcionando ok, exceto pelo fato de não estar retornando o erro para posições invalidas (quando eu coloco uma posição maior ou igual ao tamanho da string), não consegui entender o por que.
Answer: <code>if (c > 0 && c < tamanho) {

      nova = ("Erro: posicao invalida.");

    }
</code>
no if acima ocorre a verificação de a posição é correta , se a posição for correta, esse trecho de código é executado. O Problema e que seu código de inserção do caractere deveria vim nesta parte, e não else


Checking if two virtual machines are running on the same host

Question: Is there a way to see if several Virtual Machines are running on the same host? Specifically, I have three VMWare VMs (each running a Ubuntu Server 14.04) and I have tried to compare different pieces of information:

dmidecode -s system-serial-number gives different results for each VM
lspci returns the same output for each VM
cat /proc/cpuinfo returns similar values for two of them and one has a completely different output (notably the "model name" line is different)

This doesn't help me to find determine which ones are running on the same host (if any).
Are there any other way to check?
Comment: @pauska actually I can imagine a few scenarios. For example for making sure all your DB replicas are not running on the same physical host, when the virtualization provider is untrusted third party ... (and yes, this s***ty politics happens in large 'professional' corporations as well)
Comment: In what professional setting do you need to figure this out? Does it matter where the VM's run, as long as they're up? Can't you ask the people administrating the virtualization hosts?
Comment: So you haven't contacted support to report your problem because you want to identify the problematic host first? That makes no sense to me. Why would it matter to you from a support perspective? If I have a problem with a service, I don't generally try to isolate the cause of the problem for the service provider before I call for support. That's their job. I call them and report the problem and let them do the work of finding it and resolving it.
Comment: "in what professional setting do you need to figure this out?" I have a build server that's one the physical box as my lower test environment vms (SIT)... For full builds (~1.2 Gb tar.gz) i can either transfer files over the network (~5-10 minutes) to deployment server or copy locally (<1min) and execute deploy, shaving about 10min off total run time on avg...
Comment: It's annoying to have people question the *why* of your question. There are plenty of reasons why you'd like to know whether 2 instances run on the same host, and I'll add one: **redundancy**. If you're using a load balancer with a few instances behind it for redundancy, but all these instances are on the same host, then you pretty much have zero redundancy. If the host fails, your whole infrastructure is down.
Comment: @pauska I am not managing the hosts and have been encountering some disk performance issues on some VMs. I'd like to confirm that it's only affecting a particular host before I contact anybody.
Comment: @joeqwerty it's not that type of situation. I don't want to elaborate but it's not a client/support type of situation and, because of bad dynamics with the other party, I can't ask them or find an alternative. Can't "report" the problem to anyone really. I understand context is important but I'd like to have an answer (even if the answer is "not possible") to my technical question regardless of the particular business context :)
Comment: @ixM have you found any way to check that?
Comment: @Bruno Bieri Sadly not...
Answer: If vmware tools are installed then below command can be used on both machines to verify physical host's hostname
/usr/bin/vmtoolsd --cmd "info-get guestinfo.hypervisor.hostname"
Answer: It's not 100%, but there are some tricks you can try with networking...
If you can trace route to each VM, then look for them all to go through the same second-to-last hop. If that's the case, there's a decent chance they're on a common host.
Try pinging from VM to VM and from VM to default gateway. If the VM-to-VM times are the same and ≤ the VM-to-defgw times, then there's a high probability that they're on the same machine. (Look at the minimum time across lots of pings for best results).
If you know more about the actual network topology from backbone -> host -> guest then you may be able to glean additional insight from network tools.
You can also try looking at the MAC addresses on the VMs for some clues.


django template slice css behaviour

Question: I was working on a small blogging engine for fun which allows for html contents. Also on the home page every blog post is sliced to 500 and displayed.
While I was coding this element it struck me that such a slice could be very dangerous. Assuming there is a  tag in the blog post which is sliced after the tag is opened, this would make every other content of the home page become bold.
I was wondering if Django itself has any mechanism to slice only after an html element has been completely closed or if there is any other way in which such a problem can be solved.
Answer: The truncatewords_html template filter takes into account tags that might have been opened but not closed given the slice.
Take a look in the docs at: https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#truncatewords-html for the filter's use and have a look at line 140 in django/utils/text.py at the _html_words() function which is leveraged by truncatewords_html
Comment: Yeah, Django is simply the most badass web framework I've ever used :)
Comment: this is brilliant. I knew django had to have some sort of implementation for this, like for almost everything else.

django template slice css behaviour


Itens não são mostrados no dataGridView

Question: Estou usando o seguinte código para incluir itens em uma lista e mostrar a mesma no meu DataGridView:
PedidodetalheOffline item = new PedidodetalheOffline(); //crio um novo item
item.IdOffline = id; //seto o id
item.PedidoOffline = numero; //seto o numero do pedido
item.ItemOffline = iditem; //seto o item
pedido.Add(item); //adiciono o item à lista "pedido"
id++; //incremento a variavel id para nao repetir

MessageBox.Show(pedido.Count().ToString()); //quantidade de intens que tem na lista
gridPedido.DataSource = pedido; //passo a lista pro DataGridView

Esse é o código do botão que inclui itens na lista e passa pro DataGridView. O que ocorre é que na primeira vez funciona (o primeiro item é mostrado dentro do DataGridView), mas à partir do segundo, não funciona (continua mostrando apenas o primeiro). Incluí a MessageBox pra confirmar que os itens estão sendo incluídos na lista e confirmei que estão sim.
O que pode ser? Será que tem algum comando pra atualizar a lista ou o DataGridView cada vez que incluo um novo item?
Comment: escreve assim `gridPedido.DataSource = pedido.ToList()`
Comment: `pedido` é o que?
Comment: pedido é a lista
Comment: @VirgilioNovic funcionou perfeitamente! Obrigado. Se quiser, posta a resposta pra eu marcar. Abraço.
Answer: Troque isso:
gridPedido.DataSource = pedido;

por isso:
gridPedido.DataSource = pedido.ToList();

forçando o tipo de dado enviado para DataSource do DataGridView List<T>. Esse DataSource pode receber os tipos implementados das interfaces:

IList e IList<T>,
IListSource (Exemplo: DataTable e DataSet),
IBindingList (Exemplo: BindingList<T> classe) e
IBindingListView(Exemplo: BindingSource classe).

Referencia

Referencias:

Ways to Bind DataGridView in C# Windows Forms
DataGridView.DataSource Property
DataGridView WinForms Control

Itens não são mostrados no dataGridView


Inter-vlan routing issues

Question: I've been brought in to help administer a network and I've run into an issue - I'm not sure why this one is beyond me, however I figure an extra set of eyes on the problem may help resolve the issue.
I have an HP MSM720 controller and at the time I'm trying to set up a basic hotspot set up with access points. For the time being I'm just looking to have people authenticate with a PSK and access the internet and other resources (namely printers) on other vlans.
The user authenticates and the DHCP server on the controller gives them a 192.168.1.0/24 address. They are able to successfully browse the internet and ping machines on other networks, however they are unable to print to network printers that sit on the same LANs as the very computers that wireless clients can ping.
The (extremely simplified) topology is as follows

Computers on the wireless 192.168.1.1 network are able to ping computers on the 192.168.0.0 network, however cannot ping or print to the printers on the same network.
I'm baffled and I have no idea why this is the case. Can anyone shed some light on this for me? Can someone spot the error of my configuration?
EDIT : It should be noted that for whatever reason other computers on the 10.0.100.0/24 network cannot even ping the gateway of the Wireless Access network (192.168.1.1) - I'm not sure if this is relevant.
These are the VLANS listed on the controller.
Answer: My gut reaction is that the printers don't have default gateways specified, or have the wrong gateway specified (i.e. a gateway that can't route traffic back to the wifi clients). Can you verify that?
Edit:
Your comment vexes me a bit. There are computers in the 192.168.0.0/24 network that clients in the 192.168.1.0/24 network can ping. There are printers in the 192.168.0.0/24 network that clients in the 192.168.1.0/24 network cannot ping. Do the computers in 192.168.0.0/24 that do return pings and the printers in the 192.168.0.0/24 network that do not return pings have the same default gateway specified? If so, does the device acting as the default gateway have any kind of ACL or filtering capabilities that might be getting in the way?
The phrase "...or it didn't like something with the VLAN configuration." doesn't make sense to me. The printers, presumably, are connected to untagged member ports in the appropriate VLAN. I think you're mixing things up across layer boundaries.
Not everything in your diagram has an IP address listed for each interface. It's really unclear where routing is occurring because of that. If you would, please modify your diagram to include:

IP address and location of the interface in the 192.168.0.0/24 network used as the default gateway for printers
IP address and location of the interface in the 192.168.1.0/24 network used as the default gateway for wireless clients
IP address and location of the interface in the 10.0.100.0/24 network used as the default gateway for clients in that network

Just throw some arrows on the diagram w/ callouts pointing to the devices where these IPs are configured.
Comment: We have tested that. I can confirm that the gateway is correct, although the address is 192.168.0.15 for the gateway - I'm wondering if that may be the issue in that the printer wants to look for a .1 address, or it didn't like something with the VLAN configuration.
Comment: I have updated the drawing to reflect your questions and noted what the controller views as the "Internet Network" and the "Access Network". My "didn't like something with the vlan configuration" is in reference to the fact that I'm not sure if the networks are properly tagged.
Comment: What about my questions in the paragraph after the word "Edit:"?
Comment: Yes they have the same default gateway specified and there are no ACL's that should prevent the traffic. There is ICMP traffic flow across the network to computers, but not PC's. Any "interior" firewalls were dropped for testing purposes and the printers are still not able to be printed to or ping'd
Comment: I'd sniff the traffic between the printer and its LAN, then, to see if echo requests are ever getting to it from the wireless clients. Depending on what I find there I'd move my sniffer to either find where the echo request is being dropped or, if the printer is receiving the request and responding but the response is never getting back to the client.
Answer: Running a traceroute to the printer from a different part of network address will give an idea of where the deadend is.  If the printer has network diagnostic tools, try those.
Try temp configure a laptop with printers IP configs & ping,tracert to other parts of the network - this will give you a prespective from printer's side of the network.

Inter-vlan routing issues


Show that a square with vertices t, u, v, w has center 1/4 (t+u+v+w).

Question: I need a help with this question!
Show that a square with vertices t, u, v, w has center 1/4
(t+u+v+w).
Answer: Note that $1/4(t+u+v+w)$, if t, u, v, and w are integers gives the mean(average) of the four numbers. This may help in your understanding of how the center of the square is $1/4(t+u+v+w)$.
Comment: I figured this one out, let P be the center point,

Let u, w be diagonals, and t, v be diagonals.

p=u/2 + w/2,
p=t/2 + v/2,

2p = u/2 + w/2 + t/2 + v/2,

p = 1/4(u+w+t+v),

:D


A difficult Limit Problem

Question: Suppose $x \in \mathbb{R}$, evaluate
$$ f(x)=\lim_{n \rightarrow \infty}\left|\frac{x^n}{n(1+x^{2n})} \right|^{\frac{1}{n}}$$
Numerical evidence seems to support a conjectured answer of
$$
   f(x) = \left\{
     \begin{array}{lr}
       -\frac{1}{x} & : x<-1\\
       |x| & :|x|\leq 1 \\
       \frac{1}{x} &: x>1
     \end{array}
   \right.
$$
Any help on this one? Of course it can be written as
$$f(x)= |x|\lim_{n\rightarrow \infty}\left|\frac{1}{n(1+x^{2n})} \right|^{\frac{1}{n}}$$
which I assume can be L'Hopotalized, however any work I've tried seems to just get really..messy.
Comment: You can squeeze $n^{-1/n}\to 1$ out of the limit too. Now you have $1+x^{2n}\to (x^2)^n$  for $|x|>1$ and $1+x^{2n}\to 1$ for $|x|<1$.
Answer: Yes, your conjencture is correct.
Consider the term of $\dfrac{x^n}{1+x^{2n}}$ at $n\to\infty$
For $|x|<1$ this is asymptotically equivalent to $x^n$.
For $|x|>1$ this is asymptotically equivalent to $\dfrac{1}{x^n}$.
Does that help?
Comment: Ah, I didn't think of using $a_{n} \rightarrow L$ implies that $a_{n}^{1/M} \rightarrow L^{1/M}$ Thanks, this should simplify things immensely.

A difficult Limit Problem


$P(A_i \cap A_j) = \emptyset$: An Error in Describing the Probability Function?

Question: I am reading Statistical Theory: A Concise Introduction, by Felix Abramovich and Ya'acov Ritov. In the the appendix, the authors provide a primer on basic probability theory. In discussing the probability function, the authors write the following:

The probability function assigns to each event $A \in \mathcal{A}$ a real number $P(A)$ called the probability of $A$ satisfying the following conditions:
...

If $A_1, A_2, ...$ are disjoint events, that is, at most only one of them can happen and $P(A_i \cap A_j) = \emptyset$ for all $i \not= j$, then $P(A_1 \cup A_2 \cup \ ...) = \sum_{i = 1}^\infty P(A_i)$.

$A$ denotes an event, and $\mathcal{A}$ is a set of events.
My question is, shouldn't it be $P(A_i \cap A_j) = 0$? After all, it makes no sense to say that $P(A_i \cap A_j) = \emptyset$.
Answer: It should indeed be either $A_i\cap A_j=\varnothing$ or $P(A_i \cap A_j) = 0$.
Apparently the author(s) accidently mixed them both up and the editor didn't notice this error.


Hide Drop down option base on the current date

Question: Is it possible to hide drop down option base on the current date ?
Pls have a look at the following code !
I have a drop down option as the following
options
1
2
3
4
.
.
.
30
31
By default - option 1 is selected .
Suppose to day is 10 for the present month.
I'd like to hide the rest of the drop down
from 11 to 31 !
Comment: Full code at : https://jsfiddle.net/74v95d59/7/
Answer: For make this (with Jquery), create your option select dynamicly.

$(document).ready(function() {
   monthDay = 10;
   for(t=1;t<=monthDay;t++){
    opt = '<option value="content-'+t+'">'+t+'</option>';
    $("#target").append(opt)
   }

 })
.selectdate{
   background: #ea6153;
   padding:10px 5px;
   color: #fff;
   border-radius: 5px 5px 0px 0px;
   }
  .selectdate select{
   background: #ea6153;
   padding:5px;
   color: #fff;
 border: 1px solid #fff;
   }

 .inv {
    display: none;
}

   Please Select a Date
<select id="target">
<option value="content_today" selected="selected" >Todays NewsPaper</option>
</select>

Todays Newspaperz

Date 1</h3

Date 2

Date 3

Date 4

UPDATE - With Javascript only
Add a
Comment: Perfect , can this be done base on the current date , say if today is 25 , it shows from 1 - 25 . if possible can this be done without jquery , with simple script, if yes pls post the full code !
Comment: Its working on fiddle demo: https://jsfiddle.net/74v95d59/19/    but when i use the code on my system , its not displaying the div content. Any way to do this without jquery
Answer:
Use getDate() method of date object to get the current date.
Iterate through all the options using querySelectorAll and set display to none to those elements whose innerText is greater than current date.

    var d = new Date();
    var n = d.getDate();
    var options = document.querySelectorAll("#target option");
    Array.prototype.forEach.call(options, function(item) {
      var text = parseInt(item.innerText, 10);
      if (text >= n) {
        item.style.display = 'none';
      }
    });
    document.getElementById('target').addEventListener('change', function() {
      var vis = document.querySelector('.vis'),
        target = document.getElementById(this.value);
      if (vis !== null) {
        vis.className = 'inv';
      }
      if (target !== null) {
        target.className = 'vis';
      }
    });
.selectdate {
  background: #ea6153;
  padding: 10px 5px;
  color: #fff;
  border-radius: 5px 5px 0px 0px;
}
.selectdate select {
  background: #ea6153;
  padding: 5px;
  color: #fff;
  border: 1px solid #fff;
}
.inv {
  display: none;
}

  Please Select a Date
  <select id="target">

    <option value="content_today" selected="selected">Todays NewsPaper</option>
    <option value="content-1">1</option>
    <option value="content-2">2</option>
    <option value="content-3">3</option>
    <option value="content-4">4</option>
    <option value="content-5">5</option>
    <option value="content-6">6</option>
    <option value="content-7">7</option>
    <option value="content-8">8</option>
    <option value="content-9">9</option>
    <option value="content-10">10</option>
    <option value="content-11">11</option>
    <option value="content-12">12</option>
    <option value="content-13">13</option>
    <option value="content-14">14</option>
    <option value="content-15">15</option>
    <option value="content-16">16</option>
    <option value="content-17">17</option>
    <option value="content-18">18</option>
    <option value="content-19">19</option>
    <option value="content-20">20</option>
    <option value="content-21">21</option>
    <option value="content-22">22</option>
    <option value="content-23">23</option>
    <option value="content-24">24</option>
    <option value="content-25">25</option>
    <option value="content-26">26</option>
    <option value="content-27">27</option>
    <option value="content-28">28</option>
    <option value="content-29">29</option>
    <option value="content-30">30</option>
    <option value="content-31">31</option>

  </select>

Todays Newspaperz

Date 1</h3

Date 2

Date 3

Date 4

Fiddle here
You can also do this using dynamically creating options If your DOM is not pre-created.
Try this:

var d = new Date();
var n = d.getDate();
var options = '<option value="content_today" selected="selected">Todays NewsPaper</option>';
var targetElem = document.getElementById('target');
for (var i = 1; i <= n; i++) {
  options += '<option value="content-' + i + '">' + i + '</option>'
}
targetElem.innerHTML = options;
targetElem.addEventListener('change', function() {
  var vis = document.querySelector('.vis'),
    target = document.getElementById(this.value);
  if (vis !== null) {
    vis.className = 'inv';
  }
  if (target !== null) {
    target.className = 'vis';
  }
});
.selectdate {
  background: #ea6153;
  padding: 10px 5px;
  color: #fff;
  border-radius: 5px 5px 0px 0px;
}
.selectdate select {
  background: #ea6153;
  padding: 5px;
  color: #fff;
  border: 1px solid #fff;
}
.inv {
  display: none;
}

  Please Select a Date
  <select id="target">
  </select>

Todays Newspaperz

Date 1</h3

Date 2

Date 3

Date 4

Comment: Rayon Dabre... nice example
Comment: Your example does not hide value from 11 to 31
Comment: Still its not hiding drop down option - today is 11 so the rest 11-31 - on the drop down shouldn't be displayed ,  if today is 15 , the drop down should display from 1- 15  ,  in short .. the drop down option value should depend on the current date . but its not happening !
Comment: Hi! Rayon .... its still not ... pls check this link : https://jsfiddle.net/74v95d59/19/      its working here but can you help me do this without using jquery .thanks a lot !
Comment: Thanks Buddy - You are Awesome !
Comment: Accepted! Yes its the exact code i was looking for ! Thanks once again !


Windows Networks available over the internet

Question: I am trying to develop a windows network audit/discovery application
As I do not have a windows network available at home to test on
I got to wondering whether or not there is any type of "test/sandpit" windows network available over the internet.
does anyone know of such a service?
Answer: I would imagine if there was then it wouldn't be somewhere I would want to go anywhere near with my PC!
The most common way to do what you need would be to create a number of virtual machines to provide you with a network to work with. Tools like VMWare Workstation or Virtualbox will let you do that on your desktop. Alternatively if you don't have the resources then you could look at using one of the many cloud providers such as Amazon or Rackspace to provide you with a cloud based network.
Comment: Dear Sam thanks very much for your time in answering my question


Ruby on Rails: Is it possible to request the current time from the SQL server?

Question: In a previous question about overriding Time.now, I was working toward a solution of faking clock synchronization across all machines connecting to a given database.  Overriding Time.now seemed the best way for the approach I was taking, however:
It appears as though I could get the result I was after via a much simpler line.  If I can get the SQL server's current time, my life will be much simpler.
On each machine, I can do something like; Record create, examine creation_time in Record, Record delete, but if there is something simpler, I'll take it.
I've seen SELECT GETDATE() (oracle) and SELECT NOW() (mysql) and like forms.  The people that review my code are unlikely to like direct-to-sql calls.  I really need something through rails - if it exists.
Comment: So if you just need to synch to anytime and you don't want to query a database but you want to get the time there. Why does it have to be THAT server wouldn't ANY single clock defined as the standard work?
Comment: Considering that I plan to have a dozen machines all working in this system and the only unifying point among them is the connection to the SQL server via active record, it seems unlikely that any easier synch mechanism _could_ exist than using that server's time, if an easy access exists.  =]
Answer: SELECT GetDate() would yield the current time from SQL Server
Comment: That's fine in Oracle, but not in MySQL.  And for the sake of clean code, I'd rather do this through a rails interface than an implementation-specific one, if at all possible.
Comment: That doesn't work in Oracle... not sure why you'd say that. You said, "If I can get the SQL server's current time, my life will be much simpler" That's how you get SQL Server's Current time.


Usando ImagemView para carregar foto da galeria

Question: Eu quero fazer um programa que eu carregue uma foto para uma ImagemView da galeria do Android.
Preciso de um código para abrir a galeria e salvar a imagem como se fosse para um perfil.
Comment: Achou alguma solução? poste como resposta para ajudar outros usuários!
Comment: http://tjkannan.blogspot.in/2012/01/load-image-from-camera-or-gallery.html http://www.coderzheaven.com/2012/04/20/select-an-image-from-gallery-in-android-and-show-it-in-an-imageview/ Verifique os exemplos destes links e veja se ajuda você assim como outros desenvolvedores que queiram fazer o mesmo.
Comment: Conseguiu resolver seu problema com a resposta? Ou precisa de mais alguma informação?
Answer: Primeiro passo
Dar permissão de leitura usando READ_EXTERNAL_STORAGE para fotos da galeria no manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Segundo passo
Criar uma simples intenção
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

Terceiro passo
Exibir foto na em um ImageView explorando o ciclo de vida da aplicação, utilizando o método onActivityResult().
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.iv);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
}

Boa sorte!


A variance of how much is acceptable for a column before we can use it for modelling?

Question: I am trying to create a classification model. While pre-processing the data. I look at the variance in each column. This is the amount of variance in each column. I am confused on which all columns should I log transform before modelling. How much variance is acceptable? Could somebody please shed s
<code>
Temparature     2.318567e-01
HR              4.747868e+02
SpO2            1.179291e+01
SBP             6.263887e+02
MAP             2.905884e+02
RR              2.794205e+01
FiO2            9.061920e+00
PaO2            1.327011e+03
PaCO2           7.466527e+01
pH              4.851681e-03
A.a.gradient    0.000000e+00
HCO3            1.358290e+01
Hb              5.337076e+00
TLC             6.326940e+07
Platelets       1.062145e+10
K               3.332203e-01
Na              4.429681e+01
Serum.Cr        1.897277e+00
Blood.Urea      7.321509e+02
Bili            3.352918e+00
Urine.output    5.157271e+05
Lactate         3.795719e+00
INR             5.362644e-01
dtype: float64

`````````````````````````````````````````
</code>
Comment: Why do you believe that there is a maximum amount of acceptable variance?
Comment: I am taking this ML course and was told in a class of log transformation of variables if the variance is too high compared to the other variables. I am not sure on how to decide on when to apply log transform.
Comment: That sounds like advice that is safely ignorable, or at least begging of a follow up "why?".
Comment: I can think of some situations where you might want to re-scale the variables to be meaningful, i.e. you might transform something like Gross Domestic Product from raw dollars into billions or trillions of dollars. Sometimes, vastly different scales can cause convergence trouble. However, log transforming now mean you assume the variable has a non-linear effect, and this may not be what you want to do. I, too, have never heard that you should log transform simply because the variance is over some amount.
Comment: Side note: is the variance of heart rate really 475 or so, and the variance of temperature really 0.232? Those look like potential data errors.
Answer: This answer argues that, "The only time you would be justified or correct in taking the Log of $Y$ is when it can be proven that the Variance of $Y$ is proportional to the Expected Value of $Y^2$".
If there is high variance but it is inappropriate to log transform, one way to deal with some columns having higher variance than others is to put them on equal footing by performing input normalization
This ensures that all your columns have a variance of 1.


Erro ao utilizar o POST AngularJS

Question: Meu controller está assim:
app.controller("listaTelefonicaController", function ($scope, $http)

Dentro dele está minha função de adicionar
ctrl.adicionarContatos = function (contato) {
            contato.telefone = ctrl.formatCel(contato.telefone);
            console.log(contato);
            var data = JSON.stringify(contato);
            $http.post("/contatos.json", {cont: data},{headers: {'Content-Type': 'application/json'}}).then(
                 function (response) {
                     console.log("success:" + response);
                     delete ctrl.contato;
                     $scope.contatoForm.$setPristine();
                     return response;
                 },
                 function (response) {
                     console.log(response);
                     return response;
                 }
             );

            // $http({
            //         url: 'http://127.0.0.1:5500/contatos.json',
            //         method: "POST",
            //         headers: {
            //             'Content-Type': 'application/json',
            //             'Accept': 'application/json'
            //         },
            //         data: contato
            //     })
            //     .then(function (response) {
            //             console.log("success:" + response);
            //         },
            //         function (response) { // optional
            //             console.log("Fail:" + response.data);
            //         });
            };

Fiquei algumas horas procurando e testando de várias formas e todas apareciam o mesmo erro:

POST http://127.0.0.1:5500/contatos.json 405 (Method Not Allowed)

Esse arquivo está populado com alguns dados como esse abaixo:
{
    "nome": "Larissa",
    "telefone": "9999-3399",
    "cor": "orange",
    "data": "2015-04-12T12:53:46.204Z",
    "operadora": {
        "nome": "GVT",
        "codigo": 25,
        "categoria": "Fixo"
    }
}

O GET deu tudo certo, mas quando tento fazer com o POST ele da esse erro, já fiquei algumas horas procurando e não encontro uma forma de solucionar meu problema.
Entra direto na opção de erro do POST.
Comment: Que eu saiba, o Angular não precisa de `var data = JSON.stringify(contato);`. O Angular por padrão já faz isso (e com o header application/json)
Comment: fiz isso para tentar resolver o problema, mas mesmo sem isso não funciona
Answer: @EduardoBobato não tenho certeza do que vou te dizer agora pois nunca vi isso em lugar nenhum e a resposta é da minha cabeça mas acho que voce nao pode dar um post para um arquivo .json, visto que json não é uma linguagem de programaçao provavelmente não tem suporte para variaveis tipo post.
Se seu servidor suportar php tente mudar o arquivo contatos.json para contatos.php e coloque no seu interior o codigo:
<?php
print_r(
  json_encode(
    [
        "nome"=> "Larissa",
        "telefone"=> "9999-3399",
        "cor"=> "orange",
        "data"=> "2015-04-12T12:53:46.204Z",
        "operadora"=> [
            "nome"=> "GVT",
            "codigo"=> 25,
            "categoria"=> "Fixo"
        ]
    ]
  )
);

Erro ao utilizar o POST AngularJS


Send 'compare product' action to Google Analytics

Question: I am having a products page in my site. In that I have a comparison functionality.
Now I want to send data to google analytics so that Admin can later on check which products were compared. I have captured the products I.E. on which products checkbox the user clicked and store that array of products in a jquery variable.
Now I want to send this variable in ga function but I am not able to do soo. Can anybody help me out with it or some other solution?
Comment: [Sending Data to Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits#hits_hit_types_and_the_measurement_protocol)
Comment: Drupal 7 or Drupal 8?
Answer: You can use GA Push module

GA Push offers an API to enqueue informations that are sent GA
  servers, and three submodules to track browser events (using jQuery),
  form validation errors and log exceptions.

So, you can use the API to send an event to Google Analytics when user adds a producto to the comparison.
For example, you can use the page view function and send virtual page views for each compared product:
$push = array(
  'location' => '/comparision/product/' . $nid,
  'page' => 'comparison',
  'title' => 'Product ' . $product_name . ' comparison',
);

ga_push_add_pageview($push);

This code should called when you detect that a product is being compared.
Disclaimer: I'm one of the developers of this module.
Comment: $(".page-personal-loans a.compare-btn").on('click', function(event){
  var selected = [];
$('.flag-compare-products input:checked').each(function() {
 var parent = $(this).parent().closest('td').text().replace(/remove/g,'').replace(/compare/g,'').trim();
selected.push(parent);
  });
$push = array(
'location' => '/comparision/product/' . $nid,
  'page' => 'comparison',
  'title' => 'Product ' . selected . ' comparison',
);
ga_push_add_pageview($push);
  });.,i want to send values in selected variable to google analytics in one hit so we can calculate which product were compared
Comment: If you are using Drupal 7 you can use GA Push Browser submodule to send data to GA at certain JS events.
Comment: can we have  skype call.I am having some issues over it
Comment: No, in that way you are the only one that gets help. If we write here the questions and answers it may help other people. You may start a chat, though.


identity for integration of analytic function

Question: I came across an identity for integration of analytic function , and I don't know how to prove it. Please help me with it, thank you. The statement goes as following
For any analytic function $f(\alpha)$
\begin{equation}
f(\beta) = \frac{1}{2\pi}\int f(\alpha)\exp{\{-|\beta-\alpha|^2/2\}}d^2\alpha
\end{equation}
in which $d^2\alpha=d\mathrm{Re}\{\alpha\}d\mathrm{Im}\{\alpha\}$
Answer: This identity follows from Gauss mean value theorem: If $f:\Bbb C\to \Bbb C$ is entire (with moderate growth), we have
$$\begin{align*}
\int_{\Bbb R^2}f(\alpha)e^{-|\beta-\alpha|^2/2}d\alpha&=\int_{\Bbb R^2}f(\beta+\alpha)e^{-|\alpha|^2/2}d\alpha\\&=\int_{0}^{2\pi}\int_0^\infty f(\beta+re^{i\theta})e^{-\frac{r^2}2}r drd \theta\tag{*}\\&=\int_0^\infty\left(\int_{0}^{2\pi} f(\beta+re^{i\theta})d \theta\right)e^{-\frac{r^2}2}r dr\\&=2\pi f(\beta)\cdot \int_0^\infty e^{-\frac{r^2}2}r dr\tag{**}\\&=2\pi f(\beta)\left[-e^{-\frac{r^2}2}\right]^\infty_0=2\pi f(\beta).
\end{align*}$$ $(*)$ : polar coordinate change. $(**)$ : mean value theorem is used.
Since harmonic functions have mean value property, the identity is true for every harmonic function.
Comment: Thank you very much!


How to use the YML structure of routes to control access to Group Content

Question: I am using the Group module and would like to leverage each Group's permissions in my module's yml files.
I have a module.permissions.yml with something like
tam_api.group_gid_members_uid:
  path: 'group/{group}/members/{member}'
  defaults: { _controller: '\Drupal\tam_api\Controller\TamApi::getGroupMember' }
  methods: [GET, HEAD]
  requirements:
    _permission: 'access user profiles'
  options:
    _format : ['json']
    _auth: ['oauth2', 'cookie']
    parameters:
      group:
        type: entity:group
      member:
        type: entity:group_content

I would like to change access user profiles to the View individual group members for the given Group?
Can this be done within the Structure of Routes?
Answer: in group.services.yml you'll find access_check entries like:
  access_check.group.permission:
    class: 'Drupal\group\Access\GroupPermissionAccessCheck'
    tags:
      - { name: 'access_check', applies_to: '_group_permission' }
  access_check.group.member:
    class: 'Drupal\group\Access\GroupMemberAccessCheck'
    tags:
      - { name: 'access_check', applies_to: '_group_member' }

you can use these in your routes like:
tam_api.group_gid_members_uid:
  path: 'group/{group}/members/{member}'
  defaults: { _controller: '\Drupal\tam_api\Controller\TamApi::getGroupMember' }
  methods: [GET, HEAD]
  requirements:
    _group_member: 'TRUE'
# or    _group_permission: 'view group membership content'
  options:
    _format : ['json']
    _auth: ['oauth2']
    parameters:
      group:
        type: entity:group
      member:
        type: entity:group_content

Note: the parameter argument must be named {group}


Is there anything wrong with this sort of model reduction (p value + AIC)?

Question: I have fitted a model with 7-8 covariates.
Here's what I do to reduce it:
I first look at the p-values. I select all covariates with p-values > 0.05. Then I remove them one by one, get the AIC, and then see what had the lowest values. I pick that model.
Then I repeat: again, look at p-values, pick candidates, do AIC.
Is this how it's usually done?
Comment: What are your reasons for removing the covariates in the first place? Removing them just because they are not significant is generally a bad idea, especially if they are warranted by the theory. I think that similar questions have already been asked; have a look at [this](https://stats.stackexchange.com/questions/66448/should-covariates-that-are-not-statistically-significant-be-kept-in-when-creat) and [this](https://stats.stackexchange.com/questions/133920/should-i-remove-non-significant-variables-from-my-regression-model)
Answer: I really would like to say that Michael R is spot on. The covariates in your model are included for a reason, e.g. their inclusion aligns with theory. For example, if I study school performance, I am going to include socioeconomic status in my model. Maybe socioeconomic status doesn't matter, but you can be certain that if it was not in my model, a reader would wonder why not and also wonder if that were the true cause of the effect. Parsimony is important, but so is creating a model that is firmly grounded in theory. In short, to answer your question, the only reason I would see to remove covariates is if there were issues of covariance between them, in which case, there is probably theory behind that as well (e.g. in the prior example a model that includes socioeconomic status and free/reduced lunch status would probably have a lot of covariance between the two covariates)


'Matrices not aligned' in one dot-product example, but works fine in a different example

Question: I need to do a dot-product between a simple pandas dataframe and a multi-index pandas dataframe.    I made a toy example to determine the right manipulation, which works fine.    However, when I do the same manipulation to my real data,  it complains, "ValueError: Matrices not aligned."
The thing is, I cannot see the what the difference between the Toy and Real dataframes are.  The .shape and .index seem to be identical.  The dtypes are different, but i cannot see how that makes a difference.
Does anyone see what the problem is, or what other difference  I'm not checking for?
.
Shapes look the same...

.
The dtypes are mostly the same...

Also the indices look same.

But the .dot operation works on the toy, fails in the real:

Generating the toy-example.
import pandas as pd
import numpy as np
yield_data = {"red_delicious":[0.4, 0.4, 0.2, 0.4, 0.45, 0.05],
"macintosh":[0.6, 0.2, 0.2, 0.61, 0.3, 0.05],
'fuji':[0.3, 0.3, 0.4, 0.3, 0.35, 0.35],
'config':["a"]*3+['b']*3,
'product':['juice', 'candy', 'pulp']*2}

toy_yield = pd.DataFrame.from_dict(yield_data, ).set_index(['config', 'product'])

index=pd.date_range(start="20191201", end="20191210", freq="d")
price_data = {"juice":(np.random.randint(6000,7000,size=(len(index)))/100),
             'candy': (np.random.randint(6000,7000,size=(len(index)))/100),
             'pulp':(np.random.randint(6000,7000,size=(len(index)))/100),
             }
toy_price = pd.DataFrame(data=price_data, index=pd.date_range(start="20191201", end="20191210", freq="d") )

toy_price.dot(toy_yield.unstack('config'))

Comment: Please share code/data as text in the post itself, not as images.
Comment: I linked to the code i used to generate the toy example.  I am showing all the measurements that seem to say my working dataframe is identical to the toy dataframe.
Comment: @user3556757, it's best if people can see and select code (if they want to copy) from the question, without having to follow links. Therefore, please share code, not images.
Comment: Please share the code of the variant, which doesn't work. Not the one that works (I think the one you call "the real")
Comment: Also - I was wondering- on this screenshot: https://i.stack.imgur.com/ycmSt.png what's "crude" and "Security"? It doesn't seem to be mentioned anywhere else...
Answer: Ooops... wasted mine and everyone elses' time on this sorry --  the issue was that the name of the columns being dotted with each other were different.  EG: in toy_price, the column was Pie and in the toy_yields frame, the column was called PIE.  Pandas couldn't match those. The error message wasn't super useful, but I didn't realize Pandas was smart enough to try that in the first place -- had assumed the dot() operation was applied by position of the columns.