Como verificar se a String é null ou em branco em Java / Android

Question: Passei por esse problema implementando uma biblioteca simples de consultas ao banco de dados sqlite em android e gostaria de compartilhar a solução com a comunidade, acredito que seja útil já que penei até encontrar uma solução simples.

Na implementação era necessário saber se a String do where era null ou vazia ou se era uma String em branco, sendo que a verificação de null e vazia era simples o problema era a String em branco.

E como fazer isso?
Comment: vale a pena a leitura: [Evitando comparação "!=null" em Java](http://pt.stackoverflow.com/q/4491/3117)
Answer: Mais uma API interessante para usar é a  Google Guava. Ela tem uma série de funcionalidades para esse tipo de tarefa.
Um exemplo de uso seria:
 import com.google.common.base.Strings;

 Strings.isNullOrEmpty(""); // retorna true para vazia
 Strings.isNullOrEmpty("   ".trim()); // retorna true para string em branco

Existem diversas outras funcionalidades para primitivos, e outros conceitos como por exemplo o uso de:
Precontitions:
Tratamento de estado booleano de alguma condição sem guava:
 if (estado!= Estado.INCOMPLETO) {
      throw new IllegalStateException(
              "Esse Objeto está em um estado " + estado);
 }

Ficaria mais simples com Guava, sem uso de ifs:
import com.google.common.base.Preconditions;

  Preconditions.checkState(
    estado == Estado.PLAYABLE, "Esse Objeto está em um estado  %s", estado
  );

CharMatcher:
Determina se um caracter é um constate como:
  CharMatcher.WHITESPACE.matches(' ');
  CharMatcher.JAVA_DIGIT.matches('1');

Ou usando um  factory method específico como:
  CharMatcher.is('x')
  CharMatcher.isNot('_')
  CharMatcher.oneOf("aeiou").negate()
  CharMatcher.inRange('a', 'z').or(inRange('A', 'Z'))

Detre muitas outras funcionalidades em uma lib de apenas 2,1KB. Que inclusive teve contribuição do @Josh Block.
Mais informações:

InfoQ Br - google-guava
Comment: Muito boa sua contribuição, vi na sua referência que ela foi integrada com o [Google Collection](https://code.google.com/p/google-collections/). +1 pela agregação.
Answer: A partir do Java 6, a forma mais eficiente e direta para verificar se uma String não é vazia é usando o método String.isEmpty(). Exemplo com a verificação de null:
if (str == null || str.isEmpty()) {
    //é nula ou vazia
}

Incluindo o trim():
if (str == null || str.trim().isEmpty()) {
    //é nula, vazia ou só contém caracteres de espaço, tabulação e quebras de linha
}

A implementação do isEmpty apenas verifica o tamanho (length) do vetor de caracteres interno da classe:
private final char value[];
public boolean isEmpty() {
    return value.length == 0;
}

Antes do Java 6 poderia ser feito assim:
if (str == null || str.length() == 0) {
    //é nula ou vazia
}

Incluindo o trim():
if (str == null || str.trim().length() == 0) {
    //é nula, vazia ou só contém caracteres de espaço, tabulação e quebras de linha
}

Answer: Esta é minha class utils:
public class StringUtils {

    // Verifica se a String é null ou vazia ou só tem espaços em branco
    public static boolean isNullOrBlank(String s) {
        return (s == null || s.trim().equals(""));
    }

    // Verifica se a String é null ou vazia
    // Pode ser utilizado como suporte em APIs menores que 9 do android onde não está disponivel o metódo de String isEmpty()
    public static boolean isNullOrEmpty(String s) {
        return (s == null || s.equals(""));
    }
}

Exemplo de utilização:
String teste = null;
System.out.println(StringUtils.isNullOrEmpty(teste)); // true
System.out.println(StringUtils.isNullOrBlank(teste)); // true

teste = "";
System.out.println(StringUtils.isNullOrEmpty(teste)); // true
System.out.println(StringUtils.isNullOrBlank(teste)); // true

teste = "    ";
System.out.println(StringUtils.isNullOrEmpty(teste)); // false
System.out.println(StringUtils.isNullOrBlank(teste)); // true

teste = "  t  ";
System.out.println(StringUtils.isNullOrEmpty(teste)); // false
System.out.println(StringUtils.isNullOrBlank(teste)); // false

Espere que seja de grande utilidade para vocês, assim como está sendo para mim.
Fonte: http://alvinalexander.com/blog/post/java/java-method-test-string-null-or-blank
Comment: Não sou especialista em Android, mas você não pode usar a **[Apache commons-lang](http://commons.apache.org/proper/commons-lang/)**? Acho melhor do que "reiventar" a roda. Aqui está a [**API da StringUtils**](http://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html) do commons-lang.
Comment: @RicardoGiaviti Talvez sim, não conhecia esse `API`. Só "reinventei" a roda por que não conhecia essa `API`. Mas de qualquer maneira para quem não quiser importar toda uma `API` para seu projeto, compartilhei uma dificuldade que tive. Mas obrigado pela dica, me parece uma boa alternativa pronta para usar. Muito útil sua ressalva.
Comment: Concordo com você @Fernando. Não valeria mesmo a pena importar toda a commons-lang para um única validação. O bacana da API é que ela tem muita soluções para esses problemas simples que nos deparamos no dia a dia e não precisamos ficar quebrando a cabeça. Acredito que toda a [**Apache Commons**](http://commons.apache.org/) é assim.


Works great when all tags are present (DOM)

Question: This works great when all tags are present:
$data=''
$html = $data;
$dom = new DOMDocument();
$dom->loadHTML($html);
$data = ($dom->getElementsByTagName('a')[0]->getAttribute('href'));

The output is
http://somelink.com

However if the first tag is missing
$data='a href="http://somelink.com">'

The output is blank and it actually makes the whole page go blank. Is there a way to still have the same output
http://somelink.com

even if the first tag is missing?
Comment: what you exactly want?
Comment: "Is there a way to still have the same output even if the first tag is missing?" Not that hard to understand...
Answer: No because then you don't have an HTML element tag, you have characters with spaces and quotes.
Comment: But why is it "killing" the whole page? Can at least that be fixed? I wouldn't mind if the output was the same as the original link without the tag. But when it all goes blank, that's an issue.
Comment: Unfortunately no. Without the opening `<` you no longer have valid HTML and the vast majority of parsers will not recognize it as such.
Comment: @MrK: The text may look like HTML to your human eyes, but to a browser, or DOMDocument, armed with only a left-to-right parser, `'a href="...">'` is indistinguishable from `'a friend in need'`. You no longer have an `a` element, so `getElementsByTagName('a')` simply isn't going to find anything. Best you can do, if you can't rely on the source markup getting something this simple right, is extract the URL directly from the input without using DOMDocument at all.
Comment: @zainul abdeen 's solution does the job.
Answer: I don't think it's possible. Because $dom->getElementsByTagName('a')[0]->getAttribute('href') by doing this you are storing the Attribute value of an HTML tag  in the variable $data. but if you remove the HTML tag then it's not possible to get the Attribute value of a tag That do not exist.
Apart from this, If you still want to do this by removing the HTML tag then You should use String Manipulation FUnctions to extract the URL from a string stored in php variable.
REGEX is also a solution to your problem.
Here is the code that will extract the URL from your string.
$data='a href="http://somelink.com">';
preg_match_all('@((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*(\\?\\S+)?)?)*)@', $data, $match);
echo $match[0][0]."
"; //URL of  tag
echo $match[0][1]; //URL of image tag

Comment: I tried to do this with:

`preg_match('/"([^"]+)"/', $data, $href);

$data = $href[1]; ` however when the first tag is missing, it strips everything. Is there a way to make sure that if the first tag is missing it simply outputs the original url without the first tag?
Comment: @MrK See my edited answer now. This will give you your expected result i.e `http://somelink.com`
Comment: WOW!! I just tested it and it works on all levels. I mean I tried several links that had a class="test" and target="_blank", with and without the first tag and the output was `http://somelink.com` That's so cool. I've been at it for the last 3 hours. Thought I'd never make it work. Thank you so much.
Comment: Can you help me with one more thing? It seems like your preg_match_all doesn't work if www. is present. It has to be part of the code since some urls will have https:// and some http://www. I'd appreciate if you could add this to your solution.
Comment: When I put something like (note the www): `` the output is `http://www` the rest of the link is stripped. Can it be fixed?
Comment: I just edited my answer. replace your `preg_match_all` with the current one
Comment: this will surely work. check it and let me. I already tested it on my end. Here it is working flawlessly even with `www`
Comment: show me your code. paste your `preg_match_all()` here


How can I calculate the bit density of a disc shaped object?

Question: I am trying to calculate the bit density of a disc shaped magnetic tape.
Okay so I know the following
The diameter is 3.38 inches

The film is 0.003 inches thick (when viewed on its side)

The bit density is 0.62 Gb/mm2

I made the following attempt which I know to be incorrect
The disc has 35.8909 square inches in total

There are 23155.37304 mm2 in 35.8909 square inches

The bit density is 0.62 Gb/mm2

23155.37304 x 0.62 =  14356.3312848 Gb

This yields 14.3563312848 (14.36Tb) which sounds wayyyyy too low
I am guessing the issue is that I am calculating in 2-Dimensions and not accounting for thickness? How can I more accurately calculate the bit density considering we are working in 3D?
Comment: The length of a spool of tape (or roll of toilet paper) can be found [here](https://math.stackexchange.com/questions/1633704/the-length-of-toilet-roll). If you know the tape width (= spool height) you can calculate the total area and hence total bytes.
Comment: @Jens it isn't a spool, it is just a circle like a CD but it is made of tape instead of plastic.
Comment: OK, but then I don't understand how the 3D comes into it. Are there bits inside the disc as well as on the surface?
Comment: @Jens Imagine a cake, the first layer has cream, the second chocolate and the third jam, each layer has magnetic information on it, now if our cake is very thick and each layer is very thin we can store a lot of information,  if I use the above formula am I accounting for each layer or would I have to use a more 3D formula such as the volume of a sphere?
Answer: My understanding now is that you have a cylinder divided into layers and the surface of each layer has a fixed bit density of $a$. Assuming each layer has the same thickness $t$ and that the thickness of the disc is $T$, you will then have $N=\frac{T}{t}$ layers. If the radius of the cylinder is $r$, the total number of bits is $$B = N \cdot \pi \cdot r^2 \cdot a$$
From the info you gave, it is unclear to me what the thickness of the disc is (I assume the thickness of the "film" is the thickness of each layer).
Comment: It's 0.003 inches thick so it wouldn't add very much to the surface area.
Comment: What's the thickness of each layer, then?
Comment: I'm actually not sure, I'm not even sure if it encodes in layers, I cannot find the answer to that question anywhere.


Only last wxStaticBitmap is showing

Question: The same image is meant to be shown in different locations but only the second one is shown, why?
void AppFrame::OnButtonClicked(wxCommandEvent& evt) {

    Tiles* knots = new Tiles(panel, 1);
    string tile = knots->firstTile();
    ImagePanel* drawPane = new ImagePanel(panel, tile, wxBITMAP_TYPE_PNG);

    wxStaticBitmap* image1 = new wxStaticBitmap(panel, wxID_ANY, drawPane->getImage(),wxPoint(Background::defaultStartX, Background::defaultStartY), wxSize(100, 100));

    wxStaticBitmap* image2 = new wxStaticBitmap(panel, wxID_ANY, drawPane->getImage(),wxPoint(Background::defaultStartX+100, Background::defaultStartY), wxSize(100, 100));

}

Comment: Read about sizers...
Answer: You don't position your ImagePanel and depending on its size it can overlap the first bitmap. Generally speaking, using hard-coded position in pixels is strongly discouraged, you should let the controls use their natural size and position them using sizers as already mentioned in a comment.

Only last wxStaticBitmap is showing


$injector:modulerr

Question: Recebo o seguinte erro:
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module contato due to:

Error: [$injector:nomod] Module 'contato' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.6/$injector/nomod?p0=contato

Código da minha página:

Answer: Pode ser duas coisas. 1: A função checkConnection(); não está definida e por isso quebra o restante do javascript. 2: faltou inserir o arquivo contatoController.js no seu html.
Comment: Removi a função e o  com a inclusão, e funcionou. Era uma função javascript normal, provavelmente por isso não funcionou

$injector:modulerr


How to apply mutliple rotate values for one image in imgaug? (Not randomly)

Question: from imgaug import augmenters as iaa
from imgaug import parameters as iap

import cv2

aug=iaa.Affine(rotate=iap.DeterministicList([90,180,270]))

imglist = []

img = cv2.imread('i/1.jpg')

imglist.append(img)

images_aug = aug.augment_images(imglist)

cv2.imwrite('i/new.jpg', images_aug[0])

I have this code and want to apply my 3 rotation values(90,180,270) to an image. so my output should be 3 images(rotated with 90,180,270 angles versions of an image) but when I use this code, it assigns a random rotate value and gives me one rotated image.
Answer: This does what you want:
from imgaug import augmenters as iaa
from imgaug import parameters as iap
import cv2

rotations = [90,180,270]
aug = iaa.Affine(rotate=iap.DeterministicList(rotations))
img = cv2.imread('i/1.jpg')
imglist = [img for i in range(len(rotations))]
images_aug = aug.augment_images(imglist)
for i in range(len(rotations)):
    cv2.imwrite('i/new_{}.jpg'.format(rotations[i]), images_aug[i])

The changes are:

We have an array of rotations, which is used throughout the code. This just helps to shorten the subsequent code.
We add enough imgs to imglist to cover every rotation.
We output each image from images_aug.

End result:


PowerSchool Python Queries

Question: I have successfully set up the plugin I need in PowerSchool to query tables via Python as follows. I looked at the examples in the PowerSchool library documentation, but cannot successfully query a specific table (while applying any filters) with the same approaches. I can only get the entire table (when using the SQL query) or "HTTPError: 400 Client Error: Bad Request for url: ..." (when using params).
import powerschool
import pandas as pd

client_id =  'client id goes here'
client_secret = 'client secret goes here'
my_credentials = (client_id, client_secret)
host_name = 'host name goes here'
ps = powerschool.PowerSchool(host=host_name, auth=my_credentials)
st = ps.get_schema_table('students')

# I have tried each of these and they all return the entire table
sql = '''SELECT * FROM STUDENTS WHERE last_name IN ('SMITH', 'JOHNSON')'''
params = {'last_name':'SMITH',
          'projection':'last_name'}

stData = st.query(**params)
df = pd.DataFrame.from_dict(stData)

stData2 = st.query(body=sql)
df = pd.DataFrame.from_dict(stData2)

Thanks in advance!
Answer: The docs you linked give this example:
params = {
    'q': 'id=ge=10000',
    'projection': 'school_number,abbreviation',
}
schools_table.query(**params)

Your code does:
params = {'last_name':'SMITH',
          'projection':'last_name'}

stData = st.query(**params)
df = pd.DataFrame.from_dict(stData)

It seems to me that 'last_name':'SMITH' should be something closer to 'q': 'id=ge=10000'. I don't know PowerSchool but maybe 'q': 'last_name=SMITH'?
Comment: `'q': 'last_name=eq=SMITH'`?

PowerSchool Python Queries


Different actions using same REST calls

Question: I am building an application which has same functionalities both from AWS and Google Cloud. For example Creating an instance , Launching instance from Machine ID, Creating snapshot, Liting all Instances,etc. Which I called using REST calls.
For example:
<form method="post" action="rest/create/new" class="form-inline">
            User Name <input type="text" id="user"
                name="user" class="form-control" size="50"
                placeholder="Enter Username">
            <button type="submit" class="btn btn-info">Start New Machine</button>
        </form>
        <form method="post" action="rest/launch/start" class="form-inline">
            Launch Existing Machine
 <input
                type="text" id="AMId" name="AMId" class="form-control" size="50"
                placeholder="Enter Instance ID">
            <button type="submit" class="btn btn-info">Launch</button>

        </form>

        <form method="get" action="rest/create/listAll" class="form-inline">
            Show All EC2 Instances

            <button type="submit" class="btn btn-info btn-lg">Show All</button>
        </form>

        <form method="post" **action="rest/create/listRunning"**>
            Show All Running EC2 Instances

            <button type="submit" class="btn btn-info">Show All Running</button>
        </form>

        <form method="post" action="rest/create/terminate" class="form-inline">
            Enter Instance ID
 <input
                type="text" id="terminateID" name="terminateID" class="form-control"
                size="50" placeholder="Enter Machine ID">
            <button type="submit" class="btn btn-info">Terminate</button>
        </form>

And I am catching these rest calls in classes.
For example,
@GET
    @Path("/listAll")
    public Response getAllAvailableImages(@Context ServletContext context)

Now what I want is how can I use both AWS and google cloud features, using these same calls or some other method,depending on requirement or choice?
Answer: How about:
GET /{provider}/images
POST /{provider}/images/{imageID}/start

where the variables in braces are placeholders for path parameters:
{provider} may resolve to AWS, Google or another provider
{imageID} references a unique image ID
Examples:
GET /AWS/images   (gets all AWS images)
POST /GoogleCloud/images  (creates new Google Cloud image)
POST /OpenStack/images/gfhdh45ff4/terminate  (terminates a specific image)

If you are using Spring MVC for REST, the controller could look like:
@RestController
public class ImageController {

    @Autowired
    private ImageService imageService;

    @RequestMapping(value = "/{provider}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public List<Image> getImages(@PathVariable String provider) {
        return imageService.getImagesByProvider(provider);
    }

    @RequestMapping(value = "/{provider}", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public Image createNewImage(@PathVariable String provider, @RequestBody Image image) {
        return imageService.createImageForProvider(provider, image);
    }

    @RequestMapping(value = "/{provider}/images/{imageId}/start", method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void startImageAtProvider(@PathVariable String provider, @PathVariable String imageId) {
        return imageService.startImageAtProvider(provider, imageId);
    }

}

The HTTP method for starting the image could be POST - and should be if starting an image is not idempotent. But I am assuming hat attempting to start an image which is already running will just be ignored.
Extra edit:
If the image IDs are unique across ALL providers, you could shorten the REST URLs regarding images:
POST /images/gfhdh45ff4/terminate  (terminates a specific image)

Comment: I have explained the placeholders and added a Spring MVC example.
Comment: Yes - Jersey looks a bit different, with the annotations Get and Path - but placeholders are the same - so the changes are not in the internals of the methods, but only in the annotations.
Comment: What do we call them (the braces {}), can you give me a link that can explain it in details?
Comment: It explains alot. But can you tell me , what if both are of type POST(i.e getImages and createNewImage)?
Comment: POST is fine - and I actually think most people would use POST and not PUT for an 'operation' on a resource. My view is that I like to signal whether a operation is idempotent (like GET and PUT must be) or not (like when creating a new resource via POST)
Comment: Thanks alot! Any changes if I am using Jersey as my framework?

Different actions using same REST calls


non parametric test to detect price discrimination

Question: Let us say that I have these columns for a product:

Day
Price
Channel of sale (e.g. web or snail mail)
Number of sales

Looking at the distribution, they can be bi modal as products can be on sale/promo or not.
Let us say there are only 2 channels. Is it possible to test for the null hypothesis that prices are on average (median?) not different for both segments? Can I use a Wilcoxon test (paired?) for this. Any input would be very much appreciated. Thanks!
Answer: It's not clear how you would try to pair observations.
You could use Wilcoxon-Mann-Whitney to compare Price across the two Channels. However, be aware that WMW (and other rank-based tests) typically do not test hypotheses about the mean or median.
It may be better to try to compose a more complex model that includes Day as a blocking variable.
Also, if Sale/Not_sale is the variable causing the bi-modal distribution, including this in your model may bring the residuals of the model to a normal-ish distribution.
I assume Number_of_sales would be considered a separate dependent variable, but it could also be included in the model as an independent variable if that makes sense.


Getting form Array from a webform created with Webform module?

Question: Is it possible to easily get the form Array from a webform created with Webform module?
I want to be able to call a copy of the form elsewhere
thanks
Answer: First off you'll need to know the form_id. You can get this a million ways but the 2 I use frequently are using the devel module that has the dpm() function to display any variable you want to the screen. So in a hook_form_alter you can put dpm($form_id) and get it that way. Another way is to just view the source and find the opening form tag. The id is in there as well.
Once you have the form id you can use drupal_get_form($form_id) to get the form array.
Comment: For forms created with the Webform module, `$form_id` will be like `webform_client_form_NODE_ID`, so if you have the nid of your webform's node handy you're all set.


Consulta MySQL excluindo LINHAS vazias

Question: tenho que fazer uma consulta (que será levada a uma aplicação PHP) na tabela abaixo. Gostaria de realizar a consulta de modo que não fossem selecionadas as linhas que não contenham preços (ou seja que são null) nas colunas 'gnbr' até a 'sprd'. Não quero excluir as linhas que estão em branco (pois se amanha precisar cadastrar preços nelas, precisaria digitar novamente o cod, prod, fab, qtd e carac.) apenas quero fazer a consulta de modo que o result set a ser enviado pro php nao receba essas linhas. a quantidade de linhas é variável (sempre haverá cadastro de coisas novas) portanto não posso fazer 'WHERE cod = xxxx;' por exemplo. alguem pode dar um norte, pelo menos??
grato.
Comment: Faça gnbr is not null e assim sucessivamente
Comment: as linhas mostradas seriam: cod 7100,7210,7211 e 7212. As linhas ignoradas seriam: cod 7101, 7300,71000 e 72000. Os nomes das colunas são abreviações de supermercados da região. @VirgilioNovic
Comment: No caso acima quais linhas seriam mostradas? coloque um exemplo ou pelo menos fale o cod de tal por exemplo iria aparecer!?
Comment: Pense também em rever o modelo , nome de colunas ininteligéveis , estrutura sem normalização , um novo tipo de preço demanda uma nova coluna.
Answer: Boa tarde.
Você precisa indicar a condição no WHERE. Pode ser feito da seguinte forma:
SELECT * FROM produtos WHERE gnbr IS NOT NULL AND sprd IS NOT NULL.

Você precisa adicionar manualmente cada elemento com "AND {nome_do_campo} IS NOT NULL".
Answer: Se quiser verificar se a linha tem pelo menos um NULL, você pode somar todas as colunas numéricas em questão e excluir as linhas em que essa soma for NULL:
WHERE (gnbr + vnse + ... + sprd) IS NOT NULL

Ou:
WHERE NOT ISNULL(gnbr + vnse + ... + sprd)

Não sei sobre a eficiência dessas variações. A soma das colunas certamente tem um "peso" sobre a consulta, sugiro analisar um EXPLAIN dela.
Se quiser eliminar só as linhas onde todas as colunas forem NULL, pode usar isto:
WHERE COALESCE(gnbr, vnse, ... , sprd) IS NOT NULL

O COALESCE funciona estabelecendo uma cadeia de fallbacks. O resultado só será NULL se todas as colunas estiverem nulas.

Consulta MySQL excluindo LINHAS vazias


/p cmd option is resolved as a drive letter in git-bash

Question: I used to call this command to popup a simple balloon message when gradle build is complete. It had worked fine on cygwin's bash.
notifu /p "Gradle build complete" /m "Now you can take a look at the results" /d 0 > /dev/null

However, after switching to git's bash, the windows-style command line options such as /p /m have become resolved as cygwin drive letters: p:/ m:/. Obviously, notifu couldn't accept them.

Could anybody please tell me why it had been perfectly working on cygwin's bash, but not on git-bash now?
Answer: @astrounaut use like this in git-bash:
notifu //p "title" //m "message.."

Answer: I used previously (in here) or seen (in that answer) the escape character '^' for Cygwin msys bash.
Try a ^ in front of the /, in order to convince Cygwin that /p isn't a drive path:
notifu ^/p "Gradle build complete" ^/m "Now you can take a look at the results" ^/d 0 > /dev/null


Why does the following code give different answers?

Question: I have the following code.
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  time_t t2 = rawtime;
  if(rawtime == t2) printf("Hi %ul %ul\n", rawtime, t2);

  return(0);
}

When this code is run, the printf gives different answers for rawtime and t2. Why is that? Could somebody please help?
Comment: You are accessing uninitialized variables. That is undefined behavior.
Comment: You are basically asking why `int a; printf("%d", a)` is different every time.
Comment: Did you mean the result is different in different execution? Or in 1 execution rawtime & t2 is different?
Comment: Yes. My question is why rawtime not equal to t2. I am not asking why it is different in different executions. I am especially confused because the condition "(rawtime == t2)" is true.
Comment: @anupamb In that case, it should be the same, I can't think why not.
Comment: @anupamb Your code has a bug that causes it not to do what you expect. Fix the bug and they mystery will go away.
Comment: It's not. That's the problem. I am using Visual Studio 2010, if that matters.
Comment: Your question is basically "why should two variables that both hold a value that was never initialized not compare as equal". And the answer is simply that there's no reason why they should, so any result is reasonable.
Comment: @David Schwartz Is the bug in the printf part?
Comment: @anupamb It's everywhere. Yes, it's in `printf` too because that reads variables whose value has not been initialized.
Comment: @David Schwartz I thought it gets initialized to some unknow value (not in the hands of the programmer). But whatever that value is, it should remain so, when the variable is assigned to another. Isn't that correct?
Comment: If it is unknown, how can you expect it to not be same? It can be same, or not same, or in a quantum state being same and not same at the same time. :)
Comment: @anupamb Short answer: No, but for very complex reasons. If you don't want to understand register caching and trap representations, just think of it as really being uninitialized. See my answer.
Comment: @anupamb On linux, with gcc, each time run your code, the result is the same. But u are using windows, I think there are implementation differences.
Answer: You are accessing uninitialized variables. That is undefined behavior.

why it is different in different executions. I am especially confused because the condition "(rawtime == t2)" is true.
There is not any question of why, when there is an undefined behavior being invoked. The variables have been declared and are thus having a place in the memory. That place could contain garbage value from previous program execution, or any other value. It might also happen that the values somehow, by some co-incident are same for those 2 variables, so your if() condition is coming as True.
But all these things on one side, one cannot question the flow of a program or statement when it is invoking undefined behavior, because to question is to query in the standards, and when the standard itself does not define it, where will anyone get an explanation from.
Answer: Here's why they don't compare as equal:

rawtime is not initialized.
Either t2 is initialized or it is not.
If t2 is initialized, then we are comparing an initialized value to an uninitialized value. There's no reason to expect these to compare as equal.
If t2 is uninitialized, we are comparing two uninitialized variables. There's no reason to expect these to compare as equal
So either way, there's no reason to expect these to compare as equal.

To expect them to compare as equal, you have to invent some odd state for t2 to be in that's, I don't even know what, initialized to an unspecified value? Uninitialized but guaranteed to compare equal to another uninitialized value? Or what?
Whatever thought process lead you to expect these to compare as equal, it is incomprehensible to me.
By the way, trying to glean this from the C standard is extremely difficult. It comes from a very obscure rule -- "If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined."
It's much easier to just understand that it really is uninitialized than to try to understand the complex rules for when it's guaranteed to have an unspecified value and when it's not. You have to learn about trap representations and other complexity.
Comment: Thanks for the answer. I am trying to look into this problem from a memory perspective too. The variable is already allocated a memory address (which is not changing). So I believe the 32 (or 64 bits) in that location are something (although uninitialized). I may be wrong in assuming that the '=' is doing some bit-level assignment to another variable (here t2), but that may be a naive mistake. I will try to have a better understanding of uninitialized variable. Thanks!
Comment: @anupamb Why do you say it's allocated a memory address? It never has a value assigned and its address is never taken. So when do you think it's assigned an address?! What operation do you think takes place that requires it to be assigned a memory address as opposed to, for example, being kept in a register for its entire life?
Comment: That's correct. My supposition is not necessarily correct. But I am guessing whether or not it's allocated memory (when just declared) is a compiler thing.
Comment: @anupamb: On a conventional machine, your suppositions are basically correct.  On a conventional machine, "uninitialzed" means "unpredictable, essentially random, might change from run to run, can't depend on it".  But it does not typically mean that the uninitialized value cannot even be inspected or copied.  David Schwartz's answers, though theoretically correct, refer to the abstract language of the C standard and to unusual concepts such as "trap representations" which are almost certainly not a factor on the machine you're using today.
Comment: @SteveSummit The thing is, he is specifically asking about a case where the atypical behavior is observed. So your choices are to either understand the unusual concepts to make sense of the C standard language or use common sense reasoning about a purely abstract machine.
Comment: @DavidSchwartz Unless it's just a `%ul` vs. `%lu` problem.
Answer: On the one hand, yes, since rawtime is uninitialized, the behavior is undefined, and all bets are off.  Demons could fly out of your computer's nose, for all the Standard cares.
But on the other hand, rawtime is just an integer.  Maybe 64 bits, probably 32 bits.  There are either 232 or 264 ordinary values.  There are no trap representations (on any computer you are at all likely to be using.)  So whatever random value starts out in rawtime gets copied to t2.  So they pretty much have to compare equal, so printf pretty much has to be called.  All right so far.
So if printf gets called on account of rawtime and t2 being equal, how could they print as unequal?  Probably because you accidentally used %ul instead of %lu.  Your two format specifiers might be printing the top and bottom halves of rawtime (which are probably unequal) and not printing t2 at all.  Try changing %ul to %lu and see what happens.
[Disclaimer.  This has been a real-world answer, not a Standard-thumping answer.  If you look only at the Standard, it is indeed meaningless to ask what a program does after its behavior has become undefined.  And there are now compilers that will let themselves do some pretty bizarre things when your program is undefined and they're allowed to.  It's very hard to imagine that a compiler would emit code which (a) copied a bit pattern but then either (b1) compared it unequal or (b2) compared it equal but printed it unequal, but it's not completely out of the question.)
Comment: Thanks for the answer. This helps. Yes changing the format specifier changed things, but it wasn't lu that gave the right answer, it was lld. Thanks!


Android Dagger-2 how to provide the dependency for method parameters

Question: I have a module FragmentModule
@Module
public class FragmentModule
{
    @Provides
    public static PickerDashboardFragment providesPickerDashboard(int status, String name, Object someComplexObject)
    {
        PickerDashboardFragment fragment = new PickerDashboardFragment();
        Bundle b = new Bundle();
        b.putInt("status", status);
        b.putString("name", name);
        b.putInt("object", someComplexObject);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Provides
    public static PickingFragment providesPickingFragment()
    {
        PickingFragment fragment = new PickingFragment();
        return fragment;
    }
}

Here's my Component class
@Component(modules = {UtilModule.class, FragmentModule.class})
public interface ApplicationComponent
{
    void inject(PickerDashboardActivity target);
}

In my activity this is how i'm injecting the PickerDashboardActivity
@Inject
PickerDashboardFragment frag;

ApplicationComponent component = DaggerApplicationComponent.builder().build();
        component.inject(this);

My question is what's the best and easiest way to provide the dependencies for PickerDashboardFragment providesPickerDashboard(int status, String name, Object someComplexObject) i.e status, name and someComplexObject.
Best Regards
Comment: Any one else want to answer?
Answer: Add attributes and Provides methods to your module like this:
@Module
public class FragmentModule
{

    private final int status;
    private final String name;
    private final Object someComplexObject;

    public FragmentModule(int status, String name, Object someComplexObject) {
        this.status = status;
        this.name = name;
        this.someComplexObject = someComplexObject;
    }

    @Provides
    int providesStatus() {
        return status;
    }

    @Provides
    String providesName() {
        return name;
    }

    @Provides
    Object providesSomeComplexObject() {
        return someComplexObjext;
    }

    @Provides
    public static PickerDashboardFragment providesPickerDashboard(int status, String name, Object someComplexObject)
    {
        PickerDashboardFragment fragment = new PickerDashboardFragment();
        Bundle b = new Bundle();
        b.putInt("status", status);
        b.putString("name", name);
        b.putInt("object", someComplexObject);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Provides
    public static PickingFragment providesPickingFragment()
    {
        PickingFragment fragment = new PickingFragment();
        return fragment;
    }
}

Having a module providing ints and Strings will probably make you use some qualifiers (such as Named) in order to avoid collisions
Comment: thanks for the answer and where did the values for name, status etc will come? In fragment module you didn't initialized them!
Comment: You can always remove the `@Provides` method and use attributes directly. Or use another `Module` to provide those method parameters dependency
Comment: My bad, I forgot the constructor. I've updated my answer
Comment: no worries. Your answer is correct but seems like a bit of overhead for us to do. Think about this module having more methods and every method with different arguments so i have to make more constructors and hence creating more boiler plate. I was think if that dependency could be full filled at the time of method invocation?
Comment: What if providesPickerDashboard required two string parameters? For example, string firstName, string lastName? How does dagger know whether to use String providesFirstName vs String providesLastName?
Comment: It doesn't know. You'll have to use [Qualifiers](https://google.github.io/dagger/users-guide.html#qualifiers)
Answer: Don't inject Fragments into your Activities using Dagger 2. Why? Fragments have a lifecycle controlled by the Android OS. When you add a Fragment to an Activity using a transaction, the FragmentManager will retain a reference to the Fragment. When the Activity instanceState is saved, the Fragments added to FragmentManager will be saved. When the Activity is restored, if you request injection without checking for the presence of the Fragment in the FragmentManager, your Activity begin to reference two instances of the Fragment and create a memory leak.
For this reason, in void onCreate(Bundle savedInstanceState) method you should check for the presence of the retained Fragment in the FragmentManager rather than request injection from Dagger 2. If the Fragment is not retained then you can instantiate it at that point. It is perfectly fine to use the new keyword or static factories for this.
Example:
MyFragment frag;

void onCreate(Bundle savedInstanceState) {
     setContentView(R.layout.content);
     frag = fragmentManager.findFragmentByTag(MyFragment.TAG);
     if (frag == null) {
         frag = MyFragment.instantiate(new Bundle());
     }
}

However, at another level it seems you are asking how to combine parameters and dependencies. A good solution for these is often Factories. Say you have a CoffeeMaker:
class CoffeeMaker {

    private final Kettle kettle;
    private final Grinder grinder;
    private final BeanFlavour beanFlavour;

    CoffeeMaker(Kettle kettle, Grinder grinder, BeanFlavour beanFlavour) {
        this.kettle = kettle;
        this.grinder = grinder;
        this.beanFlavour = beanFlavour;
    }
}

The beanFlavour is variable (dark, roasted etc.) and varies and so is more like a parameter than a dependency. You could then write a CoffeeMakerFactory and inject this using Dagger 2:
 class CoffeeMakerFactory {

     private final Kettle kettle;
     private final Grinder grinder;

     @Inject
     CoffeeMakerFactory(Kettle kettle, Grinder grinder) {
         this.kettle = kettle;
         this.grinder = grinder;
     }

     public CoffeeMaker create(BeanFlavour beanFlavour) {
         return new CoffeeMaker(kettle, grinder, beanFlavour);
     }
 }

Factories are the standard solution for a combination of dependency and parameters see here and they can even be be generated using code generation tools like Google Auto.
Comment: Can you please provide any reference to this i mean not to inject fragments!
Comment: @ecDroid Please look at the Google sample project https://github.com/googlesamples/android-architecture
Comment: Thanks David, i think you are right. I'll change my implementation to not inject fragments. Please tell me what other components i shouldn't inject with dagger?
Comment: Accepted your suggestion and changed my implementation. Thanks


Printing fields in theme: Undefined index: safe_value

Question: I want to print my fields in tpl.php files as cleanly as possible. To do this, I have used the following code in my template.php file:
function print_field($field_name, $format = 'safe_value') {

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

$field= field_get_items('node', $node, $field_name);

if ($format == 'url') {
    print file_create_url($field[0]['uri']);
} else {
print $field[0]["$format"];
}
}

Now, I can print my fields in my tpl.php file in a clean manner, without any unnecessary mark-up or labels:
<?php print_field('field_section') ?> -- Prints the field with safe formating
<?php print_field('field_title', 'value') ?>  -- Prints the field in Raw
<?php print_field('field_intro_image', 'url') ?> -- Prints the image url of a field
It all works fine, but I get this error message:

Notice: Undefined index: safe_value in print_field() (line 19 of template.php).

How I can resolve this?
Also, is it possible to just enter value or url in my tpl.php file without wrapping them in quote marks?
Answer: The problem is with your function, not the template.
Ideally you should check if the index exists, e.g.
print array_key_exists($format, $field[0]) ? $field[0]["$format"] : '';

or:
print !empty($field[0]["$format"]) ? $field[0]["$format"] : '';

or:
print @$field[0]["$format"] ? $field[0]["$format"] : '';

Alternatively you can ignore the notices in PHP config (php.ini) or in Drupal admin.
Or you can just prefix the field with @ to silence/suppress any errors (usually not recommended), e.g.
print @$field[0]["$format"];

Answer: Have you seen field_view_value() which already does what you're attempting, i.e. getting the value of a field without additional markup.
e.g.
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

(For reference taken from: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way which is well worth a read.)
Comment: I have read that link, but as I understand it (any my understanding could be wrong!!) that requires two lines of code in the tpl.php file. I would like it to be as cleanly as possible, as I want my tpl.php files to be easy to read!
Comment: I understand, I was suggesting you place that in your function.  Generally I find that there are a slew of advantages to using the Drupal API compared to using your own functions, security, portability, compatibility etc.  Once you start using it you start seeing how it all fits together and why, which often isn't obvious.  Like in this case you wouldn't have to worry if there isn't a `safe_value`, the best fit would be auto magically produced for you.


How can I split an ArrayList of type string into 5 different subArrays without using guava or any external Library?

Question: Currently the code I have adds a set of attributes into the list below, and returns one giant ArrayList with 70 attributes. I'd like those 70 attributes split into 5 Arrays that represent the 5 columns of the dataset - so I can more easily visualise and then compare the data repetition inside each.
I cannot use an external library like guava since its for an assignment so I can't add any extra files into the project.
I found methods that only work to partition byte lists, and a List<> generic method which I could not make work.
Any suggestions? I know this should be so simple but I cannot find the solution
ArrayList<String> allRows = new ArrayList<String>();

        for (int ex = 1; ex < dataExamples; ex++) {
            for( int ats = 0; ats < dataAttributes; ats++){

                allRows(data[ex][ats]);

                        }
                }
        System.out.println(allRows);

Comment: Why don't you build an object with the correlated values, instead of arranging them as flying values correlated with some other data structures? Something like: `Example { row1, row2, row3 ... rowN }` — eventually, `rowX` is a meaningful name, I just used them because I don't know what your column names may look like. Then you can make an array of `Example` and you have everything packed up ready for (almost) anything...
Answer: This is a simple problem of iterating through the data in the correct manner.
I am unsure if you want Horizontal insertion into the 2d array or vertical insertion. So I've added both, just uncomment the one you want.
// Create fake data
ArrayList<Integer> allRows = new ArrayList<Integer>();
for (int i = 0; i < 70; i++)
  allRows.add(i);

System.out.printf("All Data: %s%n", allRows.toString());

// Create 2 Dementional Array
ArrayList<ArrayList<Integer>> twoDRows = new ArrayList<ArrayList<Integer>>();
// Add the 5 rows
for (int i = 0; i < 5; i++)
    twoDRows.add(new ArrayList<Integer>());

// Split allRows
for (int i = 0; i<allRows.size(); i++) {
  int rowToAddTo;

  // Horizontal
  rowToAddTo = i/(allRows.size()/twoDRows.size());

  // Vertical
  rowToAddTo = i%twoDRows.size();

  twoDRows.get(rowToAddTo).add(allRows.get(i));
}

// Pretty-ish print
for (ArrayList<Integer> array:twoDRows)
  System.out.println(array);

Comment: Brilliant Aaron, I just changed the types to String and that seemed to do it! Cheers
Comment: good, its the same as what I answered, use the mod operation and determine which array to use
Answer: Assuming your array contains your column elements evenly distributed (that is elements 0,5,10,... belong to the same column; 1,6,11,.. to another column, etc.) you can use the mod operation (%) to separate those elements, something like this:
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

//populate listOfLists
for(int i = 0; i < numberOfColumns; i++){
    listOfLists.add(new ArrayList<String>());
}

for(int index = 0; index < totalElements; index++){
    //Obtain number of correponding column with mod
    int remainder = index % numberOfColumns;

    //Insert your element into that corresponding array in listOfLists
    listOfLists.get(remainder).add("YOUR ELEMENT");
}

Notice that numberOfColumns is the total number of columns you have, being it 5 or something else.
You may also want to check this answer regarding the sublist() method. Which seems to be also similar to your question.
Cheers
EDIT
Changed the code so it will match any number of columns and add your element to the corresponding array.
Comment: In that case you should check the question I linked in the answer, regarding the `sublist()` method. Either that, or make an `ArrayList>` with `columnNr` elements, each one corresponding to a column and use the **mod** operator to determine to which element of your Array of Arrays it corresponds.
Comment: Thanks GrayCygnus - but the problem is that the data i'm reading is always changing - I have a variable that stores how many columns there are in the file that the algorithm is reading (right now there are 5 for the dataset I am reading) so I want to split the data for the same amount of columns there are: ex while(ArrayNumber < columnNr) : create new sub array, with the size of columnNr
Comment: I modified my answer to reflect what I am saying


With several user profile pages built in Views as tabs, how do I build a menu linking to those pages?

Question: I can't just use the menu UI to create menu links because the links need to be dynamic. The best solution I have found so far is in OpenAtrium. Are there any others?
<code>   $block['content'] .= "<h3>". t('My account') ."</h3>". theme('links',
atrium_account_links());
</code>
and
<code>/**
 * Generates an array of account links suitable for use in theme_links().
 */
function atrium_account_links() {
  global $user;
  $links = array();

  // @TODO: If menu.inc had a real API function for this we would use it, but
  // as of now we'd have a copy hand paste hack job of menu_local_tasks()...
  $paths = array(
    "user/{$user->uid}" => t('Profile'),
    "user/{$user->uid}/dashboard" => '',
    "user/{$user->uid}/edit" => '',
    "user/{$user->uid}/notifications" => '',
    'logout' => '',
  );
  foreach ($paths as $path => $title) {
    $item = menu_get_item($path);
    if ($item && $item['access']) {
      $links[] = array(
        'title' => !empty($title) ? $title : $item['title'],
        'href' => $item['href'],
      );
    }
  }
  drupal_alter('atrium_account_links', $links);
  return $links;
}
</code>
Comment: Can't you just create the menus in the views?
Comment: Yes, I did and they are primary and secondary tabs. However, the four major ones that user should have access to at all times also need a menu block. I don't think that making two views with the same path but two different menus work.
Answer: I went ahead and implemented the OpenAtrium code in Drupal 7 which I'll use unless somebody comes up with a better answer.
<code>/**
* implements hook_block_info()
*/
function helper_block_info () {
  $blocks['helper_user_links'] = array(
    'info' => t('Menu user links'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/**
* implements hook_block_view()
*/
function helper_block_view($delta = ''){
  $block = array();

    case 'helper_user_links':
      $block['subject'] = NULL;
      $block['content'] = array(
        '#markup' => theme('links', array(
          'links' => helper_user_links(),
          'attributes' => array('class' => 'menu'),
        )),
      );
    break;
  }

  return $block;
}

/**
 * Generates an array of account links suitable for use in theme_links().
 */
function helper_user_links() {
  global $user;
  $links = array();

  // @TODO: If menu.inc had a real API function for this we would use it, but
  // as of now we'd have a copy hand paste hack job of menu_local_tasks()...
  $paths = array(
    "user/{$user->uid}/businesses/reviews" => '',
    "user/{$user->uid}/content" => '',
    "user/{$user->uid}/workbench" => '',
    'logout' => '',
  );
  foreach ($paths as $path => $title) {
    $item = menu_get_item($path);
    if ($item && $item['access']) {
      $links[] = array(
        'title' => !empty($title) ? $title : $item['title'],
        'href' => $item['href'],
        'class' => $_GET['q'] == $item['path'] ? 'leaf active-trail active' : 'leaf',
      );
    }
  }
  drupal_alter('helper_user_links', $links);
  return $links;
}
</code>


Meaning of Capitalization on The Notation of Gregorian Psalm Tone Endings

Question: As you know, most Gregorian Psalm Tones have alternative endings. For example, Tone I has 10 possible endings.

The endings are denoted by a letter and a number. I understand (correct me if I am wrong) that the letter itself indicates the degree (on the scale) of the last note of the ending. For example, all the "D" endings end in D while all the "g" endings end in G. The number is just a sequential to differentiate between all the possible endings that end on the same note.
Is there any logic, though, behind capitalizing some of these letters? For example:

why is a capital D used for the "D" endings of Tone I while a lower case g is used for the "G" endings?
why is a capital A used for the "A" endings of Tone IV while a lower case a is used for the "A" endings of Tone VII?

I apologize if I am misusing a technical term. I am not a musician or a musicologist.
Thanks!
Answer:
Formulas for terminations: The different intonations of the antiphons have given place to the diverse final cadences in each mode, in order to facilitate the intonation of the antiphon, when psalm ends.
The termination of each particular case is indicated in two ways:
a) placing next to the modal number of the antiphon a letter that indicates the final note of the termination: A, B, C, E, F, G
     8c
Uppercase letters are used when the last note of the termination is at the same time the final in the mode; otherwise lower-cases are used.
When several terminations have the same end, the letters take, in their right superior part, indexes that distinguish them: g, g2, g3, g4.

GREGORIAN CHANT PSALMODY, Schola Cantorum Bogotensis

Liber Usualis (p112 - 118)


Infinite discounted sum of betas

Question: Let $0 \leq \gamma < 1$, $X_i \sim \text{Beta}(\alpha, \beta)$, and
$$Y \sim \sum_{i = 0}^\infty \gamma^i X_i$$
What is the distribution of $Y$? Does it have a closed form? Can it be sampled efficiently? We know that
\begin{align}
\operatorname{supp}(Y) &= \left[0, \frac{1}{1-\gamma}\right) \\
\operatorname{E}(Y) &= \frac{\operatorname{E}(X)}{1-\gamma} \\
\operatorname{Var}(Y) &= \frac{\operatorname{Var}(X)}{1-\gamma^2} \\
\end{align}
Also, note that
\begin{align}
Y = X + \gamma Y'
\end{align}
where $Y$ and $Y'$ have the same distribution. Therefore, denoting the characteristic function of a random variable $A$ as $\phi_A$,
\begin{align}
\phi_Y(t)
&= \phi_{X + \gamma Y'}(t) \\
&= (\phi_X \cdot \phi_{\gamma Y'})(t) \\
&= \phi_X(t) \cdot \phi_{\gamma Y'}(t) \\
&= \phi_X(t) \cdot \phi_{Y'}(\gamma t) \\
&= \phi_X(t) \cdot \phi_Y(\gamma t) \\
\frac{\phi_Y(t)}{\phi_Y(\gamma t)} &= \phi_X(t) \\
&= {}_1F_1(\alpha; \alpha + \beta; i t)
\end{align}
where the last RHS is the characteristic function of the beta distribution. Is there a way to solve for $\phi_Y(t)$ or at least sample efficiently from $Y$'s distribution?
Comment: This is another case of the situation considered by Vincent Granville at https://stats.stackexchange.com/questions/432136.  The connection is this: let $\phi:\mathbb{R}_{+}\to\mathbb{R}_{+}$ be $\phi(x)=\sqrt{x+1}-1$ for him and $\phi(x)=\gamma x$ for you, so that in both cases $0$ is the sole attractor of $\phi.$ Take a sequence of iid positive random variables $X_1,X_2,X_3,\ldots$ and consider the distribution of $\phi(X_1+\phi(X_2+\phi(X_3+\cdots))).$ These two situations are thereby quite alike, indicating an analysis of one will suggest an effective analysis of the other.
Comment: I noticed, thanks.  I had also worked out the relationship between the cfs, but stopped there because it doesn't appear to get us any closer to a solution.  You could pursue it a little further to deduce the cumulants of $Y$--but then, when you explore the possibility of writing a closed formula even for the cumulants of a Beta distribution, you realize that's not going to be useful either.
Answer: Note
I've used slightly different notation to you.
Firstly, let's consider the underlying random variables we are dealing with. We have that all
$$X_{i}\sim\text{Beta}(\alpha,\beta)$$
where all random variables are independent of each other. If we now consider some scaled form of these random variables:
$$Y=a X$$
where we have that $a<1$ because $\gamma<1$. Now, for a continuous random variable
$$\begin{align}
f_{Y}(y)&=\frac{f_{X}(y/a)}{a}\\
&=\frac{(y/a)^{\alpha-1}(1-y/a)^{\beta-1}}{a\cdot\text{B}(\alpha,\beta)}
\end{align}$$
Notice that the support has changed from
$$0<x<1$$
to
$$0<y<a$$
If we define
$$\text{B}'(\alpha,\beta,a)=\int_{0}^{a}t^{\alpha-1}(a-t)^{\beta-1}\,dt$$
as a variant on the usual Beta function (this function equals the Beta function for $a=1$), then we can show that
$$\text{B}'(\alpha,\beta,a)=a^{\alpha+\beta-1}\cdot\text{B}(\alpha,\beta)$$
This means that
$$\begin{align}
f_{Y}(y)&=\frac{(y/a)^{\alpha-1}(1-y/a)^{\beta-1}}{a\cdot\text{B}(\alpha,\beta)}\\
&=\frac{y^{\alpha-1}(a-y)^{\beta-1}}{\text{B}'(\alpha,\beta,a)}\cdot\frac{\text{B}'(\alpha,\beta,a)}{a^{\alpha+\beta-1}\cdot\text{B}(\alpha,\beta)}\\
&=\frac{y^{\alpha-1}(a-y)^{\beta-1}}{\text{B}'(\alpha,\beta,a)}
\end{align}$$
For the purposes of this answer, let's denote this random variable as
$$Y\sim\text{Beta}'(\alpha,\beta,a)$$
This is essentially a scaled Beta distribution, where the support has been limited to $[0,a]$. The important point here is that random values generated from this random variable will be bound between $[0,a]$.
Now, in your summation, each Beta distribution $X_{i}$ is scaled by $\gamma^{i}$ for increasing $i$. This means that each summand will have an increasingly reduced support $[0,\gamma^{i}]$ and each subsequent summand's probability mass will be increasingly narrow.
We know this series will converge for $0\leq\gamma<1$ because, for each $i$, the maximum value that each subsequent random value can take is $\gamma^{i}$. So, at most, the series is
$$1+\gamma+\gamma^{2}+\gamma^{3}+\gamma^{4}+\ldots$$
which is a simple geometric series converging to
$$\frac{1}{1-\gamma}$$
Interestingly, this tells us the upper bound of the support of $Y$ for a given $\gamma$. If we define
$$Z=\sum_{i=0}^{\infty}Y_{i}$$
then the support for $Z$ would then be $[0,1/(1-\gamma)]$.
Now, you can derive the moment generating function of $Y$ as
$$M_{Y_{i}}(t)=1+\sum_{k=1}^{\infty}\Bigg(\prod_{r=0}^{k-1}\bigg(\frac{\alpha+r}{\alpha+\beta+r}\bigg)\frac{(\gamma^{i}\cdot t)^{k}}{k!}\Bigg)$$
Then the moment generating function of $Z$ is
$$\begin{align}
M_{Z}(t)&=\prod_{i=0}^{\infty}M_{Y_{i}}(t)\\
&=\Bigg[1+\sum_{k=1}^{\infty}\Bigg(\prod_{r=0}^{k-1}\bigg(\frac{\alpha+r}{\alpha+\beta+r}\bigg)\frac{t^{k}}{k!}\Bigg)\Bigg]\cdot \\
&\Bigg[1+\sum_{k=1}^{\infty}\Bigg(\prod_{r=0}^{k-1}\bigg(\frac{\alpha+r}{\alpha+\beta+r}\bigg)\frac{(\gamma\cdot t)^{k}}{k!}\Bigg)\Bigg]\cdots\\
\end{align}$$
I'm not sure how useful this is. But it's useful to note that for increasing $i$ the subsequent terms will decay in size so that $M_{Y_{i}}(t)\rightarrow 1$ for large $i$.
If we look at some simulations of this distribution, there are some interesting results. First we'll define some functions for $Y$.
<code>    dsbeta=function(x, alpha, beta, gamma) {
      x[x<0]=0
      x[x>gamma]=gamma
      return(x^(alpha-1)*(gamma-x)^(beta-1)/(gamma^(
                alpha+beta-1)*beta(alpha, beta)))
    }

    psbeta=function(q, alpha, beta, gamma) {
      q[q<0]=0
      q[q>gamma]=gamma
      return(pbeta(q/gamma, alpha, beta))
    }

    qsbeta=function(p, alpha, beta, gamma) {
      p[p<0]=0
      p[p>1]=1
      return(gamma*qbeta(p, alpha, beta))
    }

    rsbeta=function(n, alpha, beta, gamma) {
      return(gamma*rbeta(n, alpha, beta))
    }

    #Perform some simulations:
    a=3
    b=2
    gamma=0.2 #Scaling of each X
    N=10000   #Number of samples of Z
    M=100     #Number of Y in each Z

    #Generate random values of Z:
    r=as.vector(matrix(rbeta(N*M, a, b), N, M) %*%
                       gamma^seq(0,M-1))

    #Final simulations:
    hist(r, freq = FALSE, breaks = 50)

    #Perform fit (here we provide the upper bound gamma as the
    #             theoretical upper limit):
    f=fitdistrplus::fitdist(r, "sbeta", start = list(alpha = 2,
         beta = 3), fix.arg = list(gamma = 1/(1-gamma)))

    #Visualize the fit:
    x=seq(min(r), max(r), length.out = 1000)
    lines(x, dsbeta(x, f$estimate[1], f$estimate[2],
             1/(1-gamma)), lwd = 2, col = "blue")

    #GOF tests:
    ks.test(r, "psbeta", f$estimate[1], f$estimate[2],
               f$fix.arg$gamma)
    goftest::cvm.test(r, "psbeta", f$estimate[1], f$estimate[2],
                      f$fix.arg$gamma)$p.value
goftest::ad.test(r, "psbeta", f$estimate[1], f$estimate[2],
                    f$fix.arg$gamma)$p.value

    #qq plot:
    plot(sort(r), qsbeta(ppoints(length(r)), f$estimate[1],
     f$estimate[2], f$fix.arg$gamma), ylab = "Theoretical
         quantiles", xlab = "Empirical quantiles", col = "blue",
                     type = "l", lwd = 2)
    abline(0, 1, lty = 2, lwd = 2, col = "red")
</code>
It seems from the simulations that $Z$ can be well approximated by the scaled beta
$$Z\sim\text{Beta}'(\cdot,\cdot,1/(1-\gamma))$$
but as per @whuber's comments, for small $\alpha,\beta$ and $\gamma\rightarrow 0$ this breaks down. I think it has something to do with the bi-modality for $\alpha,\beta<1$ and the fewer 'non-degenerate' random variables due to $\gamma$ small.
Comment: I think you will get more insight into the underlying issues by considering cases where at least one of $\alpha,\beta$ is close to zero (preferably both).  This will more clearly show the limitations of approximating $Z$ as a scaled Beta distribution.  Focus on relatively small $\gamma,$ too: for large $\gamma \approx 1$ there's a CLT effect.
Comment: @whuber I'm only seeing a poor scaled Beta fit for $\alpha\approx\beta\approx 1$ and $\gamma\rightarrow 0$ where the simulated data looks quite uniform.
Comment: @whuber I wonder whether it can be proven that it approaches a scaled beta as $\gamma \rightarrow 1$ (or as $\alpha, \beta \rightarrow \infty$).
Comment: Under those conditions, properly standardized, the sum ought to approach a Normal distribution.

Infinite discounted sum of betas


Is it possible to open a link in Google chrome and Opera like safari in iOS from iOS Application

Question: I need a clarification that Is it possible to open a URL in Google Chrome and Opera browsers like Safari in iOS from iOS Application.
Anyone's  help will be deeply appreciated.
Comment: Um... Yes you can open links in any browser... Are you asking for an animation?
Comment: No I am not asking for animation. I want to know how to open the links in chrome and safari.
Comment: If we open a link in safari it open's into separate application in safari right? Like wise does the link opens into google chrome and  Opera?
Comment: Oh, then to answer your first request.  Possible dupe: http://stackoverflow.com/questions/2899699/uiwebview-open-links-in-safari
Comment: Hey sorry the link u provided is for safari. I want to know how to open the link in google chrome browser from our application
Comment: Not. Possible.  What would you open it in?  Opera and Google Chrome are against apple guidelines, and not even on the store.  Do you want to send this link to a computer and have it open there?  If so, that'll take some server-client action.
Answer: For Google Chrome you can look here for some example code from google showing how to load a URL in Chrome instead of Safari  https://developers.google.com/chrome/mobile/docs/ios-links
Opera supports the "ohttp" scheme so a similar thing can be done for that too.
Comment: Just FYI, this class is now included in the Google Open Source framework.  So if you already use that in your app, just `#import ` to get access to the `OpenInChromeController` class.
Comment: @orta Is it just me or is the link in this answer now dead?
Answer: Here is a URLOpener class to use,
Usage,
<code>NSString * url = @"http://www.apple.com";
NSString * userAgent = BROWSER_CHROME;
URLOpener * opener = [[URLOpener alloc] initWithURLString:url browser:userAgent];
[opener openURL];
</code>
    URLOpener.h
<code>#define BROWSER_CHROME  @"chrome"
#define BROWSER_OPERA   @"opera"

@interface URLOpener : NSObject

@property (nonatomic, retain) NSURL * url;
@property (nonatomic, retain) NSString * browser;

- (id) initWithURL:(NSURL *)u;
- (id) initWithBrowser:(NSString *)b;
- (id) initWithURL:(NSURL *)u browser:(NSString *)b;
- (id) initWithURLString:(NSString *)us browser:(NSString *)b;

- (BOOL)openURL;

@end
</code>
URLOpener.m
<code>#import "URLOpener.h"

@implementation URLOpener

@synthesize url, browser;

- (id) initWithURL:(NSURL *)u
{
    self = [super init];
    if (self) {
        self.url = u;
    }
    return self;
}

- (id) initWithBrowser:(NSString *)b
{
    self = [super init];
    if (self) {
        self.browser = b;
    }
    return self;
}

- (id) initWithURL:(NSURL *)u browser:(NSString *)b
{
    self = [super init];
    if (self) {
        self.url = u;
        self.browser = b;
    }
    return self;
}

- (id) initWithURLString:(NSString *)us browser:(NSString *)b
{
    NSURL * u = [NSURL URLWithString:us];
    return [self initWithURL:u browser:b];
}

- (BOOL)openURL
{
    if ([BROWSER_CHROME compare:self.browser options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        return [self openInChrome];
    } else  if ([BROWSER_OPERA compare:self.browser options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        return [self openInOperaMini];
    }else  if ([[UIApplication sharedApplication] canOpenURL:self.url] )
    {
        return [[UIApplication sharedApplication] openURL:self.url];
    } else {
        NSLog(@"Could not open url: %@", self.url);
        return NO;
    }
}

- (BOOL) openInChrome
{
    // is chrome installed??
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"googlechrome://"]])
    {
        NSString *scheme = self.url.scheme;

        // Replace the URL Scheme with the Chrome equivalent.
        NSString * chromeScheme = nil;
        if ([scheme compare:@"http" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            chromeScheme = @"googlechrome";
        } else if ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            chromeScheme = @"googlechromes";
        }

        if (chromeScheme) {
            NSString *absoluteString = [self.url absoluteString];
            NSRange rangeForScheme = [absoluteString rangeOfString:@":"];
            NSString *urlNoScheme = [absoluteString substringFromIndex:rangeForScheme.location];
            NSString *chromeURLString = [chromeScheme stringByAppendingString:urlNoScheme];
            NSURL *chromeURL = [NSURL URLWithString:chromeURLString];
            return [[UIApplication sharedApplication] openURL:chromeURL];
        } else {
            return [[UIApplication sharedApplication] openURL:self.url];
        }

    } else {
        return [[UIApplication sharedApplication] openURL:self.url];
    }
}

- (BOOL) openInOperaMini
{
    // is opera mini installed??
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"ohttp://"]])
    {
        NSString *scheme = self.url.scheme;

        // Replace the URL Scheme with the opera equivalent.
        NSString * operaScheme = nil;
        if ([scheme compare:@"http" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            operaScheme = @"ohttp";
        } else if ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            operaScheme = @"ohttps";
        }

        if (operaScheme) {
            NSString *absoluteString = [self.url absoluteString];
            NSRange rangeForScheme = [absoluteString rangeOfString:@":"];
            NSString *urlNoScheme = [absoluteString substringFromIndex:rangeForScheme.location];
            NSString *operaURLString = [operaScheme stringByAppendingString:urlNoScheme];
            NSURL *operaURL = [NSURL URLWithString:operaURLString];
            return [[UIApplication sharedApplication] openURL:operaURL];
        } else {
            return [[UIApplication sharedApplication] openURL:self.url];
        }

    } else {
        return [[UIApplication sharedApplication] openURL:self.url];
    }
}

- (void) dealloc {
    [url release];
    [browser release];

    [super dealloc];
}

@end
</code>
Comment: Why bother checking for the scheme for Chrome? Can't you just replace http with googlecrome, and if the 's' is left there it's there already?
Answer: Stumbled on this... @karim provided awesome code here. I ran into similar problem and eventually wrote Choosy - you can use it in your project to add support for many 3rd-party apps.


Fastest way to copy large file directory over slow internet

Question: I need to copy a directory from one of our servers several hundred miles away. Both sites where I am and where the files are have business cable. The cable is 5 Mbps(Down) / 768 Kbps(Up). This poses a small problem considering I need to copy about 85GB of data.
I used a file transfer calculator and it said it would take 11 days and some change.
I was wondering if there is any way to leverage something like DeDup to speed up the transfer.
The server I would be copying from is Windows 2003 R2, my box is Windows 7 Pro x64.
I was going to transfer the data to my iSCSI target which is running Ubuntu Linux, with ZFS and SCST. Would the dedup being performed by ZFS aid in the transfer so does the data need to be DeDup'd on the sending end?
Comment: Are you enable to employ a human at both ends? Not necessarily at the same time.
Comment: I am looking into that, might be the best way.
Comment: http://xkcd.com/949/
Answer: Buy an external hard drive. Copy data at site A. Mail it to site B. Copy to machine at site B.
Don't underestimate the power of the postal service.
Comment: I hear the latency is horrendous, though.
Comment: That idea had seriously crossed my mind.
Comment: Or [carrier pigeon](http://arstechnica.com/tech-policy/news/2010/09/carrier-pigeons-beat-rural-internet-upload-speeds.ars).
Comment: I can't believe no one's chimed in with this famous quote: http://en.wikipedia.org/wiki/Andrew_S._Tanenbaum#Quotes
Comment: Sneakernet4Life! Since the USPS is going TU soon...
Comment: A couple of USB sticks is probably cheaper to buy, and would *certainly* be cheaper to ship.
Comment: @womble I think that is the best idea.
Comment: "Never underestimate the bandwidth of a minivan filled with hard disks" ?
Answer: Is there duplicate data?
If not, then a dedup will help not at all; if there is, it will only be deduplicated over the wire if you transfer it with zfs send -D - since your destination is Windows, then that's probably a no.
Don't forget good old fashioned compression.
Comment: All normal computer compression is lossless (zip, gzip, bzip2, rar, etc). It means the data which goes in is the same when it comes out. It won't corrupt your DWG files unless you have hardware failure or hit a program bug or it gets corrupted while copying. Lossy compression is where some of the data is thrown away on the grounds that we probably won't notice, and it applies to music, pictures and video, typically. (i.e. what goes in isn't what comes out, but it sounds or looks pretty much the same). In other words, you should use compression, but fix why it corrupts things first.
Comment: There is a lot of data that is redundant, they are a bunch of PDF file and AutoCAD DWG files. We found out that compressing the data in certain ways corrupts the DWG files. If I was going to compression would it be better to use something like bzip2 instead of zip. I was told bzip2 is "lossless" compression whatever that means.
Answer: For Directory with lots of redundant data, you can try DZO Compressor. Deduplication makes sense. DZO performs Deduplication as well as Lossless Compression. The product is still in beta phase. As per initial results on Data with duplicates, it performs 2-3 times better than winzip, winrar and others. See their website http://essensolabs.com/ for details or download the beta from below link.
http://essensolabs.com/invitation-trial.html
If the data doesn't contain duplicates, then it gives the same compression as 7zip as it uses lzma for lossless compression.
Above can only help in reducing the size and thus lesser time for transfer, but it may still be in days !!!


Regarding the Continuum Hypothesis

Question: Mathematicians seem to be reluctant to say the Hypothesis of the continuum is true, many even arguing against. Ever since 2021, when it was proven that the cardinality of the continuum is at least ${\aleph_2}$. We also know that the cardinality of the natural numbers is ${\aleph_0}$.
But now strictly intuitively speaking, wouldn't it be very logical that the cardinality of the real numbers is $2^{\aleph_0} $?
Let me explain:
Every positive (for the sake of simplicity) real number can be written as the fractional part + integer part. And since the length of the integer part is a lot smaller than the factionary part in a real number, we may just consider that cardinality of the fractional part.
The next step would be that we write the fractional part in binary.
Something like this:
$0.011010110....$
But there are ${\aleph_0}$ digits in such a number (since its never-ending - even the rational numbers have a never ending either of repeating digits, or of 0s).
And since there are only 2 digits that we can use in binary - 0 and 1 -, this means that for a sequence of n digits we can create exactly $2^{n}$.
And since there are ${\aleph_0}$ digits in a real number, we may conclude that there are $2^{\aleph_0} $ real numbers.
Please note that I'm just an amateur in math, and enjoying to play around with concepts. I have most likely made a mistake, and I'm eagerly waiting to understand what that mistake is and why it cannot be the way I said.
So take it with a grain of sault.
Thanks alot!
Comment: It was not "proved" that the continuum hypothesis is false. I suppose that you mean that article in Quanta about the Asperó–Schindler paper. That is **definitely** not what they prove there.
Comment: For convenience for the non-expert and the ignorant (e.g., me), here is a link to the Quanta article https://www.quantamagazine.org/how-many-numbers-exist-infinity-proof-moves-math-closer-to-an-answer-20210715/
Comment: @AsafKaragila Yes. That's exactly what I mean :D
Answer: The cardinality of the continuum is $2^{\aleph_0}$, the argument is roughly as you describe, although there are some subtleties to be dealt with (e.g. some numbers would have two distinct binary expansions, but we can correct for that).
The problem is that assuming only the axioms of $\sf ZFC$, we are unable to determine whether or not $2^{\aleph_0}=\aleph_1$ or $2^{\aleph_0}=\aleph_2$, or maybe it is actually much larger.
The only thing we can prove that that the cofinality of $2^{\aleph_0}$ is uncountable. This is a technical concept, but in this case we can state it simply: if $F\colon\Bbb{R\to N}$ is any function, then there is some $n\in\Bbb N$ such that $\{r\in R\mid F(r)=n\}$ has the same cardinality as the continuum. This mean that $2^{\aleph_0}\neq\aleph_\omega$, where $\aleph_\omega$ is the first infinite cardinal which has infinitely many infinite cardinals below it.
But we know that this is the only limitation. We can have the continuum as large or as small as we want as long as it satisfies the above requirement.

As a side note, nobody proved recently that $2^{\aleph_0}\geq\aleph_2$. The work of Asperó and Schindler show that assuming a technical axiom called $\sf MM^{++}$, which implies $2^{\aleph_0}=\aleph_2$, we can prove an even more technical axiom known as $(*)$.
But $\sf MM^{++}$ itself is not provable. You can assume it, or you can assume its negation. And whether or not there is an absolute mathematical truth, so far as a mathematical society we seem more keen to assume that it is something like $\sf ZFC$, and so we do not have enough information to determine whether or not $\sf MM^{++}$, $(*)$ or $\sf CH$ are true.
Comment: $\aleph_1$ is the number of countable well-ordered sets (up to order isomorphism). $\aleph_2$ is the number of well-ordered sets (up to isomorphism) which have cardinality $\aleph_1$ or less. These can be represented concretely as a set of equivalence classes of orders of subsets of $\Bbb N$, or more directly as the von Neumann ordinals corresponding to the $\aleph$ number.
Comment: $0.011111\ldots=0.10000\dots$
Comment: Oh yeah. Obviously
Comment: @Daron: That is just because you've spent a lot more time learning about $\Bbb R$. Getting down to brass tacks, in the language of set theory, $\omega_1$ is arguably *simpler* to write down than $\Bbb R$.
Comment: I see. But how can a number have two distinct binary expansions? Could you give me an example? And perhaps even an explication? It seems fascinating to me.
Comment: But then what could an ${\aleph_1}$ be? assuming  the cardinality of real numbers is bigger that ${\aleph_1}$. Is there a set that has ${\aleph_1}$ elements?
Comment: @MarcusRost There are sets with $\aleph_1$ elements.  But you will never be able to write down such a set in the same simple way that you can write down $\mathbb R$ as being a set with $2^{\aleph_0}$ elements.
Comment: @Daron: $\omega_1$ is fairly simple to write down.
Comment: @AsafKaragila I only know the list of all countable ordinals write-down-ition. But I don't know what all those ordinals look like in the same way I know what all the real numbers look like.
Comment: @AsafKaragila Hmmm . . . maybe I need four strokes of the pen to write down $\mathbb R$ but I can manage $\omega_1$ in only three!
Comment: @Daron: Both require two! :P

Regarding the Continuum Hypothesis


What happens if a batsman does not play a shot and the ball touches their pad?

Question: What are the rules in cricket if a batsman does not play a shot and the ball touches their pad? Can the batsman take a run?
Answer: No, unless the striker was trying to avoid being hit by the ball. This is made very clear in (the newly numbered) Law 23, but there is no substantial change from the old Laws:

23.2.1 If a ball delivered by the bowler first strikes the person of the striker, runs shall be scored only if the umpire is satisfied that the striker has
either     attempted to play the ball with the bat
or          tried to avoid being hit by the ball.
[...]
23.3 If in the circumstance of 23.2.1 the umpire considers that neither of the conditions therein has been met, then Leg byes shall not be awarded.

In particular, this means that you can't score runs by kicking away balls which pitch outside leg stump.


Free and easy software to Monitor Cisco Router (T1)?

Question: I have a Cisco 1700 series router configured for T1 use. I was told to setup active monitoring to log uptime/flapping/etc. What options are out there for free? Cacti looks like a nightmare to setup I cant find a download of a VMWare image or I would go that route. The downloads I found expired. Any suggestions greatly appreciated.
Comment: What about cacti looks like a nightmare? It's not that hard to setup (no more so than any other SNMP/MRTG based tool anyway)
Comment: If you only care about uptime and not bandwidth try smokeping
Comment: Cacti is not that hard to configure, like any other tool there will be a learning curve. Google for some tutorials and take the time. I used to be in the same situation!.
Comment: If all you want is uptime nagios'll work. But the graphs of everything else that cacti gets you are pretty awesome.
Answer: SNMP
On the cisco, add the snmp service and set the community string:
conf t snmp-server community [community string] ro

Then check what interface to monitor:
MYCISCO#show snmp mib ifmib ifindex
  FastEthernet0/0: Ifindex = 1
  Null0: Ifindex = 3
  Multilink1: Ifindex = 8

You will need the number next to the interface, in this config, Multilink1 is a bonded T1 interface, so we will remember 8 for later on.
Exit conf t and save:
exit
exit
wr mem

These are the OID's you'll set in PRTG, STG or any other snmp monitoring app:
220.127.116.11.220.127.116.11.1.10.8
188.8.131.52.22.214.171.124.1.16.8

Notice the 8 at the end, that is the number that indicates the interface that we identified above.
Answer: I've had a great time with PRTG and its ease of use.
Comment: Good, but not free
Answer: zenoss core. they have a virtual appliance as option as well.
Comment: tried it, terribly bloated. Anything else?
Comment: bloated how? I've monitored 400 devices and 75,000 datapoints with just the base VM
Comment: Currently using Zenoss Core and I like it, not as good as some proprietary software but very good for free. Lots of addons for monitoring servers, ups's vmware etc.
Answer: Define 'etc'.  You can go with something simple like http://oss.oetiker.ch/mrtg/ (MRTG) or something much more full featured.  What are your requirements, exactly?  Bandwidth measurement?  Uptime?  What system are you going to use this on? (windows/unix)?  Do you want alerts sent when something happens?
Answer: If you think Cacti looks complex most other "real" monitoring systems are even more complex to setup. If you have a Linux machine available you could always use syslog-ng and use a syslog to mail script to trigger e-mail alerts based on certain syslogged strings (such as %LINKPROTO etc). It's very simple but would not be as reliable and scalable as implementing nagios, zenoss, opennms or a similar system.
On the Cisco router enable remote syslogging:
logging 192.168.1.1 (the ip of the Linux box running syslog)

You also need to define what you want to send to the syslog server with the snmp-trap directives (yes, snmp-traps also control syslogging).
syslog-ng.conf example:
source s_remote {
    tcp();
    udp();
};
destination d_mail {
    program("/usr/local/bin/syslog2mail.sh");
};
destination d_varlog {
    file("/var/log/$HOST" owner(root) group(logging) perm(0640)
    );
};
filter f_cisco {
    level(debug..emerg) and
    match("IP-EIGRP|IP-OSPF|LINKPROTO|LOGIN_FAILED|etc")
    and not match("stuff to ignore|dog|cat");
};
log {
    source(s_remote);
    filter(f_cisco);
    destination(d_varlog);
    destination(d_mail);
};

And the script to trigger emails:
#!/bin/bash -x
while read line; do
    var=$(echo $line | cut -d' ' -f4)
    echo $line | /bin/mailx -s "log notification $var" email@example.com
done

An alternative and possibly nicer way to do the same thing is to send snmp traps from the Linux box and translate the traps to emails in a similar way.
Answer: I've setup Graphite and fallen in love with it. Granted, it's best if you write your own scripts to poll for data, but sending data to it is pretty easy if you follow their sample python script.


Listing all nilpotent matrices of $\mathcal{A} = \{c_0I+c_1E_1,c_2E_2\mid c_i\in K\}$

Question: How to solve the following problem:

Let $\mathcal{A} = \{c_0I+c_1E_1+c_2E_2\mid c_i\in K\}$, where
  $I,E_1,E_2\in \mathcal{M}_n(K)$ and $E_1,E_2$ are idempotent
  orthogonal matrices, that is $E_1^2 = E_1, E_2^2 = E_2$ and
  $E_1E_2=E_2E_1=O$. $K$ is a field. We also assume that $E_1,E_2\neq O$
  and $E_1+E_2\neq I$. The set $\{I,E_1,E_2\}$ forms a basis for
  subalgebra $\mathcal{A}$.
List all nilpotent matrices of $\mathcal{A}$, that is matrices
  $A\in\mathcal{A}$, such that $A^m=0$ for some $m>0$.

I have tried solving this, but I'm not sure of my solution and want to verify my approach.
Comment: Does $K$ have characteristic $0$, or not necessarily?
Comment: This information is not given in my problem. One thing I forgot to mention: $\mathcal{A}$ is a subalgebra. If it helps.
Answer: Hint: Let
$$A=c_0I+c_1E_1+c_2E_2$$
Then
$$A E_1 =(c_0+c_1)E_1$$
$$A E_2 =(c_0+c_2)E_2$$
This shows that $c_0+c_1$ and $c_0+c_2$ are eigenvalues of $A$ with any non-zero column of $E_1$ respectively $E_2$ as eigenvectors.
Now, if $A$ is nilpotent, all its eigenvalues are ....
Hint 2
$$(I-E_1-E_2)^2=??$$
Comment: Thank you! =) Excellent. I was on the right track, but I didn't consider about the eigenvalues :)


Find joint density given conditional density

Question:
These are the steps I followed:
$ \frac{f(y_1,y_2)}{f(y_1)} = f(y_2|y_1) $
$ f(y_1,y_2) = f(y_1).f(y_2|y_1) $
$ f(y_1,y_2) = 3e^{-3y_1}.\frac{1}{2y_1} = \frac{3}{2y_1} e^{-3y_1}$
Inorder to find marginal distribution of y2, we need to integrate wrt y1 from 0 to infinity.
But this integral has no bounded solution from what I know. Is there something I'm missing or some transformation that I should be doing somewhere?
Comment: You are missing the indicator function $\mathbb I_{0\le y_2\le y_1}$
Answer: The question asks you to use the conditional distribution. You'll utilise the law of total expectation:
$$E[Y_2]=E[E[Y_2|Y_1]]$$
And, $E[Y_2|Y_1]=Y_1$.


How to prevent stack overflow in a game that infinitely loops?

Question: I made a Tetris game in c++ command line. It actually works perfectly fine until the stack overflows. I understand what a stack overflow is, but I don't know how to prevent it in a game that is supposed to go on forever. For sake of not sharing 700+ lines of code, I am going to simplify the code into basic functions.
Code:
int main(){
    //Sets position of first block
    //picks random tetris piece for player to control
    updateScreenMain();
}
int updateScreenMain(){
    //All code related to drawing screen is here
    //At the end of it, there are several if statments-
    //-that test for if the block hit the ground yet
    // If one of those functions is called, example: reseting the
    // block to the top of the screen, it will call updateScreenMain()
    // again
}

Basically, what I want to do is clear the stack memory. I see that when my functions call other functions, they get nested until a stack overflow. How can I prevent this?
Comment: Use a loop instead of recursion - recursion is absolutely not the right tool for this
Comment: You say in your title that you want something that "infinitely ***loops***". That should have been a hint about the solution. :)
Comment: Rather use something like `for(;;)` or `while(true)` instead of recursion.
Comment: If you really must use recursion make sure it's tail recursion so the compiler can optimise away your function calls. Tail recursive code is usually easy to convert to a loop. If you want us to help further we need a [mcve]
Comment: Thanks guys I just turned everything into one huge loop and it seemed to do the trick
Answer: There are a lot of ways. Here is an example:
int main() {
    while(updateScreenMain());
}
int updateScreenMain() {
    // Just return 0 to stop
}

In general, just avoid recursion.


Show that $\int_\mathbb{R} f' g = - \int_\mathbb{R} f g'$ for $f, g \in C^1(\mathbb{R})$ with $f, g, f', g' \in L^2$

Question: Say we have  $f, g \in C^1(\mathbb{R})$ with $f, g, f', g' \in L^2$. I want to show that $\int_\mathbb{R} f' g = - \int_\mathbb{R} f g'$.
I see that
\begin{equation}
\int_\mathbb{R} (fg)' d\lambda = \int_\mathbb{R} \lim_{n \to \infty} n \cdot (fg(x + 1/n) - fg(x)) d\lambda(x)
\end{equation}
so I wanted to show that:
\begin{equation}
\int_\mathbb{R} \lim_{n \to \infty} n \cdot (fg(x + 1/n) - fg(x)) d\lambda(x) = \lim_{n \to \infty} \int_\mathbb{R} n \cdot (fg(x + 1/n) - fg(x)) d\lambda(x) = 0
\end{equation}
However, I don't see how I could prove this convergence. The function $n (fg(x + 1/n) - fg(x))$ doesn't seem to be bounded by some integrable function, so I cannot use the dominated convergence. Could someone please help me?
Comment: Use integration by parts and show that, given your assumptions, the border term vanishes
Comment: So you mean something like $\int f'g = fg - \int fg'$? But why must $fg(x)$ vanish for large $x$? What if we take $f, g$ to be $C^1$-approximation of $h$ where $h(x) = 1$ on $x \in [n, n + 1/(n^2)], n \in {2, 3, ...}$ and $h(x) = 0$ otherwise? This is in $L^2$ and can certainly be made into $C^1$ function, right? What am I missing?
Comment: Ok, this example doesn't work because $f'$ is not in $L^1$ in this case. Still, how do you prove that the border term vanishes?
Answer: As mentioned in the comments you can use integration by parts.
The boundary term vanishes because of the control on the functions and the derivatives:
$$(f g)'(x) = f'(x) g(x) + f(x) g'(x),$$
so $(fg)'$ is in $L^1(\mathbb R)$ as the sum of products of $L^2$-functions. It follows that $\lim_{x\to\infty} (fg)(x) = f(0)g(0)+\int_0^\infty (fg)'(t)\,\mathrm dt$ exists, and thus, since $fg\in L^1$, the limit must be equal to $0$.
Similarly (left to you), $\lim_{x\to-\infty} (fg)(x)=0$.
Comment: @AbbyJean It is the limit of $fg(x)$ as $x\to\infty$ (the limit exists because $(fg)'\in L^1$), and any $L^1(\mathbb R)$ function that converges as $x\to\infty$ must converge to $0$.
Comment: why does $f(0)g(0) + \int_0^\infty (fg)'(t) dt = 0$?


C++/CLI, XAML, and event handlers

Question: I'm new to the Windows world, and I think I'm getting lost in the weeds on a problem. I'd love some advice from people with experience with C++/CLI and WPF and XAML.
I have some win32 code, and I need to run a WPF GUI. I found this MS walkthrough sample, which uses C++/CLI. I adapted it to my purposes, and it works great.
Next, I wanted to rip out the programmatic WPF stuff and use XAML instead. This is so I can hand off the XAML to a designer person and take myself out of the UI design loop, where I most assuredly don't belong. After reading the "WPF Interoperation Projects" section of WPF and Win32 Interoperation on MSDN, I decided to go with the XamlReader::Load option and load uncompiled XAML at runtime. My XAML markup is a Canvas UIElement which I programmatically add as a child of my root Grid C++/CLI element. This works great.
Now I want to add event handler to controls in the XAML. This is where I have started to run into trouble. I'm sure that my general ignorance of the Windows world is 95% of what's killing me here.
I started with Rob Relyea's page outlining the various XAML-and-event-handler options.
I decided to try compiling the XAML as a C# DLL. It's basically the same XAML as what I used in the runtime Load case. I instantiate the object and programmatically add as it as a child, just like before. But ... I get nothing but a black window. No exceptions get thrown either. I'm baffled.
My question is, am I even headed down the right path? The page on XAML-and-event-handlers says you can use event handlers defined in uncompiled XAML in .Net Framework 4. Should I bite the bullet and just go to VS 2010 (I'm presently on VS 2008) so I can use .Net Framework 4 and just stick with uncompiled XAML? Are there any gotchas with doing things that way?
Or, if you do think the compiled C# DLL is a reasonable path, do you have any ideas on how I can debug the problems I'm having?
Or, is there a better and completely different approach?
Thanks in advance for your advice.
Polly
Comment: You're on the wrong path.  Tooling is pretty important in WPF, whether through the IDE or Expression.  There is no tooling integration with C++/CLI whatsoever.  And there never will be.  Nor is there any advantage to using C++/CLI over C#.
Comment: Hans, thanks for your comment. I generally favor the well-trod path (i.e., C# over C++/CLI) too, but in this case there's a considerable investment in C++ code I need to preserve. In this case, my goal is to give that existing code a much prettier face.
Comment: Unmanaged code can call managed code quite easily via C++/CLI, so you could write your GUI in C# but have it called by C++ code.  While it is more usual to have C# call C++ via C++/CLI, your approach is just as valid.  If you don't want to use C# you'll have to assign event handlers in code-behind with some tricky calls like FindName or searching the visual tree.  It can be done, but I think you'd have less pain making C# assemblies for use by your C++ code.
Answer: I think the right answer for this depends on some issues that only you can decide, but I'll start with the assumption that your C++ code base is big and complex enough that it is worth preserving.
Beyond that the next decision point is do you have UI (perhaps GDI) code in the C++ your preserving or only non-UI code.  If you are attempting to preserve only non-UI code then I would consider pushing more UI responsibilty into C#.  Perhaps you go so far as to build your views, event handlers, and maybe even view models in C#.  This will enable you to take better advantage of the VS tooling.
If you've got extensive UI code in C++ to preserve then your current path makes a more sense. I don't think it will be impossible, but you'll have quite a challenge ahead of you.  The key example here is Visual Studio 2010.  It is the premiere example of a mixed application and has GDI and WPF side by side unlike any other app I've ever seen or heard of.  There is a series of blog posts that I found pretty interesting that describe some aspects of what the Visual Studio team did to achieve this integration at The Visual Studio Blog.
I also came across this video Henry Sowizral on Refacing C++ with WPF in Expression Design that I have not seen myself, but discusses putting a WPF UI on top of an existing MFC C++ app.
Good luck.
I don't have any specific advice on the first part of your question other than to say that putting more responsibility in C# would allow you to build a small stub app if necessary which could go a long way toward diagnosing problems.
Comment: These are all good points. In this case, though, I have some large amount of performance-sensitive code in C++ that I want to give it a more attractive WPF GUI. The GUI code is not at all performance-sensitive. The performance reasons are why I decided to have a C++ app that calls into WPF code for occasional GUI purposes, rather than a C# app that calls into C++ code for long computation. I'll admit, though, that was based on intuition and not a thorough knowledge of win32/.Net interoperability performance considerations. Do you think I have that wrong? Thx for the pointers; I'll have a look.
Comment: It's really hard to be any more specific based on the information here.  I was thinking that you could create a ViewModel (search MVVM); it's basically a data model of what you want to display in your Xaml.  Then bind your Xaml to the C# ViewModel then manipulate or respond to the ViewModel in C++.  This would keep the Xaml stuff more traditional and blendable.  I don't know if putting a ViewModel in C++ would be possible.  There is a mismatch for the Xaml vs Win32 methodology in addition to the language issue.
Answer: Thanks to everyone for the responses. On the matter of getting stuck on the C# DLL, I found this C++/CLI sample: http://msdn.microsoft.com/en-us/library/aa970266.aspx. Using that, I found my error, and was able to load the WPF without problems.
However, the whole motivation for loading the C# DLL was that I had understood that that was the way to attach event handlers programmatically. Following AresAvatar's suggestion, I found that I could use FindName to attach the handlers -- both within the C# DLL, but it also worked with my original loose-XAML approach. So, I didn't need the C# DLL after all!
It's all working nicely now. Again, thanks for all of your help and suggestions.

C++/CLI, XAML, and event handlers


Is it possible to get a windows-version from a powershell command on Windows Server 2016 Nano?

Question: I'm using the latest preview of Windows Server 2016 nano.
Using a remote powershell session, I connect to the remote system via Enter-PSSession, and then I tried to use the most common techniques to check Windows versions, because the full .Net framework is not available. Also, Get-WmiObject cmdlet is not available.
The only way I can see SOME information is with this non-powershell-command DISM:
Dism /Online /Get-Feature

That gives me this output plus a list of installed features:
Deployment Image Servicing and Management tool
Version: 10.0.10514.0

Image Version: 10.0.10514.0

Features listing for package : Microsoft-Windows-Foundation-Package~31bf3856ad364e35~amd64~~10.0.10514.0

From the 10514 value, which is higher than my Windows 10 desktop, I can get some idea of the Kernel Build, and it is interesting that Windows 10 desktop has the same "Microsoft-Windows-Foundation-Package", but a lower kernel build number.
Has anyone found a cmdlet or some powershell function or alias that could be written, that will either detect for me the fact that my powershell script is running on a nano-server, in some way which is unlikely to break, or any command which will actually print out "Windows Server 2016 Nano Server"?
Update: This is closer to what I want, but is a bit of a hack:
  Get-Item -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion'

Update 2: Get-WmiObject is not present, and while the following works, it only reports kernel version:
[System.Environment]::OSVersion.Version

Above will report build 10514, whereas Windows 10 client operating systems RTM reports 10240 at the moment, but the above is really a "kernel build" not an operating system product/edition/service-pack-level.
Answer: You could try the following, I've not got a nano server to try it out on. Drop the select if it gets you something else and see if what you want is stored under a different property in Server 2016 Nano
Get-CIMInstance -ClassName Win32_OperatingSystem -Property * | select caption

When tested on a real Nano instance the -session parameter was not needed, but if you need it at some future date, here's the variant with -session:
$cuser = "Your username"
$cservername = "Your Servername"
$csession = New-CimSession –Credential $cuser –ComputerName $cservername
Get-CIMInstance –session $csession -ClassName Win32_OperatingSystem -Property * | select caption

Comment: The session stuff is not necessary if you're already in a remote session you entered via `Enter-PSSession` so I suggested an edit.
Answer: This is just an extension on your edit, but cleans up the output, by getting only ProductName
$(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' ProductName).ProductName

Comment: That's a nice improvement.
Answer: The Microsoft way aka the Cert way is to use the Get-WindowsEdition -Online
additional information on the command and all its options can be found at Here!
Comment: Very tiny amount of information in `Get-WindowsEdition -Online` reports only back `Professional` - does it report back `Nano` for nano server?
Answer: PowerShell Administrative command prompt and typing:
 Get-WmiObject -Class Win32_Operatingsystem

Returns:
Build Number and Version

Comment: No way to see if that's nano or not