setting global variables in MS Access

Question: I have been searching the internet for hours but have yet to figure out what I am doing wrong.
I have created a login form, which has a combobox for user name and a text box for the password.
I need to save the user name for future use, so I have created a new module and in it a global variable for the name:

Option Compare Database
Option Explicit
Public Name As String

I am trying to set a value in a private sub into this variable like this:

Name = Me.cmbClient.Value

but i keep getting this error "run-time error '2135': this property is read-only and can't be set"
I have no idea what I am doing wrong. I would really appreciate it if someone could help.
Answer: Name is a reserved word in VBA.
Comment: omg, thank you so much! I have literally been pulling my hair not realizing what the problem was! You are a life saver!!!!

setting global variables in MS Access


Event/ETL based Agent in OBIEE 11g

Question: I have created an Agent in OBIEE 11g which kicks off at a specific time (8 am everyday). The problem is that sometimes by this time the underlying ETL process does not complete so the report kicked off by the agent shows inaccurate data. One way to rectify this is that I can reschedule the agent, i mean delay it by couple of hrs. But I am looking for event based triggering of agent. Like when my ETL completes then the agent should kick off. Is there a way to achieve this?
Comment: Maybe this question would be better of at https://dba.stackexchange.com/?
Answer: You could set the Agent to have no schedule, and instead trigger it from your ETL batch on completion from a Web Service call executeIBotNow, or with saschinoke
This blog article gives detail around the options (even if you're not using ODI, the concepts will still apply): http://www.rittmanmead.com/2012/01/bi-ee-11-1-1-5-calling-bi-ee-11g-agents-through-oracle-data-integrator-11g/
A last option would be to use a Condition that the Agent checks before running, and schedule the Agent to run multiple times. It's not nearly as clean as the above options though.

Event/ETL based Agent in OBIEE 11g


How would one use Voronoi diagrams for KMeans for high dimensional data?

Question: I am reading Aurelien Geron's Hands on Machine Learning, and in the Unsupervised learning chapter he demonstrates how to create a Voronoi diagram after performing K-Means clustering, and produces the awesome plot below. However, he demonstrated this by artificially creating a 2D dataset. I have much higher dimensional data. I ran K-means on it, and then performed PCA so that I could visualize it in 2D. I was wondering if there's a way to visualize the 2D decision boundaries, as with the Voronoi diagram below. I tried getting the cluster centers (high dimensional ones) and reducing their dimension using PCA (if visualizing the centers is not possible, I'm presuming visualizing the 2D boundaries is not possible either), and then plotted them on my original 2D plot (the original data reduced to 2D), but I noticed that they were quite off from the 2D dataset.
One idea that I had in mind was to run K-means on the 2D dataset itself, but I'm guessing that would not be an appropriate way to do this?
Answer: If you do in fact have 2D decision boundaries, we can visualize 2D decision boundaries, you just need to compute the 3D Voronoi diagram. However, these are not usually good visualizations, since you need to be able to see through different parts they end up looking like blobs of stained glass. But...
Your data probably doesn't have 2D decision boundaries. If your data is $n$-dimensional, then the K-means decision boundaries are $(n-1)$-dimensional (because they're formed from hyperplanes). This is why the example you showed has 2D data with 1D decision boundaries, and only 3D data has 2D decision boundaries. If "much higher" dimensional data means $n > 3$, then your decision boundaries won't be 2D, they'll be $(n-1)$-dimensional.
Visualizations are limited to three dimensions or lower, so to visualize higher dimensional data, we have to reduce the the number of dimensions by projecting to a space with three or fewer dimensions. This is a problem for the decision regions from the K-means algorithm because while the decision regions don't overlap, their projections can overlap (see the image below, where the decision regions in blue and purple are both projected onto the one-dimensional line in red). It also does not preserve the shape of those decision regions.

PCA is one such way of doing this, but not the only way. In fact, PCA might not be the ideal way to visualize the clusters in your data. PCA is designed to optimize how the data can be approximated with a lower dimensional subspace, not to find a useful subspace for clustering. Here's an example where it fails (see pictures below): there are eight clusters, but six of them lie in the same plane, and then the other two clusters are above the plane and below the plane respectively. PCA will find the best 2-dimensional plane that fits the data, but when all points are projected into the plane it makes it impossible to separate the top and bottom clusters, because they get projected to the same region. It's possible that you would get better results with a random plane, but it ultimately depends on your data.
Comment: I see. So what would be alternatives to K-means and PCA to help in visualizing the boundaries?
Comment: It might not be possible depending on your data. If it looks anything like a higher dimensional analogue of the the Voronoi diagram I showed above, then it is impossible to effectively visualize. If you are lucky, maybe there are precisely two features of your data you could use to cluster on effectively. If this is the case, you could drop all other features and show the clustering in two dimensions by using only these two features. And PCA doesn't optimize for this, but I'm not sure if there's a better way. Maybe try two random features and plot repeatedly to see if anything looks good?


What is the definition of 909/808/707/etc. percussion?

Question: I would think that these sounds would be the sounds made by the classic drum machines.  But I see many samples advertised as being "909 kick" for example, and these may be different than what the machine made.  There might be a dozen 909 snares, for example.
What do these modern samples mean when they claim to be x0x?
Comment: Here is a Dr Mix sample of the classic TR-808 sounds that samples try to emulate: https://www.youtube.com/watch?v=KC7UaUD5rEA
Answer: The Roland TR-808, TR-606 and TR-909 are analog synthesizers with many adjustable settings, capable of creating a range of different sounds with different attack/decay envelopes and pitch. The TR-909's cymbal sounds are based on PCM samples, but all the rest is synthesized. Many different snare sounds can come out from a TR-909, so that's why there can be many different "909" snare samples.
The definition of 909/808/707/etc. percussion is, they are sounds that were either sampled from an actual Roland drum synthesizer with that name, or modeled after those sounds, trying to sound like the original.
The TR-707's sounds are all based on samples, not synthesized.
Answer: Although piiperi's answer is accurate, I want to note specifically that the term "808 kick" has expanded to describe any electronic kick drum sound with a long tuned decay, which can serve as both the kick drum and bass instrument in a song.
Comment: The "808" has become so famous in hip-hop that it's referenced frequently, like in Kanye West's 808s & Heartbreak. In that genre it often has a low booming sound that is very heavy in low-frequencies for subwoofers, straying from the original TR-808 bass sound.   Here are some examples https://www.youtube.com/watch?v=08tdOHT_vJA


Pass two functions to map

Question: I'm trying to pass two functions and an iterable object in map
test_code = map(get_repo_info, repo_page)

def get_repo_info(data):
  print data['id'], data['full_name']

def repo_page():
   ...some code....
   returns a list of dictionaries that I map over in the map function

def write_to_csv():
   csv_open = open('test.csv', 'wb')
   csv_writer = csv.writer(csv_open)
   return csv_writer

In the get_repo_info() function I want to write everything to a csv file. Instead of printing out each line, I want to write each line to a csv row
I want it to look something like this
def get_repo_info(data, csv_writer):
  csv_writer.writerow([data['id'], data['full_name']])

And the map function would look something like this
map(get_repo_info, repo_page())

However, I can't figure out how to pass get_repo_info() the second argument of csv_writer in the map function, since the function used by map is only passed one argument at a time, not two.
Comment: `map(get_repo_info, repo_page())`?
Comment: So you want to use `get_repo_info()` as the function in a `map` statement, but the problem is that functions in `map` should only take one argument (a single item from the list) and `get_repo_info()` takes two as it's currently written. I edited your question to clarify this.
Comment: This isn't something that calls for `map`.  map is for 1:1 transforming each element of an iterable into something else.  You're just feeding each element into a `csv.writer` - just use a `for` loop.
Answer: def get_repo_info(data):
  print data['id'], data['full_name']

def repo_page():
   return [{"id":"bar","full_name":"foobar"}]

test_code = map(get_repo_info, repo_page()) # call the method
bar foobar

You could call map in your write_to_csv:
def get_repo_info():
    map(write_to_csv,[[[data['id'], data['full_name']] for data in repo_page()]])

def repo_page():
    return [{"id": "bar", "full_name": "foobar"}, {"id": "bar1", "full_name": "foobar1"}]

def write_to_csv(data):
    csv_open = open('test.csv', 'wb')
    csv_writer = csv.writer(csv_open)
    csv_writer.writerows(data)
get_repo_info()

This writes:
 bar,foobar
 bar1,foobar1

to your csv file.
But using a for loop would achieve the same:
def write_to_csv(data):
   csv_open = open('test.csv', 'wb')
   csv_writer = csv.writer(csv_open)
   csv_writer.writerows([[data['id'], data['full_name']] for data in repo_page()])

Comment: But how does it get written to csv?
Comment: @TheSoundDefense, the OP's code was not using `repo_page()` so the second arg would not support iteration, that is what I thought he/she was talking about
Answer: I just broke it out into a separate function
test_code = map(get_repo_info, repo_page)

def get_repo_info(data):
  return (data['id'], data['full_name'])

def repo_page():
   ...some code....
   returns a list of dictionaries that I map over in the map function

def write_to_csv():
   csv_open = open('test.csv', 'wb')
   csv_writer = csv.writer(csv_open)
   return csv_writer

some_info = get_repo_info(data)
csv_writing = write_to_csv()
csv_writing.writerow(some_info)

Pass two functions to map


Função para retornar frequências de letras numa array

Question: Eu tava tentando fazer a função que consta no título, porém não obtive sucesso, ao olha o código solução para tal função, não consegui entender, segue o código:
    function letter_frequency(s) {
    let arr = [];
    let i = 0;
    let str = s.toUpperCase();
    while (i < str.length){
        let char = str.charAt(i);
        if (arr[char]!== undefined){
            arr[char]++;
        } else arr[char] = 1;

        i++
    }
    return arr;
}

Minha pergunta se refere ao scope do if. Digamos que recebemos uma String "hello". Porque a letra H (charAt[i] para i = 0;) é considerada undefined?
Comment: Entendi a pergunta não é "porque o código não funciona" e sim "porque a letra testada é undefined"
Comment: JS tem umas coisas esquisitas e posso não saber de uma delas, mas pra mim isso é código ruim e não faz sentido. o `s` pode ser `undefined`. O código é tão ruim que faz 2 laços onde poderia fazer um só, e a pessoa que fez não percebeu isso, deve ter colocado esse `if` de alegre também porque viu algo parecido em algum lugar que manipulava outro tipo de objeto.
Comment: O código ta escrito errado nunca terá o efeito de contar frequência.
Comment: Não é a letra H que está sendo comparada com `undefined`, e sim `arr["H"]`. Basicamente, `arr[letra]` guarda a quantidade daquela letra, mas se for a primeira ocorrência dessa letra, `arr[letra]` ainda não existe, por isso verifica-se se é `undefined`
Comment: Agora que eu vi que ele está usando isso como dicionário.
Comment: Ele faz um laço na string da palavra e quando não encontrar uma letra na string, ou seja, enquanto ela **não** for undefined, significa que a letra não existe na string, ela define que a frequência é 1 (uma vez). Caso contrário, ele soma a quantidade de vezes que a letra se repete na string, tira o let e usa var... para entender: use: 'hello'.charAt(0); 'hello'.charAt(1);
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: O if em si ali está testando uma condição de um dicionário. Um dicionário é um objeto que tem vários elementos indexados por uma chave e esta chave pode ser qualquer valor válido.
Ele parece um pouco com um array, mas é diferente porque no array a chave é chamada de índice, só aceita um valor numérico inteiro em sequência, no caso do JS começando em 0 e terminando no número igual ao tamanho menos 1. No array todas as chaves dentro dessa faixa são chaves válidas, em um dicionário (também conhecido por hashtable ou array associativo ou mapa em certos contextos) não tem uma sequência, as chaves são esparsas então qualquer chave pode ou não existir nessa coleção de dados. Então essas coleções são um par de chave e valor, onde o que te interessa mais é o valor, mas é acessado através da chave.
A API do JavaScript escolheu que se você tentar acessar uma chave que não existe não dá erro, ele apenas resulta em um valor undefined porque se não tem a chave é claro que não tem o valor. Então o jeito de verificar se a chave não existe é exatamente ver se o valor resultante é undefined.
Neste código está pegando uma letra do parâmetro recebido e verificando se ela existe na coleção de dados, se ela não existe então a chave é criada com um valor inicial de 1, se ela já existe então apenas incrementa o valor de lá. Portanto essa coleção terá um elemento para cada letra diferente existente na string passada, quando a letra for repetida em vez de criar uma nova chave ele incrementa o contador de letras e assim obtém o que se espera, a contagem de frequência de letras.
Dá para fazer melhor isso, mas é uma forma válida.
Assim visualiza o que ocorre:

 function letter_frequency(s) {
    let arr = [];
    for (let chave in s) {
        let char = s[chave].toUpperCase();
        if (arr[char] !== undefined) arr[char]++;
        else arr[char] = 1;
        for (let chave in arr) console.log(chave, "=>", arr[chave]);
        console.log("------");
    }
    return arr;
}

letter_frequency("Hello");

Coloquei no GitHub para referência futura.
Answer: Porque a solução utiliza um array, arr, como um mapa, sendo que a chave será a letra presente na string e o respectivo valor será a quantidade que ela se repete. Inicialmente esse array está vazio e, portanto, não existirá nenhuma letra associada nele. Isso implica que arr['h'] retorne undefined.

let arr = [];

console.log(arr['h']);

Portanto, se for undefined, é criado o índice no array e inicializado com o valor 1. Nas próximas iterações o índice existirá e não retornará mais undefined e quando isso acontecer será apenas incrementado o valor.

let arr = [];

arr['h'] = 1;

console.log(arr['h']);

Ou seja, ao percorrer as letras da string sempre será retornado undefined quando for a primeira ocorrência dela. Nas próximas será apenas incrementado a quantidade.
Utilizando o Map
Uma alternativa seria utilizar o próprio tipo Map para criar esse mapa:

function frequency(text) {

  // Define o mapa que gerenciará as frequências
  const map = new Map();

  // Percorre as letras do texto
  for (let letter of text) {

    // Busca a quantidade de vezes que a letra já se repetiu, ou 0 para a primeira ocorrência
    let count = map.get(letter) || 0;

    // Atualiza a frequência incrementando-a
    map.set(letter, count+1);
  }

  // Retorna o mapa de frequências
  return map;
}

const frequencies = frequency("anderson");

// Exibe a frequência de cada letra
for (let [letter, total] of frequencies) {
  console.log(`A letra ${letter} repetiu ${total} vezes.`);
}
Answer: Amigo, é o seguinte:
Ele verifica enquanto o array da letra "não" for indefinido, ou seja, quando ela entrar na regra de contagem e passa a somar os valores. A letra H no caso é definida, ou seja, oposto do que você está dizendo. e não é um array como você publicou, do tipo: charAt[i], mesmo se comportando como tal, isso é uma função do javascript, que captura a posição da letra na string:
Por exemplo: 'Hello'.charAt(0) irá retornar "H";
A função String.charAt() retornará a letra na posição da string [0 => 'H', 1 => 'E', 2 => 'L', ...]
O if no caso está testando a letra, considere que i seja 0, então na variável char terá a letra "H", ela é indefinida, certo, então ela entra no else, o [negado+igual+igual] ( !== ) está verificando se é diferente tanto o tipo, como seu valor.
Ou seja, se for um "H" ele entra no else e recebe o valor 1:
 let char = str.charAt(i);

`else arr[char] = 1;`

O while está incrementando a variável i , enquanto ela for menor que o total de letras da palavra, isso faz com que ele percorra letra a letra e atribua os valores da soma para elementos definidos, em todas as outras situações será undefined, e receberá o valor 1:
 if (arr[char]!== undefined){
     arr[char]++;
 }

Observe que o while faz isso para cada letra:
arr[char]irá somar quando for definido:
arr["H"]++
arr["E"]++
arr["L"]++ //aqui fará uma soma de vezes pois ele terá sido definido mais de uma vez
arr["O"]++

Ele vai passar pela regra de atribuição 5 vezes:

1º entrará no else, já que arr[char] ainda não foi definido, retornando o valor 1 para a posição da letra H.
      2º entrará no else, já que arr[char] ainda não foi definido, retornando o valor 1 para a posição da letra E.
      3º entrará no else, já que arr[char] ainda não foi definido, retornando o valor 1 para a posição da letra L.
      4º entra na condição do if, uma vez que já tenha definido arr[char] com a letra L, ele se auto-somará: 2
      5º entra no else novamente pois a letra O ainda não foi definida e coloca  o valor 1.

Você pode testar e ver isso acontecer da seguinte maneira no console do seu navegador:
function letter_frequency(s) {
    let arr = [];
    let i = 0;
    let str = s.toUpperCase();
    while (i < str.length){
        let char = str.charAt(i);
        if (arr[char]!== undefined){
            arr[char]++;
            console.log('definido',  arr[char], char)
        } else {arr[char] = 1;
            console.log('indefinido',  arr[char], char)
        }

        i++
    }
    return arr;
}
letter_frequency("Hello");


Architectural - How to setup content types for very unique editable pages

Question: We are working on a site for a client. This page has in total about 30 different pages. Each page has a unique and complicated design. In order to give the client the possibility to edit texts on the pages without changing the design we created text fields for each content type. Each content type has around 30 fields (text or long text) which we manually render in the template files. Each field has a unique machine name. We always created a new field whenever we needed a new field in one of the content types. And each content type has only a few contents (variation of the page).
Current structure:
<code>Content type 01
    Field 01
    Field 02
    ...
Content type 02
    Field 05
    Field 06
    ...
</code>
The question now is if there is a better way of building such a architecture, since we are having a quite large php memory usage. The idea of drupal is to create a content type and have then a lot of contents of that type. But that approach doesn't fit to our customized page design.
One possible solution which we gathered is to reuse the fields in all the content types. Originally we named the fields in the example above field_content_type_01_field_01 and field_content_type_02_field_05. This solution would mean we have to change the fields to have field_field_01 and reuse that field in all content types.
But is there a better way for our setup?
Answer: Option 1: Panels
Maybe you should check to what extend your unique and complicated design of each page" could be implemented using the Panels module. Some details from its project page:

The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Learn Page manager! is an interesting (and amazing) set of videos. They contain various topics related to the Panels module. Here is a summary of the entire set of videos about this topic (quote from the link above):

Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
The screencast series is targeted at experienced Drupal developers.
Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about the Panels module.
Option 2: Display Suite
Another approach is to use the Display Suite module. Some details from its project page:

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.

Screencasts & articles about Display Suite has numerous screencasts with more details about it.
Comment: Thank you, but all that doesn't fit in our situation. We are using display suite, that can't help with the original problem, how to setup the content types. Displaying the data is totally fine how it is. Our question is the setup...


IIS 7 Fails to do anything

Question: I can access the administrator front end but:

http://localhost cannot find the page
Any asp.net apps cannot be located via a browser
I have reinstalled, if you call it that - did it via the server manager, but no such luck.

Help!
Comment: Have you checked your IIS logs?
Comment: This question should have been asked at ServerFault.com
Comment: That's actually a feature! :D (Sorry, I couldn't resist.)
Answer: Double check your IIS binding to make sure that it allows port 80, (all unassigned) and no host header.  That will get http://localhost.  Check Event Viewer.  If there are any issues, it  should report there.
Also, try a specific page to rule out the default doc settings.  e.g. http://localhost/default.aspx.

IIS 7 Fails to do anything


android how to compare between simpleCursorAdapter and ArrayAdapter

Question: I have an application. I want to optimize that one. how can i do that.
For example I am using simpleCursorAdapter to bind listview and it fetch data from database.
But if i retrieve data from cursor into an string array and then by using ArrayAdapter I can bind listview.
So I want to know which one is the better one means which takes less time to binding or takes less CPU time.
Plz give me the answer.
And if u have any extra tips of code optimization then tell me plz.
Thank you
Comment: Why are you asking other people to measure performance metrics for you, when you should be able to do it easily yourself?
Answer: Please try to test by your self. Have a look on the following steps to check performance difference
Create a sample application where you write both of the technique. also print two print statements for displaying and free heap memory
one statement before calling database
second statement after creation of list view
In this way you can find which technique is better as per your requirement.
Thanks
Deepak


UITableViewCell- how to change selectedBackgroundView, default ImageView, textLabel, detailTextLabel frames

Question: I am creating tableview with row height 100, between each row i want a 5 pixels gap. For that for each row i am adding uiview(width:320px, hight:1px) at row's 95th 'y' position . Now everything is going fine. But when i select the cell the rows selectedbackgroundview covering entire row i. But i want to set rows selectedbackgroundview height as 95.
i tried following way in cellForRowAtIndexPath but no use, please help me out.
cell.selectedBackgroundView.frame = CGRectMake (0, 0, 320, 95);

Comment: You need to reload the table and return the height in the heightForRowAtIndexPath: delegate method.
Comment: http://stackoverflow.com/a/5784367/2043580
Comment: i am using 'heightForRowAtIndexPath', for row height
Comment: You mean you designed tableview that cells show 5 px gap in between them but , when cell is tapped selection effect covers whole cell show you can see the gap?
Comment: @Bhumit: yes, when i tap the cell the selection covering entire cell(height:100px), but in this case selection has to cover 95 px.
Answer: Thanks for your answer, Finally got the solution.
We can adjust the selectedBackgroundView frame by creating the custom cell. Steps to solve the problem.

First we have to create class with UiTableViewCell as a Subclass
Inside that under layoutSubviewsmethod we can change the tableviewcell related view frames        those are selectedBackgroundView, defalut imageView, textLabel, detailTextLabel frames
To change the selecteddBackgroundView frame
 - (void )layoutSubviews {
// always try to set frame in layoutSubviews
[super layoutSubviews];
self.selectedBackgroundView.frame = CGRectMake(10, 0, self.frame.size.width - 20, 88);
 }

To change the textLabel, detailTextLabel Frames
    - (void)layoutSubviews {// always try to set frame in layoutSubviews
    [super layoutSubviews];
    self.textLabel.frame = CGRectMake(0, 0, 50, 20);
    self.detailTextLabel.frame = CGRectMake(55, 0, 225, self.frame.size.height);

   }

Answer: Swift:
override func layoutSubviews() {
    super.layoutSubviews()
    // containerView -> Is a view with constraints in the storyboard where I whish to see the selection
    selectedBackgroundView?.frame = containerView.frame
}

Answer: Just a thought

You can use multiple sections tableview pass array.Count in  numberOfSectionsInTableView
numberOfRowsInSection in each section will be 1
Pass 5px in  heightForHeaderInSection  so that there will be 5px gap between each of the rows
Pass 95 px to  heightForRowAtIndexPath as you want height of cell to be 95 ,
In cellForRowAtIndexPath instead of indexPath.row you will have to deal with indexPath.section

Let me know if i am missing something. I think it will do what you want to achieve. Hope it helps
Comment: Thanks for your answer but found the solution.
Comment: Glad you did :) Can you share it here


Outer Measure limit equality

Question: Suppose M is the class of measurable sets with respect to an outer measure $\mu^*$ defined on the subsets of $\Omega$. Take {$E_n$} to be a monotone increasing sequence of sets in M and A any set in $\Omega$. Prove that:
lim $\mu^*( A \cap E_n)$ = $\mu^*($lim $A \cap E_n)$
(the limits are taken with $n$ going to $\infty$)
I could prove "less or equal" using monotonicity of the outer measure, but I'm having a bit of trouble with the other side.
This is exercise 8 from section 4.1 of S. J. Taylor's Introduction to Measure and Integration

Edit:
$\mu^*$ here is any outer measure, not necessarily an induced one. In such manner, we can't say that for every set $A$ there exists a measurable set that covers it and has the exact same measure. When this property holds, Taylor refers to $\mu^*$ as a "regular outer measure".
Comment: Maybe split into two cases, $\cup_n E_n$ has finite measure or not.
Comment: @Ramiro Unfortunately I don't think it does. This answer relies on that fact that we're using a specific outer measure that is regular, in the sense that we can approximate every set by a measurable one. As it is stated in Taylor's book, my question should be more general.
Comment: OK. I see. The question is about a general outer measure, not necessarily regular one (that is, not an  induced one).
Answer:
Lemma: Let $A \subseteq \Omega$ and $E, F \in M$ such that $E \cap F=\emptyset$, then
$$\mu^*(A \cap (E \cup F)) = \mu^*(A \cap E) + \mu^*(A \cap F)$$

Proof: Since $E \in M$ and $E \cap F=\emptyset$, we have
\begin{align}
\mu^*(A \cap (E \cup F)) &= \mu^*(A \cap (E \cup F) \cap E) + \mu^*(A \cap (E \cup F) \cap E^c) =\\
&= \mu^*(A \cap E) + \mu^*(A \cap F)
\end{align}
$\square$
Now for the main result:
Since for all $n$, $A \cap E_n \subseteq \lim_k A \cap E_k$, we have
$\lim_n \mu^*( A \cap E_n) \leqslant \mu^*(\lim_n A \cap E_n)$.
Now, let $E= \lim_n E_n = \bigcup_n E_n$. Let us define $F_0 = E_0$ and, for each $n$, $F_{n+1} =E_{n+1} \setminus \bigcup_{k=0}^n E_k$. Then the sets $F_n$ are disjoint set and for all $n$, $F_n \in M$. Moreover $E_n= \bigcup_{k=0}^n F_k$ and  $E= \lim_n E_n = \bigcup_n E_n= \bigcup_n F_n$.
So we have
$$\lim_n \mu^*( A \cap E_n) \leqslant \mu^*(\lim_n A \cap E_n)= \mu^* \left (\bigcup_n ( A \cap  F_n) \right ) \leqslant \sum_n\mu^*(A\cap F_n)$$
where the last step is $\sigma$-sub-additivity of $\mu^*$. So we have:
$$\lim_n \mu^*( A \cap E_n) \leqslant \mu^*(\lim_n A \cap E_n)\leqslant \lim_k\sum_{n=0}^k\mu^*(A\cap F_n)  \tag{1}$$
Using the Lemma and induction, we have that for all $k$,
$$\sum_{n=0}^k\mu^*(A\cap F_n)= \mu^*\left (A \cap \bigcup_{n=0}^k F_n \right ) = \mu^*(A \cap E_k) \tag{2}$$
Combining $(1)$ and $(2)$:
$$\lim_n \mu^*( A \cap E_n) \leqslant \mu^*(\lim_n A \cap E_n)\leqslant \lim_k\sum_{n=0}^k\mu^*(A\cap F_n) = \lim_k\mu^*(A \cap E_k)  $$
So $\lim_n \mu^*( A \cap E_n) = \mu^*(\lim_n A \cap E_n)$
Comment: The result does not hold for general outer measures. See problem  2.10.3 in Bruckner, A.M, et. al. Real Analysis, 2nd edition, pp.92.
Comment: @OliverDíaz, If $E_n$ were a monotone increasing sequence of  arbitrary sets, the result would not hold. However,  $E_n$ is a monotone increasing sequence of  sets **in M**, and that is key to make the result hold.
Comment: (+1) Oh! I missed the bit in which the sets $E_n$ are measurable, then of course things go well.
Comment: @OliverDíaz , Thanks!
Comment: Incidentaly, it just so happens that the set function $\mu^*_A:E\mapsto \mu^*(A\cap E)$ for $\mathcal{M}_A:=\{A\cap E: E\in\mathcal{M}_{\mu^*}\}$ is in fact a measure. One can reproduce the steps in the proof of Caratheodory's theorem (your argument goes along those lines), or apply directly Cratheodory's extension theorem: for (1) $\mu^*_A$ is finitely additive in the $\sigma$-algebra $\mathcal{M}_A$, and (b) subadditive.
Answer: I will be using this resource. Feedback appreciated. We start by defining the outer measure $\mu^*:2^X\to [0,\infty]$ with $\mu^*(\emptyset)=0$ and $\mu^*(A)\leq \sum_{n}\mu^*(A_n)$ for all $A\subseteq \cup_nA_n$, inducing the property $\mu^*(A)\subseteq \mu^*(B),\,\forall A\subseteq B$. Then, we define (Definition 1.2) the usual $\mu^*$-measurable sets
$$\mathscr{M}:=\{A\subseteq X:\mu^*(S)=\mu^*(S/A)+\mu^*(S\cap A),\,\forall S \subseteq X\}$$
Further, we can show that for $\mu^*$-measurable $(A_n)_n$ pairwise disjoint, we have (Remark 1.7)
$$\mu^*(S\cap (\cup_nA_n))=\sum_{n \in \mathbb{N}}\mu^*(S\cap A_n),\,\forall S\subseteq X$$
We then obtain similarly to (1.8) that for $\mu^*$-measurable $(E_n)_n$ s.t. $E_n\subseteq E_{n+1}$ and $A\subseteq X$ we get
$$\begin{aligned}\mu^*((\cup_nE_n)\cap A)&=\mu^*((\cup_n(E_n/E_{n-1})\cap A)=\\
&=\lim_{n\to \infty}\sum_{k\leq n}\mu^*((E_k/E_{k-1})\cap A)=\\
&=\lim_{n\to \infty}\mu^*((\cup_{k\leq n}(E_k/E_{k-1}))\cap A)=\\
&=\lim_{n\to \infty}\mu^*(E_n\cap A)\end{aligned}$$
Comment: @OliverDíaz since $E_n$ are measurable, it should work: I just changed the argument of (1.8) in the resource from $\cup_nE_n$ alone to $\cup_nE_n\cap A$. Let me know if you think it doesn't work
Comment: (+1) I missed the bit where the OP mentioned that $(E_n)\subset\mathcal{M}_{\mu^*}$. Of course the whole things works well in such case.
Comment: @OliverDíaz thank you!
Comment: With a little more effort I think you can show that if you apply the Caratheodory construction to subsets of $E$ by restricting $\mu^*$ to $\mathcal{A}_E=\{A\cap E: A\in\mathcal{M}_{\mu^*}\}$ you obtained a measure $\nu^*_E$ on $\mathcal{A}_E$ such that $\nu_*(B)=\mu^*(B)$ for all $B\in\mathcal{A}_E$, that is $\mu*(\cdot E)$ is already a measure on $\mathcal{M}_{\mu^*}$.
Answer: The function $\mu^*_A(B):=\mu^*(A\cap B)$ defines a measure on the $\sigma$-algebra $\mathcal{A}_A:=\{B\cap A: B\in\mathcal{M}_{\mu^*}\}$.
One can reconstruct the steps of Caratheodory's construction (postings of @Ramiro and @Snoop) or apply the Caratheodory extension theorem directly.
Notice that $\mu^*_A$ is finitely additive on $\mathcal{A}_A$. Suppose $B,C\in \mathcal{M}_{\mu^*}$ and such that $A\cap B\cap C=\emptyset$, then
\begin{align}
\mu^*((A\cap B)\cup(A\cap C))&=\mu^*\Big(\big((A\cap B)\cup(A\cap C)\big)\cap B\Big)\\
&\qquad+\mu^*\Big(\big((A\cap B)\cup(A\cap C)\big)\setminus B)\\
&=\mu^*(A\cap B) +\mu^*(A\cap C)
\end{align}
Clearly $\mu^*$ is subadditive; hence, by Caratheodory's theorem $\mu^*_A$ extends to a measure $\nu$ for which each  $B\in\mathcal{A}_A$ is $\nu$-measurable and $\nu(B)=\mu^*(B)$ for all $B\in\mathcal{A}_A$.
The statement of the OP now follows immediately:
\begin{align}
\lim_n\mu^*(A\cap E_n)&=\lim_n\nu(A\cap E_n)=\nu(\bigcup_n(A\cap E_n))\\
&=\nu(A\cap\bigcup_nE_n)=
\mu^*(A\cap\bigcup_nE_n)
\end{align}

Notes:

If the assumption that $(E_n)\subset\mathcal{M}_{\mu^*}$ is dropped, the
the statement still hols for for outer measures $\mu^*$ for which
$$\mu^*(E)=\inf\{\mu^*(A): A\in\mathcal{M}_{\mu^*},\, E\subset A\}$$
Here is a proof: Let $C_n=A\cap E_n$. $C_n$ is a monotone sequence and $C_n\nearrow C=A\cap\bigcup_nE_n=\bigcup_n A\cap E_n$. Clearly  $\mu^*(C_n)\leq \mu^*(C)$.
If $\lim_n\mu^*(C_n)=\infty$, there is nothing to prove.
Suppose $\lim_n\mu^*(C_n)<\infty$.
For each $n$, there is a measurable set $B_n$ such that $C_n\subset B_n$ such that $\mu^*(C_n)=\mu(B_n)$ (why?).
Let $B'_n=\bigcap^\infty_{k=n}B_n$.  Then $C_n\subset B'_n$ for each $n$ and $\mu^*(C_n)=\mu(B'_n)$. The sequence $B'_n$ monotone nondecreasing and so
$$\lim_n\mu^*(C_n)=\lim_n\mu(B'_n)=\mu(B), \quad\text{where}\quad B=\bigcup_nB'_n$$
Since $C\subset B$, $\lim_n\mu^*(C_n)\leq \mu^*(C)\leq\mu(B)$; thus $\mu^*(C)=\mu(B)$.

For the why? notice that of for any set $A$, if $\mu^*(A)<\infty$, then by definition of outer measure, for any $n$ there is a measurable set $B_n$ such that $A\subset B_n$ and
$$\mu(B_n)<\mu(A)+2^{-n}$$
Set $B=\bigcap_nB_n$.

For a general outer measure, the result does not hold unless the sequence $(E_n)\subset\mathcal{M}_{\mu^*}$. Here is an example. Let $\Omega=\mathbb{N}$, define $\mathcal{T}=\{\{n\}, \Omega, \emptyset: n\in\Omega\}$
and let $\tau:\mathcal{T}\rightarrow[0,\infty]$ by
$\tau(\emptyset)=0$, $\tau(\{n\})=2^{-n+1}$, and $\tau(\Omega)=\infty$.
Define doe any $E\subset \mathbb{N}$
$$\mu^*(E)=\inf\{\sum_n\tau(A_n):A_n\in\mathcal{T}, E\subset\bigcup_nA_n\}$$
Then, for $E\neq\Omega$, $\mu^*(E)=\sum_{n\in E}2^{-n+1}$, and $\mu^*(\Omega)=\infty$.
$E_n=\{1,\ldots,n\}\nearrow\Omega$ and
$$\lim_n\mu^*(E_n)=2<\lim_n\mu^*(\Omega)$$
Comment: @Snoop: one can start with a nonnegative finitely additive and countably subaditive  set function $\mu$ on a semiring $R$, define $\mu^*(A)=\{\sum_n\mu(A_n): A_n\in R \, A\subset\bigcup_nA_n\}$ and work with Caratheodory's extension too.
Comment: Hello @OliverDiaz, is $\mu$ a pre-measure in this context?
Comment: @OliverDíaz thank you! Still, I believe my question should be true for any outer measure. You're using the fact that the measure in Caratheodory's extension is a "regular" outer measure, which is not always the case.
Comment: @OliverDíaz indeed regularity is also used for measures on topological spaces, you're right. My point is exactly on the "why?" part, this is not true for every outer measure - outer measures with such property are sometimes called "regular outer measures". $\mu^*$ is not necessary induced by some measure $\mu$.
Comment: @LeonardoVoltarelli: I initially missed the assumption that the sets in the  increasing sequence are $\mu^*$-measurable. I have corrected that still using directly the Caratheodory extension theorem. I keep the contents of my original solution to show that that assumption is indeed important.

Outer Measure limit equality


Proof with ideals

Question: Question:
Let $R=\mathbb{Z}[X]$ and $I=(2, X) \subset R$. Prove that $X^{2}+4 \in I \cdot I$, but that $X^{2}+4$ cannot be written as $x y$, with $x, y \in I$.
I feel like this question should be very easy.
I am not sure what $I=(2,X)$ means, my textbook is not very clear on this. Product of two ideals $IJ$ is defined as $\{\sum_{i=1}^{n} x_{i}y_{i} : n \in \mathbb{Z}_{\geq 0}, x_{i} \in I, y_{i} \in J\}$.
So is it correct if I say $I\cdot I = \{4, 2X, X^{2}\}$. And $I\cdot I$ is again an ideal so $X^{2} + 4 \in I \cdot I$, since its closed under addition.
Comment: $I$ is the ideal generated by two elements, $2$ and $X$. So using that formula, $X^2+4$ would be in $II$ because it is $X\times X + 2\times 2$. To show why it cannot be written as $xy$, $I$ is an ideal where every element is a polynomial with even constant term (try and see why) and see if you can take it from here
Comment: Please do not use images to convey information not otherwise present in your post. See [here for the reasons](https://math.meta.stackexchange.com/a/34123/742).
Comment: Would $X^{2} + 6$ or $X^{2} + 2k$ with $k \in \mathbb{Z}$ also be in $I \cdot I$?
Comment: That is correct.
Answer: Note that the roots of $X^2+4$ are $\pm 2i$, which clearly are not elements of $\mathbb{Z}$, and so $X^2+4 \in \mathbb{Z}[x]$ is irreducible. That is, we can't write it as a product of elements in $\mathbb{Z}[x]$ that aren't units (which is just the element $1$ in $\mathbb{Z}[x]$).
The ideal $I=(x,2)=\{f\cdot x+g\cdot 2:f,g \in \mathbb{Z}[x]\}$, and so $X^2+4=X \cdot X+2 \cdot 2,$ but $X^2+4$ is irreducible (as described above), and so it can't be factored into two elements of $I$.

Proof with ideals


Calculating the Brier score for multinomial models

Question: I was wondering whether it is possible to calculate the Brier score for multinomial models in R?
For example:
<code>library(nnet)
data(iris)
mlogit <- multinom(Species ~ ., data = iris)
</code>
and given the definition of the Brier score for multinomial model on Wikipedia. I do not believe I can compute the Brier score, because I lack the class probabilities of the non-realized classes for each observation right? Or am I missing something?
Answer: doi:10.1002/sim.5321 may give you some ideas.  I don't think an overall Brier score for polytomous outcomes has been fully worked out.  But at least you could report $k-1$ Brier scores for predicting the probability of $k-1$ out of the $k$ levels of $Y$.
Comment: Dear Frank; A bit of a long shot I am sure but I wonder if you still have any of these references to hand please, given that citeUlike is no more.
Comment: Fixed above - thanks.
Comment: Great, thank you.


How to calculate probability of getting 1 heads in 2 coin flips or 1 heads in 12 flips, and so on

Question: If I wondered about the probability of getting:

Only one heads in two tosses - 2/4
Only one head in three tosses = 3/8 or 37.5%

But I just counted on my fingers, how do you do it for big numbers?
Comment: You're describing the [binomial distribution](http://en.wikipedia.org/wiki/Binomial_distribution).
Answer: For $n$ coin tosses: there are $n$ places where the one heads can appear, and for each such combination, the probability is exactly $2^{-n}$.
So the probability is $n2^{-n}$, giving $2 \times 1/4 = 1/2$ for $n=2$ and $3 \times 1/8 = 3/8$ for $n=3$.
BTW - if you want the probability of getting exactly $k$ heads out of $n$ tosses, then you can expand this to $\binom{n}{k}2^{-n}$. The case of $k=1$ is just a particular case of that.


Pass a Python unittest if an exception isn't raised

Question: In the Python unittest framework, is there a way to pass a unit test if an exception wasn't raised, and fail with an AssertRaise otherwise?
Comment: Possible duplicate of: http://stackoverflow.com/questions/4319825/python-unittest-opposite-of-assertraises
Comment: I've only found the need to do this when testing legacy code and putting up a bunch of sanity tests. These are tests without any Asserts (basically verifying that the code block executes without blowing up). Any unexpected exceptions fail the test anyway - not sure if the Python frameworks works similarly to the xUnit family.
Comment: Does this answer your question? [Python unittest - opposite of assertRaises?](https://stackoverflow.com/questions/4319825/python-unittest-opposite-of-assertraises)
Answer: If I understand your question correctly, you could do something like this:
def test_does_not_raise_on_valid_input(self):
    raised = False
    try:
        do_something(42)
    except:
        raised = True
    self.assertFalse(raised, 'Exception raised')

...assuming that you have a corresponding test that the correct Exception gets raised on invalid input, of course:
def test_does_raise_on_invalid_input(self):
    self.assertRaises(OutOfCheese, do_something, 43)

However, as pointed out in the comments, you need to consider what it is that you are actually testing. It's likely that a test like...
def test_what_is_42(self):
    self.assertEquals(do_something(42), 'Meaning of life')

...is better because it tests the desired behaviour of the system and will fail if an exception is raised.
Comment: Why bother to first catch an exception and then raise a different one?  Just call `do_something()`, and if an exception gets raised, the test automatically fails.  This is also the reason why `assertDoesNotRaise()` does not exist.
Comment: IMHO something like this should be part of the unittest.TestCase class, it's an awkward thing to want, but I can't be the only person who wants it.
Comment: @Levi Campbell: I agree, an `assertDoesNotRaise()` method would be neater. N.B: I have edited my answer since you accepted.
Comment: @Sven Marnach: You are correct and I have updated my answer accordingly. I initially answered the question as posed without giving due consideration as to the nature of the underlying problem.
Comment: No @SvenMarnach is not correct: There is a difference between raising an error and failing a test. If do_something() raises an error in your last version, then the test will exit with an error instead of registering a test failure, which is what you actually want.
Comment: @Alex While test frameworks usually distinguish between tests that raise exceptions and tests that fail assertions in the output, both of these results are considered test failures. And if test code raises an exception when it actually shouldn't, then what's wrong marking the test as an error? To me adding try/except blocks around the code looks like pointless busywork, and I can't see the value it adds.
Answer: Many of the comments on this page treat errors and failures as equivalent, which they are not. The right solution in my opinion is to explicitly fail the test if the exception is raised. E.g.:
def test_does_not_error(self):
    try:
        code_under_test()
    except ThatException:
        self.fail("code_under_test raised ThatException")

Comment: Agree -- while the console output for errors and failures parses comparably by a human read, most automated unit testing tools treat the two quite differently, right?
Comment: It's the default assumption that code does not error out. Tests should test for desired behaviour. I don't see what value the try/except block adds. In fact, it _decreases_ the usefulness of the test, since the output won't include the traceback, which it would if you just let the code fail.
Comment: One value the try/except block adds is that it gives the OP what they were asking for.

I understand it's a matter of preference; this style is my preference over unhandled exceptions.

By catching a specific exception that indicates a known problem, the failure can be understood faster than if one has to scan screenfuls of traceback output.

If this were a real test and not an example, and the traceback or other details of the exception were important, they could be reported in the `self.fail` as well.
Answer: Simply call your functionality, e.g. do_something(). If an unhandled exception gets raised, the test automatically fails! There is really no reason to do anything else. This is also the reason why assertDoesNotRaise() does not exist.

Credit: comment by Sven
Comment: That is not true, As if the method raises an error, then the test cases will be marked as an `error` not a `failure`
Comment: @Acumenus the point isn't to just fix the test, you could in principle fix the test by cheating it. The point is that the purpose of the test is to exactly have you understand what is happening in the code and distinguishing between exceptions, sheer code bugs and failures is fundamental.
Comment: @IslamTaha What difference does it make? Either way it has to be fixed.
Comment: If you cheat with your test, you have bigger problems. For example, if I were to put one foot on the floor when I am checking my weight, then it's not the weighing scale that is to blame.
Answer: I stumbled upon this question while looking for an answer to this obvious problem. Whilst the suggested solutions with try/except are fine, I found that I ended up with uncovered lines of code in coverage and that doesn't sit well with me. So I have come up with another solution, whilst not perfect, works for functions that only throw exceptions.
def check_raises(obj):
    if obj.condition is True:
        raise Exception('Condition is true')

In order to successfully test this function, I have resorted to using assertIsNone. The below code covers both cases.
import unittest

class Object:
    def __init__(self):
        self.condition = None

class TestCheckRaises(unittest.TestCase):
    def test_check_raises_exception(self):
        obj = Object()
        obj.condition = True
        self.assertRaises(Exception, check_raises, obj)

    def test_check_raises_no_exception(self):
        obj = Object()
        obj.condition = False
        self.assertIsNone(check_raises(obj))

I am with the original poster that a assertNotRaises would be nice, but failing that, assertIsNone is perfectly acceptable for functions that do not return a value.


Single-Sign-On (SSO) for JavaScript Excel custom functions?

Question: Custom functions (https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-overview) execute in a runtime different from the usual office-js runtime for, i.e., task pane add-ins. Task pane add-ins can use 'Office.context.auth.getAccessTokenAsync' for SSO but as far as I can see there is no such function available for custom functions add-ins.
I'm aware that custom functions add-ins can open a dialog for authorization but this is not the same as SSO where no prompt for credentials would be required.
Is there a way to perform SSO within a custom functions add-in?
Answer: I'm afraid that SSO is not yet supported in custom functions. You will have to implement your own login dialog and, optionally, pass the token to the task pane by storing it in AsyncStorage.
Comment: Thanks Rick, sounds like an authoritative answer. 'Not yet' looks promising :)


Duplicate SQL model into Ruby on Rails postgresql model

Question: I am very new to Ruby on Rails development. Recently, there was a request to integrate an external database as part of our application. However, we were given SQL statements copied and pasted in a .docx file.
Example:
USE [portal]
GO
/****** Object:  User [admin]    Script Date: 9/11/2018 11:28:54 AM ******/
CREATE USER [admin] WITHOUT LOGIN WITH DEFAULT_SCHEMA=[admin]
GO
/****** Object:  Schema [admin]    Script Date: 9/11/2018 11:28:54 AM ******/
CREATE SCHEMA [admin]
GO
/****** Object:  Table [admin].[ApplicationEnterprise]    Script Date: 9/11/2018 11:28:54 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [admin].[ApplicationEnterprise](
    [ApplicationID] [varchar](15) NOT NULL,
    [ApplicationType] [varchar](50) NULL,
    [Level] [varchar](15) NULL,
 CONSTRAINT [PK_Enterprise] PRIMARY KEY CLUSTERED
(
    [ApplicationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

.....
What is the best way for me to integrate this database into my application? I have cleaned up the SQL statements by removing "GO" and the [] etc. So far, my approach is to rewrite these statements into command lines to generate models.
Example:
rails g model ApplicationEnterprise ApplicationID:string ApplicationType:string Level:string
Is this the right approach?
Answer: I would suggest, to go with the schema options. I mean you first need to convert your sql statements in to the required format of schema.rb.
Then generate models from schema. Following article may help you to proceed.
https://codeburst.io/how-to-build-a-rails-app-on-top-of-an-existing-database-baa3fe6384a0
Comment: Thank you, I would try rewriting the statements for a start!


Adding to the denominator of two fractions

Question: Say I am working with one fraction larger than another and only in the domain of positive fractions.For example, let's say I have $\frac{20}{20}$ and $\frac{50}{80}$. Clearly $\frac{20}{20}$ is the larger fraction. If I add 1 to both denominators, $\frac{20}{21}$ still remains larger than $\frac{50}{81}$.
What I want to prove or disprove is that the difference between the original fractions and their respective new fractions (after adding 1) is always bigger (or equal to?) for the originally bigger fraction. So in this case $\frac{20}{20} - \frac{20}{21}$ is larger than $\frac{50}{80} - \frac{50}{81}$. Is that true in general cases as well if the one fraction is larger than the other and can I prove it if so? I've been trying a few examples on paper and it seems to hold but I don't really know how to make a formal proof of this.
Answer: This is not true in general. Take, for instance, the fractions $\dfrac88$ and $\dfrac12$. Again, the first one is the largest. But$$\frac88-\frac89=\frac19\text{ and }\frac12-\frac13=\frac16.$$And $\dfrac19<\dfrac16$.
Comment: Thank you for the counterexample!


escaping html tags inside xslt:value-of select

Question:
I am converting text inside a XML document element (which also contains other texts not only a hyperlink) to hyperlink using the following:
<xsl:value-of
     select="replace(AUTHOR_CONTACT_INFORMATION,
                     '(firstname.lastname@example.com)',
                     '<a href="$1">$1</a>')"/>

XML Source:
<AUTHOR_CONTACT_INFORMATION>Plugin author can be reached at email@example.com for his email.</AUTHOR_CONTACT_INFORMATION>

Unfortunately, I cannot escape the '<' & '>' tags used in a href. My XSLT processor is Qt4's QXmlQuery class. It seems it doesn't support 'disable-output-escaping' attribute in the above expression and I can't seem to find any other way than to manually parse the final output and replace each '&lt' & '&gt' with '<' & '>' using C++ code.
PS: Couldn't get 'analyse-string' to work in qt either. It just returns empty string. Refered to http://www.dpawson.co.uk/xsl/rev2/regex2.html question 3 and used the following:
<xsl:analyze-string select="AUTHOR_CONTACT_INFORMATION" regex="(email@example.com)">
    <xsl:matching-substring>
        <xsl:value-of select="." />
    </xsl:matching-substring>

    <xsl:non-matching-substring>
        <xsl:value-of select="." />
    </xsl:non-matching-substring>
</xsl:analyze-string>

The above works fine in 'Altova XMLSpy' doing exactly what I want. But in Qt4, the output has empty string (To be more accurate my  tag before this expression is also mysteriously gone in the output, weird). Qt4 documentation says its processor supports 'xsl:analyze-string'. Any one have a working example of 'xsl:analyze-string' in Qt?
Qt4 documentation says its processor doesn't support 'xsl:character-map' so no point going there.
Without 'xsl:analyze-string' working I am back to square one with 'replace()'.
-Sanjeev
Comment: I'm bad with 2.0, but may be [xsl:character-map](http://www.w3.org/TR/xslt20/#dt-character-map) can be helpful.
Comment: You can't create tags by generating `<` like this. You'll need to output an actual tag (i.e. `(regex match)`.
Comment: What is your input, what output do you want to create? It might be that the `xsl:analyze-string` http://www.w3.org/TR/xslt20/#analyze-string can help if your aim is to parse plain text with a regular expression to build a link element from it in the output.
Comment: Good question, +1. See my answer for explanation and for a proper way to do this.
Comment: @Sanjeev: From http://www.w3.org/TR/xslt20/#element-value-of: *The `xsl:value-of` instruction is evaluated to construct a new text node; the result of the instruction is the newly constructed text node.* **You can't output elements nor element's tags from an instruction for output text nodes.** You are right about you must use `analyze-string` instruction.
Comment: Thanks guys for answering. I have added more info in my original post. Please re-read it.
Comment: @Sanjeev: Whenever you define this question properly, you can get an XSLT 1.0 solution that *might* work with Qt4, as you have shown that it isn't a compliant XSLT 2.0 processor. Right now you haven't provided enough relevant information and the question in its current form has been completely answerd in my answer.
Answer:
Hi all, I am converting text inside a
  XML document element to hyperlink
  using the following:
<xsl:value-of select="replace(AUTHOR_CONTACT_INFORMATION,

'(RegEx here)', '$1')"
Unfortunately, I cannot escape the '<'
  & '>' tags used in a href

The short answer: You shouldn't even try to do that.
Escaping markup is demoting it to one-dimensional text and it will only show as text in a browser.
The proper way to do this is to generate the markup as  (a sequence of) literal result elements:
<xsl:template match="AUTHOR_CONTACT_INFORMATION">
  <xsl:value-of select="someExpr2"/>
</xsl:template>

UPDATE: The OP has provided more information about the real problem. The problem is that thie following is "not working" on his XSLT processor -- Qt4 ???
<xsl:analyze-string select="AUTHOR_CONTACT_INFORMATION" regex="(firstname.lastname@example.com)">
    <xsl:matching-substring>

            <xsl:value-of select="." />

    </xsl:matching-substring>
    <xsl:non-matching-substring>
        <xsl:value-of select="." />
    </xsl:non-matching-substring>
</xsl:analyze-string>

I have verified that this codes behaves as expected and produces the expected result when run under Saxon 9.1.05.
This means that Qt4 is not a compliant XSLT 2.0 processor.
Here I can offer the following alternative solution, which works both with an XSLT 1.0 processor and an XSLT 2.0 processor:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="AUTHOR_CONTACT_INFORMATION">
  <xsl:value-of select=
   "substring-before(., 'firstname.lastname@example.com')"/>
  firstname.lastname@example.com
  <xsl:value-of select=
   "substring-after(., 'email@example.com')"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:
<AUTHOR_CONTACT_INFORMATION>Plugin author can be reached at email@example.com for his email.</AUTHOR_CONTACT_INFORMATION>

the wanted, correct result is produced (with all 8 different XSLT processors I have at hand):
Plugin author can be reached at firstname.lastname@example.com for his email.

Comment: I am not sure how this will help Dimitre. Where do I put my RegEx? May be my question wasn't clearer. I have added more info on my original post. Could you please re-read it?
Comment: @Sanjeev: I have updated my answer and am providing an alternative solution that might work with your problematic XSLT processor.
Comment: @Dimitre: Apparently, 'email@example.com' isn't the only thing I wanna convert to hyperlink. It's just an example. What I wanna convert to 'a href' ranges from hyperlinks to email addresses so the solution should be capable of having Regular Expressions to find and replace those into 'a href' tag. Again, there might be multiple hyperlinks and email addresses. For example: The author's email is email@example.com and his weblink is [http://something.com/](http://something.com/)
Comment: @Sanjeev: Then you need to re-define your question, and define it well this time. You are obviously out of luck with Qt4 -- BTW, I've never heard of such XSLT processor -- are you sure it is an XSLT **2** processor?. Anyway, this thing could be possible to do in pure XSLT 1.0 if you define your problem well. I have been doing for years tokenization, justification, spelling-checking of text, so your tasks sounds not more complex than these.
Comment: @Dimitre: I agree that my problem shouldn't be complex to solve but somehow I've managed to get stuck in this problem for two days now. The question is simple, I wanna extract all email and hyperlinks from a text element of XML using **Regular Expressions** and replace them with HTML 'a href's. You've probably not heard about [Qt](http://qt.nokia.com/products/) is because it's a C++ cross-platform library for writing desktop application and only parts of it is related to web technology.
Comment: @Sanjeev: This is not a question -- just a statement. I assume that your question is "How to do this with Qt4". This question is not an XSLT question at all, because you have shown evidence that Qt4 is not a compliant XSLT (2) processor. If you want to try Qt4 as an XSLT 1.0 processor, then you must ask for an XSLT 1.0 solution.
Comment: @Dimitre: Then what could be an XSLT 1.0 solution?
Comment: @Sanjeev: I already gave you one XSLT 1.0 solution in my answer. If you specify better your problem, then you will get corresponding XSLT 1.0 solutions, too. What is under question is whether your Qt4 ??? will function as a compliant XSLT 1.0 processor.


How can I solve this dplyr select last_col error?

Question: on the following R query, why I get the error message?
library(dplyr)
df %>%
    select(c(1:3), last_col(5:0))

>>> Result error message
> Error in `select()`:
> ! Problem while evaluating `last_col(5:0)`.

I've been using same query well on my own, but it doesn't work on another laptop. If i erase last_col() function, it is working. Maybe last_col function is the problem, but i can find any solution. What should i do?
it is working :
df %>%
    select(c(1:3))

and it didn't work :
df %>%
    dplyr::select(c(1:3), last_col(5:0))

Comment: I think you need `last_col(5)` meaning select 1,2,3 ... and up to 5th column from last
Answer: Your error message is caused by improper use of last_col(). The : operator shouldn't be used within last_col(), but last_col() can be used with select and the : operator. Can you tell us which columns exactly you're trying to select?
More information on last_col() here: https://dplyr.tidyverse.org/reference/select.html
EDIT: Added package versions and reproduced error message.
#library(pak)
#pak::pak("tidyverse/tidyverse")
library(tidyverse)
library(tidyselect)
packageVersion("tidyverse")
#> [1] '1.3.2'
packageVersion("tidyselect")
#> [1] '1.2.0'

data(mtcars)

mtcars %>% names()
#>  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
#> [11] "carb"

mtcars %>% select(c(1:3), last_col(5:0)) %>% names()
#> Error in `select()`:
#> ! Problem while evaluating `last_col(5:0)`.

mtcars %>% select(c(1:3), last_col(5)) %>% names()
#> [1] "mpg"  "cyl"  "disp" "wt"

mtcars %>% select(1:last_col(5)) %>% names()
#> [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"

mtcars %>% select(last_col(5)) %>% names()
#> [1] "wt"

mtcars %>% select(last_col()) %>% names()
#> [1] "carb"
Created on 2022-11-02 with reprex v2.0.2

Comment: Weird, `mtcars %>% select(c(1:3), last_col(5:0))` works on my machine. It's clearly an undocumented use though, which would explain the inconsistent behavior.
Comment: @zephryl interesting, I edited my post to include package versions and the reproduced error message, AFAIK I have the most updated versions of `tidyverse` and `tidyselect`.
Comment: sorry for late. and i solved it with this query : `last_col(5):last_col(0)`. It's really weired some things work and some thing don't.


trouble with oidentd on CentOS 6.3

Question:
I'm having a weird problem with the oident daemon on my VPS.
When I try running it, I keep getting this error:

[root@ldvps ~]# oidentd
  [line 4] This construct is valid only for user configuration files
  Error reading configuration file

I also made sure that it reads the correct oidentd.conf from /etc/oidentd.conf by typing

oidentd -c /etc/oidentd.conf

but I get the same error.
Here's my oidentd.conf file:
# Configuration for oidentd
# see oidentd.conf(5)
#

default {
        default {
                allow spoof
                allow spoof_all
                allow spoof_privport
                allow random
                allow random_numeric
                allow numeric
                allow hide
        }
}

There's either something I'm not doing right or there's really a problem with the oidentd.
Any help or other suggestions would be appreciated.
Thank you.
Answer: Your /etc/oidentd.conf should look like the following:
default {
    default {
        allow spoof
        deny spoof_all
        deny spoof_privport
        allow random_numeric
        allow numeric
        allow hide
    }
}

user root {
    default {
        force reply "UNKNOWN"
    }
}

user username {
    default {
        allow spoof
        allow spoof_all
        allow spoof_privport
    }
}

You could define per user configuration. Issue the following
vi ~/.oidentd.conf
global { reply "nickname" }
to irc.freenode.net { reply "freenode" }

Comment: now I got a syntax error at line 1...
Comment: Please provide more information. You either have a typo or have not run oidentd correctly. Provide the full error so could debug it easily.
Comment: so I updated /etc/oidentd.conf with the one you provided and and then typed this onto ssh: oidentd -c /etc/oidentd.conf

here's the log:
[root@ldvps ~]# oidentd -c /etc/oidentd.conf
[line 1] syntax error
Error reading configuration file
Comment: first line is the `default` word. Here starts the definition of the file. This cannot be a syntax error. How did you install oidentd? Did you use rpm/yum  or installed it from source and if so, what flags did you use during the compilation time?
Comment: I used yum. -> yum install oidentd
Comment: Did you change file permissions? does your file contain ^M characters ?  You can find this out by typing `cat -A /etc/oidentd.conf`
Comment: oh.. it seems to have ^M characters. how do I remove that?
Comment: `tr -d '\r' copy_oidentd.conf; mv copy_oidentd.conf oidentd.conf`

trouble with oidentd on CentOS 6.3


Show that the ratio between two numbers is always proportional to the the maximum percentage error of their average?

Question: The question is this: if we have a set of any random consecutive numbers, for example {1, 1.2, 4.2, 4.8, 5.6, 7.4, 9.8} then how can we prove that calculating the ratio between each of the numbers and picking the largest ratio will give the largest percentage error between the average of the two numbers and the numbers themselves.
Additionally we define the domain of the set to be $$x > 0$$
In this example, you would take the ratio 1.2/1 = 1.2, 4.2/1.2 = 3.5, 4.8/4.2= 1.143..., 5.6/4.8=1.161..., 7.4/5.6= 1.321..., 9.8/7.4=1.324... .
We can see that the largest ratio is 3.5, so we assume that the average of 4.2 and 1.2 = 2.7, will have the largest percentage error w.r.t. either 4.2 or 1.2.
The percentage error would be equal to the difference between the average and either of the two numbers (which in any case will be equal to half the difference between the two numbers) divided by the average itself:
Average: $$((4.2+1.2)/2)$$
Percentage error: $$\frac{((4.2-1.2)/2)}{((4.2+1.2)/2)}$$
Now, instead substituting numerical values for letters,the problem boils down to the following:
Prove that the greatest or least value of $$x/y$$ will always give you the greatest or least value of $$\frac{((x-y)/2)}{((x+y)/2)}$$ which is also equal to $$\frac{(x-y)}{(x+y)}$$
Comment: Can we assume the random numbers are positive, or something along those lines?  What happens if you can select both $x$ and $-x$?
Comment: This is false as stated.  Suppose your random numbers are $\{-1.01,1,2\}$.  Then the maximal ratio is $2=\frac 21$ but your error function is maximized by taking $F(-1.01,1)=\frac {-1.01-1}{-1.01+1}=\frac {2.01}{.01}=201$.
Comment: Of course, lulu, it seems you are correct. The formulae are not valid for negative numbers or cases where x and -x are taken as the numbers needed. I will restrict the domain of the set to account for this. Thank you.
Comment: If you assume the random numbers are all positive, then the statement is true.  I will post a solution below.
Comment: Something is wrong here. Assume $0 < y < x$. You state that the ratio $\frac{x}{y}$ is **proportional** to something you call a percentage error, given by $\frac{x - y}{x + y}$. In other words, you claim that there is a **proportionality constant** $c > 0$ such that $\frac{x}{y} = c \cdot \frac{x - y}{x + y}$. This is equivalent to $c = \frac{x(x+y)}{y(x-y)}$. However, $\frac{3(3+2)}{2(3-2)} = \frac{15}{2} \neq \frac{6}{1} = \frac{2(2+1)}{1(2-1)}$ shows that $c$ is **not constant**. So we have a contradiction, and your statement must be false.
Comment: Hi, sorry - I used the word "proportional" very loosely, and what I really meant to say was that if given all ratios of $y/x$ in ascending order you could assume that the percentage error of the average w.r.t. either y or x would be in the same order.
Answer: Assume the values are positive.
Consider the function $$F(z)=\frac {z-1}{z+1}$$
It is easy to differentiate:  $$F'(z)=\frac 2{(z+1)^2}$$  The derivative is strictly positive so the function is strictly increasing (at least for $z>-1$).  Thus it reaches its maximum when $z$ is maximal, and its minimum when $z$ is minimal.  But taking $z=\frac xy$ we see that this is your "maximal error" function.
Comment: No problem.  Your test function is homogeneous....i.e.  $F(x,y)=F(\lambda x, \lambda y)$ for non-zero $\lambda$.  That means it is a function of the ratio. Once you know that then you just have to look at how it grows as a function of the ratio.
Comment: How do you prove the same is true however, for values of $y \neq 1$?
Comment: In my expression, $z=\frac xy$.  I have rewritten your error function in terms of the ratio (by multiplying numerator and denominator by $\frac 1y$. That is to say, your error function evaluated at the point $(x,y)$ equals mine evaluated at $\frac xy$.  As to the max/min, I believe I meant it as I wrote it.
Comment: I understand now! Thank you! Also, I'm interested to know how you solved this so quickly? What was your thought process, especially on the key point of setting z=x/y?


Apple Developer Account 100 devices limit is over?

Question: Kindly let me know what are the best options if 100 devices limit is over in Apple Developer account and we need to add more UDIDs?
Comment: Look into testflight
Comment: Remove old unused device UDIDs, this the only way to do it if you want to test it internally, however you should always use TestFlight to distribute apps, it doesn't required UDID, so it will keep the limit in control.
Comment: Hello, do you know if it is really over? It seems it is only allowed 3 devices per account
Answer: The limit is 100 devices per device type, which means that you can register 100 iPhones, 100 iPads, 100 Apple TVs and 100 Apple Watches to your developer account. Assuming that registering devices using UDIDs is for development purposes, these numbers are pretty enough. You can send test builds using Testflight which allows for external testing up to 1000 users with up to 10 devices each. Note that external testing requires a beta review for the first build of each version of your app.
If you hit the limit of 100 iPhones in your account, you can delete the UDIDs you do not use and free space when your account renewal time comes.
Comment: Deleting UDIDs won't help right now because 6months are remaining for renewal period.Testflight is nice solution as of now but also I am thinking to take another developer account because client is not too much technical.
Comment: Testflight is much easier for sending test builds that custom udid based solutions.


Solving a circular dependency - C

Question: I checked SO for duplicates of this, but was unable to find an exact solution for my problem.
I have a header file NvCommon.h where I use an enum NV_DATA_TYPE. This enum is defined in another header NvDefs.h where I use a number of structs and enums from NvCommon.h. I can't build this due to circular dependency. I know that forwrd declaring enum is not possible.
In this situation what could be done? Is this a problem with my design? Do I have to introduce another header file to solve this?
I am no C expert. Please help me. My design may have issues and I know can fix this circular dependency by introducing another header file. What I would like to know is "is that the only way around". Looking for alternate solutions if available.
I will post the full code if it is helpful.
Comment: Placing enums on separate file works just fine.
Comment: Or, provide your code so that we can reproduce the problem easily.
Comment: Could you confirm whether you have include guards around all your header files
Comment: Or, move the definition of `enum NV_DATA_TYPE` to `NvCommon.h`
Comment: @camelccc : Thanks. Guards were present.
Comment: Side note : A bounty of 50 has been given to @PegasusEpsilon for his effort, even though the solution given by him does not address my problem properly.
Answer: It can be useful to define enums in their own file(s), and if you do that here, your problem will disappear.
Comment: Thanks. I will do this if there are no better options.
Answer: If I understand your question correctly, you've got something like this:
derpfoo.h:
#ifndef DERPFOO_H
#define DERPFOO_H

#include "derpbar.h"

typedef struct {
        char *nothing;
} FOO;

BAR foo (BAR derp) {
        return derp;
}

#endif

derpbar.h:
#ifndef DERPBAR_H
#define DERPBAR_H

#include "derpfoo.h"

typedef struct {
        char *nothing;
} BAR;

FOO bar (FOO derp) {
        return derp;
}

#endif

and then a simple derp.c:
#include "derpfoo.h"
#include "derpbar.h"

int main (void) {
        return 0;
}

A friend of mine presented me with this problem in some SDL code a while ago, and it took me a while to understand both why he was doing what he was doing and how to fix it reasonably.
The intention of separating the code like this is that derpfoo and derpbar are logically separate, but they are also, sadly, mutually dependent. The simplest solution I've found to such a thing is to combine them and split them according to anatomy rather than logic like so:
derpstructs.h:
#ifndef DERPSTRUCTS_H
#define DERPSTRUCTS_H

typedef struct {
        char *nothing;
} FOO;

typedef struct {
        char *nothing;
} BAR;

#include "derpfunctions.h"

#endif

derpfunctions.h:
#ifndef DERPFUNCTIONS_H
#define DERPFUNCTIONS_H

#include "derpstructs.h"

BAR foo (BAR derp) {
        return derp;
}

FOO bar (FOO derp) {
        return derp;
}

#endif

and still a simple derp.c:
#include "derpstructs.h"
#include "derpfunctions.h"

int main (void) {
        return 0;
}

Note that derpstructs.h includes derpfunctions.h at the end rather than at the beginning. This is not, strictly speaking, necessary, but if you do intend to have them include each other, you must include the function definitions after the struct definitions that they depend on, in all possible inclusion paths. Moving on...
This solution works, but it's not exactly sticking with the original philosophy that caused the problem to begin with -- that the two parts are logically separate, and should be kept so in the code.
The answer to both is to split everything up further, and tweak the inclusion paths even more.
derpfoostructs.h includes derpbarstructs.h first and then defines struct FOO and then at the end optionally includes derpfoofunctions.h and derpbarfunctions.h.
derpbarstructs.h includes derpfoostructs.h first and then defines struct BAR and then at the end optionally includes derpfoofunctions.h and derpbarfunctions.h.
derpfoofunctions.h includes derpfoostructs.h and derpbarstructs.h first, then includes derpbarfunctions.h, and then defines its functions.
derpbarfunctions.h includes derpfoostructs.h and derpbarstructs.h first, then includes derpfoofunctions.h, and then defines its functions.
derp.c includes derpfoostructs.h and derpbarstructs.h and then includes derpfoofunctions.h and derpbarfunctions.h, and then goes on to do whatever else it needs to do.
This satisfies both of the desired requirements. It eliminates circular dependencies, and still maintains logical separation of the two logically separate code units. You get two files to edit when you change from project to project instead of one, but it at least keeps the mutable code apart from the immutable. That, and it's the only solution I've found.
Hope this helped. Good luck on your projects.
Comment: @NeonGlow Let me know if you need more details or just a code dump of the four-include solution. The key, really, is to think about how it would flow if it was all one file, and realize that the C preprocessor makes it literally that, and then the compiler gets hold of it. So you can split your code up completely insanely, so long as the include path stitches it all back together into something legible for the compiler.
Comment: This is OK. Enough inputs here. I may do the homework reordering things.:)
Answer: Circular dependencies might mean that you're overdesigning your interface. Merge both files into Nv.h. If this trivially solves the problem, this means you were incorrectly designing the interface.
Comment: in that case you probably want to order things so NvDefs.h includes NvCommon.h Why do you want to include stuff from a file that won't change into one that will?
Comment: The file NvCommon.h contains defintions that will not change across projects and NvDefs.h contains stuff that will/may change across projects. That is how this division comes.
Comment: If `NV_DATA_TYPE` changes on a project base, it should not be used in defintions that shall be constant over projects. So `NV_DATA_TYPE` shall then **not** be used in `NvCommon.h`.
Answer: I tried modeling this problem based on your description.  In my implementation, I tested three things (1) declaring but not defining NV_DATA_TYPE in NvDefs.h, (2) declaring and defining NV_DATA_TYPE in NvDefs.h, and (3) defining NV_DATA_TYPE in NvDefs.h, but declaring it NvCommon.h.  Also, as your description provided, I created some structs in NvCommon.h and accessed those objects in NvDefs.h.  In every case--with and without guards in the header files--the code compiled and executed with correct results.
Is it possible that your circular dependency is somewhere else in your header files besides the NV_DATA_TYPE enum?
Comment: The problem is in these two headers. Moving the enum itself will solve the problem. The only thing that is holding me from doing this is the enum wont logically fit there.
Answer: Check this out
How to  properly declare and define variables, libraries, functions , etc. This might be relevant.

Solving a circular dependency - C


How to pass array structure between two verilog modules

Question: I am trying to pass a array structure as reg [0:31]instructionmem[0:31] between two modules.
I coded it as follows :
Module No 1:
<code>       module module1(instructionmem);
            output reg [0:31]instructionmem[0:31];
            ------------------
            ----lines of code---

            ---------------
       endmodule
</code>
Module No 2:
<code>         module module2(instructionmem);
           input [0:31]instructionmem[0:31];
           --------------------------------
           -----line of code---------------
           -------------------------------
           endmodule
</code>
Testbench:
<code>     module test_bench();
     wire [0:31]instructionmem[0:31];

     module1 m1(instructionmem);
     module2 m2(instructionmem);
     endmodule
</code>
I am getting errors for this implementation. So how can we send such array structures ?
Comment: have you tried defining as `output/input reg/wire [31:0]instructionmem[0:31];`, ie switching the order of the width definition.
Comment: ya i tried, but that does not work either.
Comment: I believe this is only supported in SystemVerilog, have you enabled SystemVerilog mode sometimes by using .sv file extension or running with a -sv flag
Answer: This is not possible in Verilog. (See sec. 12.3.3, Syntax 12-4 of the Verilog 2005 standard document, IEEE Std. 1364-2005.)
Instead you should "flatten" the array and pass it as a simple vector, e.g.:
<code>module module1(instructionmem);
  output [32*32-1:0] instructionmem;
  reg [31:0] instructionmem_array [31:0];

  genvar i;
  generate for (i = 0; i < 32; i = i+1) begin:instmem
    assign instructionmem[32*i +: 32] = instructionmem_array[i];
  end endgenerate
endmodule

module module2(instructionmem);
  input [32*32-1:0] instructionmem;
  reg [31:0] instructionmem_array [31:0];

  integer i;
  always @*
    for (i = 0; i < 32; i = i+1)
      instructionmem_array[i] = instructionmem[32*i +: 32];
endmodule

module test_bench(instructionmem);
  output [32*32-1:0] instructionmem;
  module1 m1(instructionmem);
  module2 m2(instructionmem);
endmodule
</code>


Docker user as root for Azure App Service

Question: Docker is usually supposed to be run as a non-root user for production applications. My understanding is that this is because having root access in the container also gives you root access on the server.
Does the same apply when deploying through Azure's app service? I don't understand the difference between having a root user on a server vs. a container service.
Answer: App Service uses port 2222 for SSH into your app's container, but that doesn't mean that port 2222 is exposed over the Internet. No matter how you use SSH in your app, all SSH traffic is handled through an endpoint on port 443.
-As a side note, if you're not using SSH, you don't have to worry about closing port 2222 because it's not exposed to the Internet.
The root password must be exactly Docker! as it is used by App Service to let you access the SSH session with the container. This configuration doesn't allow external connections to the container.
(Port 2222 of the container is accessible only within the bridge network of a private virtual network and is not accessible to an attacker on the internet.)
In order to access the SSH port, as one must first login to the Kudu container via HTTPS/it's not exposed to the Internet.
Linux apps in App Service run in their own containers. No access to the host operating system is allowed, you do have root access to the container. Likewise, for apps running in Windows containers, you have administrative access to the container but no access to the host operating system.
See, these docs for more details:
tutorial-custom-docker-image and configure-custom-container
Comment: Additionally, You shouldn't install components using SSH because they won't persist. "In general it's not recommended to install stuff over SSH since App Service instances are ephemeral so any time there is a VM rotation your app would be broken in that new instance requiring you to SSH and install the component again."
If you want to install a particular component, make sure that you do it in a Dockerfile so that the component is included in your Docker image. See this documentation for full information on how to do that.
Comment: wow, Thank you @AjayKumar-MSFT.
that exactly answers the security concerns i was having while setting the port 2222 on Dockerfile.


Why will there always be this term in $(x+h)^n$?

Question: I am trying to understand why the expression $(x+h)^n$ will always have a term $n\times h\times x^{n-1}$ in this proof for the power rule and am not understanding what the proof in the image below means when it says 'take $x$ from all but one factor and h from the remaining factors', as well as 'selecting $h$ from at least two factors'. What is meant by taking and selecting $x$ and $h$ by factors?
Comment: Hint: binomial theorem.
Comment: When you multiply $(x+h)^n$ out, you select $x$ or $h$ from each of the $n$ $(x+h)$ terms. This gives $2^n$ monomials in $x,h$. Selecting all $x$s gives $x^n$. Selecting all $x$s except for one $h$ gives $n$ terms $h x^{n-1}$, $x h x^{n-2} ( = h x^{n-1})$, etc, etc.
Comment: I am not sure what you are asking in the last comment. When you multiply out $(x+h)^n$ there are $2^n$ terms, as you can select/choose $x$ or $h$ from each of the $n$ terms. There will be $\binom{n}{k}$ entries of the form $x^k h^{n-k}$.
Comment: thank you- so 'select' in this context means 'choose to be included in an expression multiplying everything selected together'?
Answer: I think the answer to

What is meant by taking and selecting  and ℎ by factors?

is, essentially, the distributive law. When you multiply out
$$
(a+b)(c+d) = ac + ad + bc + bd
$$
the four terms in the expansion correspond to pairing each of the two summands in $a+b$ with each of the two in $c+d$. When you expand the product of three binomials $(a+b)(c+d)(e+f)$ there will be $8$ terms. starting with $ace$.
When you expand $(x+h)^n$ there will be $2^n$ terms. Each will have some $x$'s and some $h$'s. Precisely $n$ of them will have one $h$ and $n-1$ $x$'s.
The binomial theorem (referred to in other answers and comments) tells you precisely how many of the terms are of each of the forms $x^kh^{n-k}$.
Answer: Hint: For $h \ne 0,$ if $f(x)=x^N,$ then using the Binomial Theorem, we get
$$\frac{f(x+h)-f(x)}{h} = \frac{(x+h)^N - x^N}{h} = \frac{\left(\sum_{n=0}^N \binom{N}n x^{N-n} h^n \right)-x^N}{h}=\sum_{n=1}^N \binom{N}n x^{N-n} h^{n-1}.$$ So when you take the limit as  $h \rightarrow 0,$ which term in the above sum remains ?


Best way to include jQuery into TYPO3 backend

Question: I've read, what jQuery use could provoke some conflicts in TYPO3 backend. But in the same time, ExtJS proposes jQuery adapter to use these 2 frameworks together.
What will be the most safe, efficient and transparent way to include jQuery and it's plugins into TYPO3 Backend (4.5,4.6,4.7) ? If there are already some extensions, which realizes it ?
Answer: I've contacted Jürgen Furrer, the author of T3 jQuery. He adviced to use the following method using his extension :
if (t3lib_extMgm::isLoaded('t3jquery')) {
    require_once(t3lib_extMgm::extPath('t3jquery').'class.tx_t3jquery.php');
    $path_to_lib = tx_t3jquery::getJqJSBE();
    $script_to_lib = tx_t3jquery::getJqJSBE(true);
}

Answer: I think this is safer in terms of knowing which version of JQuery you are using. So in a template you would add:
page.includeJS {
    file1 = fileadmin/templates/project1/js/app.js
}


Classification of Imbalanced and Streaming Time Series Data

Question: I have a question about classification of time series. Data has two features and I want to classify it into 5 classes. We have a stream of data and new data is generated every 5 seconds. Moreover in some classes we have inadequate data for training so we have classification problem with imbalanced data. I want to classify new data using machine learning methods according to the pattern shown in the figures. What methods do you suggest?
Answer: Your datastream looks more like a regression problem for me.
And in case you are trying to make a classification problem I suggest labelling the segments by hand, since it seems that you have a certain idea what the segments should represent.
Otherwise positive slope (green) and negative slope (pink) can be easily estimated and thus resemble a feature vector.


Proof that moment generating functions uniquely determine probability distributions

Question: Wackerly et al's text states this theorem "Let $m_x(t)$ and $m_y(t)$ denote the moment-generating functions of random variables X and Y, respectively. If both moment-generating functions exist and $m_x(t) = m_y(t)$ for all values of t, then X and Y have the same probability distribution." without a proof saying its beyond the scope of the text. Scheaffer Young also has the same theorem without a proof. I don't have a copy of Casella, but Google book search didn't seem to find the theorem in it.
Gut's text seems to have an outline of a proof, but doesn't make reference to the "well-known results" and also requires knowing another result whose proof is also not provided.
Does anyone know who originally proved this and if the proof is available online anywhere? Otherwise how would one fill in the details of this proof?
In case I get asked no this is not a homework question, but I could imagine this possibly being someone's homework. I took a course sequence based on the Wackerly text and I have been left wondering about this proof for some time. So I figured it was just time to ask.
Comment: **Related**: (i) [Inversion of mgfs](http://stats.stackexchange.com/a/29024/2970) and (ii) [Existence of the moment generating function and variance](http://stats.stackexchange.com/q/32706/2970)
Comment: If you have access to Billingsley's *Probability and Measure* text, this is discussed in a section entitled, I believe, "The method of moments". (Apologies for the vagueness, as I don't currently have it at hand.) If I recall correctly, the proof he uses relies on the corresponding results for characteristic functions, though, which may not be completely satisfying. This is certainly (well) outside the scope of the expected background of Wackerly's text.
Comment: Concerning the history ("who originally proved this?"), it appears Laplace was using the characteristic function for this kind of work in 1785 and had developed the general inversion formula (which is the key to the proof) by 1810.  See Anders Hald, [A History of mathematical Statistics from 1750 to 1930](http://www.amazon.com/History-Mathematical-Statistics-1750-1930/dp/0471179124), chapter 17.
Comment: Wow @cardinal your answers to those questions were superior and very helpful thank you and thanks for the text recommendation I should get a hold of a copy.
Comment: Just a remark that the 'other result' *is* proved in Gut, since this property is a consequence of the inversion formula which is proved there.
Answer: The general proof of this can be found in Feller (An Introduction to Probability Theory and Its Applications, Vol. 2). It is an inversion problem involving Laplace transform theory. Did you notice that the mgf bears a striking resemblance to the Laplace transform?. For use of Laplace Transformation you can see Widder (Calcus Vol I) .
Proof of a special case:
Suppose that X and Y are random varaibles both taking only possible values in {$0, 1, 2,\dots, n$}.
Further, suppose that X and Y have the same mgf for all t:
$$\sum_{x=0}^ne^{tx}f_X(x)=\sum_{y=0}^ne^{ty}f_Y(y)$$
For simplicity, we will let $s = e^t$
and we will define $c_i = f_X(i) − f_Y (i)$ for $i = 0, 1,\dots,n$.
Now
$$\sum_{x=0}^ne^{tx}f_X(x)-\sum_{y=0}^ne^{ty}f_Y(y)=0$$
$$\Rightarrow \sum_{x=0}^ns^xf_X(x)-\sum_{y=0}^ns^yf_Y(y)=0$$
$$\Rightarrow \sum_{x=0}^ns^xf_X(x)-\sum_{x=0}^ns^xf_Y(x)=0$$
$$\Rightarrow\sum_{x=0}^ns^x[f_X(x)-f_Y(x)]=0$$
$$\Rightarrow \sum_{x=0}^ns^xc_x=0~∀s>0$$
The above is simply a polynomial in s with coefficients $c_0, c_1,\dots,c_n$. The only way it can be zero for all values of s is if $c_0=c_1=\cdots= c_n=0$.So, we have that $0=c_i=f_X(i)−f_Y(i)$ for $i=0, 1,\dots,n$.
Therefore, $f_X(i)=f_Y(i)$ for $i=0,1,\dots,n$.
In other words the density functions for $X$ and $Y$ are exactly the same. In other other words, $X$ and $Y$ have the same distributions.
Comment: Mainly The Moment Generating Function Uniquely Determines the Distribution.
Answer: The theorem you are discussing is a basic result in probability/measure theory.  The proofs would more likely be found in books on probability or statistical theory.  I found the analogous result for characteristic functions given in Hoel Port and Stone pp 205-208
Tucker pp 51-53
and Chung pp 151-155 This is the Third Edition.  I have the second edition and am referring to the page numbers in the second edition published in 1974.
The proof for the mgf I found to be more difficult to find but you can find it in
Billingley's book "Probability and Measure" pp. 342-345. On page 342 Theorem 30.1 provides the theorem that answers the moment problem. On page 345 Billingsley states the result that if a probability measure has a moment generating function M(s) defined on an interval surrounding 0 then the hypothesis for Theorem 30.1 is satisfied and hence the measure is determined by its moments. But these moment s are determined by M(s).  Hence the measure is determined by its moment generating function if M(s) exists in a neighborhood of 0.  So this logic along with the proof he gives for Theorem30.1 proves the result. Billingsley also comment that the solution to exercise 26.7 on page 305 is an alternative proof of the uniqueness theorem for moment generating functions.
Comment: Where is this in Chung? Did you mean pages 161-165, by chance? Even so, that deals with *characteristic functions*, not *moment-generating functions*, as requested by the OP.
Comment: @cardinal Yes I know.  I mentioned the result for characteristic functions because that is what i have found thus far.  As I said the page numbers in Chung are based on the second edition that i have.  I do not know where it appears in the third edition.  I think there should be some sources that will have the result for mgfs.
Comment: I upvoted, because I appreciate your answer too so thank you for taking the time.
Answer: Denote the moment generating function of $X$ by $M_X(t)=Ee^{tX}$.

Uniqueness Theorem. If there exists $\delta>0$ such that $M_X(t) = M_Y(t) < \infty$ for all $t \in (-\delta,\delta)$, then $F_X(t) = F_Y(t)$ for all $t \in \mathbb{R}$.

To prove that the moment generating function determines the distribution, there are at least two approaches:

To show that finiteness of $M_X$ on $(-\delta,\delta)$ implies that the moments $X$ do not increase too fast, so that $F_X$ is determined by $(EX^k)_{k\in\mathbb{N}}$, which are in turn determined by $M_X$. This proof can be found in Section 30 of Billingsley, P. Probability and Measure.
To show that $M_X$ is analytic and can be extended to $(-\delta,\delta)\times i\mathbb{R} \subseteq \mathbb{C}$, so that $M_X(z)=Ee^{zX}$, so in particular $M_X(it)=\varphi_X(t)$ for all $t\in\mathbb{R}$, and then use the fact that $\varphi_X$ determines $F_X$. For this approach, see Curtiss, J. H. Ann. Math. Statistics 13:430-433 and references therein.

At undergraduate level, almost every textbook works with the moment generating function and states the above theorem without proving it. It makes sense, because the proof requires far more advanced mathematics than undergraduate level allows.
At the point when students have all the tools needed in the proof, they also have the maturity to work with the characteristic function $\varphi_X(t)=Ee^{itX}$ instead. Almost every graduate textbook takes this path, they prove that the characteristic function determines the distribution and basically ignore moment generating functions altogether.
Comment: Indeed! And yet I have never seen a textbook that emphasizes numerical methods but has deep enough math to give a proof of the Uniqueness Theorem.
Comment: Today, mgfs shouldnt be ignored as thry are much more useful numerically than the characteristic function
Comment: Curtiss' approach is exercise 26.7 in Billingsley (3rd edition)
Comment: @PeterArndt Yes, indeed. But it is quite convoluted, and it refers to 21.17, which in turn refers to 16.6. It would be good to see a complete sketch of how to "solve" this "exercise".


Can Dart conditional imports use names?

Question: Consider a conditional import statement. The following comes from the Dart language guide:
import 'src/hw_none.dart'
    if (dart.library.io) 'src/hw_io.dart'
    if (dart.library.html) 'src/hw_html.dart';

Is there a syntax to add a name to these imports? For example, I'd like to say something like the following:
import 'src/hw_none.dart' as my_prefix
    if (dart.library.io) 'src/hw_io.dart' as my_prefix
    if (dart.library.html) 'src/hw_html.dart' as my_prefix;

Unfortunately, the above doesn't compile. I haven't been able to find a variation that does compile.
Is there a way to name conditionally imported packages?
Answer: I've done something like this a few month ago, to implement mobile and web functionalities. Seems like you cannot name each import separately.
import 'package:flutter_fcm_web_example/notification_helper.dart';
import 'firebase_mobile_messaging.dart'
    if (dart.library.html) 'firebase_web_messaging.dart' as notifInstance;

abstract class NotificationEncapsulation {
  static NotificationHelper get instance =>
      notifInstance.FirebaseMessagingHelper();
}

Comment: "dart.library.js" is not a valid conditional import.  Only two: dart.library.io, and dart.library.html.
Comment: Edited my answer with the html library, thanks for the remark.

Can Dart conditional imports use names?


How to get Q & A of a webform submission?

Question: Main goal is to get user filled in form into a pdf. Got my pdf & sending it with email. But I cant figure out how to get Q & A from a submission. I have sid of submission. I tried
<code>      $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
  $webform_submission = $storage->loadByProperties([
    'entity_type' => 'webform',
    'entity_id' => 'questionnaire',
  ]);
  $submission_data = array();
  foreach ($webform_submission as $submission) {
    $submission_data[] = $submission->getData();
  }
</code>
Webform is not attached to node.
Thanks
Comment: I am not able to understand your question.  Are you asking how do I load a single webform submission by its sid? Or are you trying to load all the webform submissions for a specific webform node?
Comment: Hi Jrockowitz, I want to load a single webform submission by its sid. Thanks
Answer: Try below code:
<code>module_load_include('inc','webform','includes/webform.submissions');
$sid = 10; //Replace this value with your dynamic sid value
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;

$web_submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
$output = webform_submission_render($node, $web_submission, NULL, 'html');

print $output;
</code>
Comment: I think that would work for drupal 7.
Comment: Yes, You are correct the above code will work for Drupal 7. Please check my another answer for Drupal 8
Answer: For Drupal 8, webform submissions are content entities so you just need to call...
<code>\Drupal\webform\Entity\WebformSubmission::load($sid)
</code>
Comment: How do I get Q label and A label? only getting value ids
Comment: You are going to have to load the Q and A element via \Drupal\webform\Entity\Webform::getElement($key) and use the element's #title and #options or for Likert element's the #questions and #answers.
Answer: Try below code for Drupal 8:
<code> $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
 $webform_submission = $storage->loadByProperties([
    'entity_type' => 'node', //Entity type = node
    'entity_id' => 1234, // Your Dynamic Node ID
 ]);
 $submission_data = array();
 foreach ($webform_submission as $submission) {
    $submission_data[] = $submission->getData();
 }
</code>