Calculating the probability of a fire incident

Question: I am currently working on a solution to a dataset that I have been given based on probabilities though I require some further guidance on the calculation.
For example, I have a dataset with the number of fire incidents for a district. I want to calculate the probability of a fire incident occurring within a 2km radius of a fire station given the number of buildings within that radius.
Let's say the total number of fires in this district is 80 in a month. The total number of buildings within the fire-station radius is 200, and the total number of buildings within the entire district is 15000.
What is the probability that one or more of those fires belong to the buildings within the fire-station radius?
It is not necessarily like rolling dice however I thought this approach could be taken: $n = 15000$, then $k = 80$ however given that we are looking at those within the 200 buildings, I was thinking something like:
$\frac{15000!}{(15000-80)\cdot200^{80}}$?
My reasoning for the equation:
I presumed that given a total population size $=15000$ ,then selecting the difference of population size and $k$ occurrences of incidents and finally $\frac{1}{200^{80}}$
$80$ represents the selection and $200$ the number of samples of interest. Though this may be a better equation when calculating for fires occurring in the same building? i.e. sampling with replacement.
Secondary Approach:
Perhaps calculating the daily probability relative to a month helps. Hence, $80/30$ ~ $2.6$ which is equivalent to $\frac{1}{30}$. We know that the sample space is $n = 15000$, and $m = 200$ is a subset of the sample space. What is the probability that in any given day, more than 1 incidences have occurred within $m$.
Given the potential of more than one station in a district, then perhaps a hypergeoemetric distribution works well in this case?
$\frac{\binom{z}{k}\binom{m}{y}\binom{15000-z-m}{80-k-y}}{\binom{15000}{80}}$
Where $z$ represents another fire-station in the district independent to the previous fire-station, and $y$ is the proportion of incidences.
Extra information:

We assume each incident is independent and happening to unique buildings. 2. Again we assume each logged incident is unique. 3. We do not know if they have caught on fire more than once in the month, again we assume uniqueness here also. 4. Presumingly those closer to the station probably have a lower rate of an incident. On this assumption, we could add a weight to those closer to the station by every 100m, the closer then the lower the probability.

Data collection:
Fire stations collected from here:
https://www.datadaptive.com/?pg=5
Fire incidents collected from here:
https://www.gov.uk/government/statistics/fire-statistics-incident-level-datasets
UK administrative boundaries here:
https://www.ordnancesurvey.co.uk/business-government/products/boundaryline
Buildings in UK:
https://www.ordnancesurvey.co.uk/business-government/products/open-zoomstack
Methodology:
Plotting the number of station across the UK on QGIS while overlaying the boundaries data to gather the administrative districts. Secondly, uploading the buildings from the open-zoom stack. Lastly, creating a buffer around each station for a 2km radius and counting the number of buildings within the buffer, and counting the number of buildings within each district.
Given that the fire incidence dataset does not have coordinates, we just take the total count of fires in a district.
More than one fire-station may be within the same district, is this something to account for - if so, how could this be interpreted?
Comment: Simply that homes, offices, farms, factories, &c. may well be at significantly different risk of fire. The age of the building, & the financial/demographic attributes of the occupants (where it's a residential property) may well be relevant too.
Comment: (1) Does each incident relate to a single building? Or in some cases to several buildings, or to none? If to a single building, were multiple incidents logged when a fire spread among buildings? Have some buildings caught fire more than once? Can you safely assume the rate of fire incidents per building was much the same within 2km of the fire station as without that radius? (2) Could you please explain your derivation of the formula for the probability of one or more incidents' occurring within 2km of the fire station? Have you tried to evaluate it?
Comment: Thank you. Could you please edit this information into the question? It would also help to explain what data is available or obtainable: e.g. presumably locations of buildings, from your comment; but presumably not locations of fire incidents. (Buildings "closer to the station probably have a lower rate of an incident" - I don't see why that would be, unless "incident" means a fire's getting out of control rather than being promptly extinguished by fireman who are able to arrive soon after the call. I was think more of different kinds of land/building use within the district.)
Comment: @Scortchi-ReinstateMonica You ask brilliant questions! I am aiming for a simple estimate. To answer your questions:
1. We assume each incident is independent and happening to unique buildings.
2. Again we assume each logged incident is unique.
3. We do not know if they have caught on fire more than once in the month, again we assume uniqueness here also.
4. Presumingly those closer to the station probably have a lower rate of an incident. On this assumption, we could add a weight to those closer to the station by every 100m, the closer then the lower the probability.
Comment: @Scortchi-ReinstateMonica Looking back at the formula it does not represent the question too well. Perhaps it's even completely way off as the values are not what I expected. I presumed that given a total population size $n = 15000$, then selecting the difference of population size and $k$ occurrences of incidents and finally $\frac{1}{200^{80}}$ where $k$ represents the selection and $n$ the number of samples of interest. Though this may be a better equation when calculating for fires occurring in the same building? i.e. sampling with replacement.
Comment: @Scortchi-ReinstateMonica I have edited the question; as for the data these are taken from various sources but its still under process as I require to filter the data in QGIS. I will upload the links to the dataset in the question and my methodology for getting the data if this helps.
Comment: @Scortchi-ReinstateMonica Tell me more about the different land/building use as I think this idea has much potential for me. Although I wish not to overcomplicate this too much
Comment: With regard to multiple fire stations in a district: what probability are you interested in, in this case?
Answer: Let $n_1$ be the no. buildings in a given district located within a 2 km radius of a fire station, & $x_1$ the no. incidents linked to those buildings; let $n_2$ be the no. buildings in the district located without that radius, & $x_2$ the no. incidents linked to those buildings.
Given the assumptions that the incidents are independent, with each linked to a unique building, & at most one incident per building, you might want to consider them as independent Bernoulli random variables with common probability parameter $\pi$; then the joint mass function for $x_1$ & $x_2$ is
$$
\Pr\left(X_1=x_1, X_2=x_2\right)={n_1 \choose x_1}\pi^{x_1}(1-\pi)^{n_1-x_1} \cdot
{n_2 \choose x_2}\pi^{x_2}(1-\pi)^{n_2-x_2}
$$
Let $T= X_1 +X_2$; you've observed $T=t$, so you need the conditional mass function
$$\Pr\left(X_1=x_1|T=t\right) =\frac{ {n_1 \choose x_1}{n_2 \choose t-x_1}}{n_1+n_2 \choose t}
$$
—$X_1|T$ has a known hypergeometric distribution, regardless  of the unknown true value of $\pi$.
If you wanted to throw out the assumption of at most one incident per building, you could consider them as independent Poisson random variables with common rate parameter $\lambda$, following @RCarnell; then the joint mass function for $x_1$ & $x_2$ is
$$
\Pr\left(X_1=x_1, X_2=x_2\right)=\frac{(\lambda n_1)^{x_1}\exp(-\lambda n_1)}{x_1!} \cdot \frac{(\lambda n_2)^{x_2}\exp(-\lambda n_2)}{x_2!}
$$
and the conditional mass function is
$$\Pr\left(X_1=x_1|T=t\right) ={t \choose x_1} \left(\frac{n_1}{n_1+n_2}\right)^{x_1}\left(1 - \frac{n_1}{n_1+n_2}\right)^{t - x_1}
$$
—$X_1|T$ has a known binomial distribution, regardless of the unknown true value of $\lambda$.
Fires serious enough to merit calling out the fire brigade are, fortunately, rather rare occurrences for an individual building; so the two models won't differ greatly. For the example you provide:—
<code>n1 <- 200
n2 <- 15000 - n1
t <- 80
x1 <- 0

1 - dhyper(x1, n1, n2, t)
# 0.6592815
1 - dbinom(x1, t, n1/(n1 + n2))
# 0.653067
</code>
I imagine most fires, in the U.K. at any rate, arise from unconnected accidents—you forget about the chip-pan, drop your lit pipe down the side of the  arm-chair, leave the wireless on till a valve overheats—& so the independence assumption seems reasonable. Of more concern is the assumption of a common probability/rate parameter; there's no guarantee that the area round a fire station is typical of the district. Buildings might be detached houses, blocks of flats, barns, factories, offices; might be new, or decades old; might be built from straw, or sticks, or solid bricks: such characteristics affecting fire risk will doubtless exhibit some degree of spatial clustering.  Depending on what other information you can get, you may sometimes be able to make a case that your calculated probability is about right, or that it's an under- or an over-estimate.

With $k$ fire stations in a district, each building falls into one of at most $2^k$ sets (e.g. for $k=2$: within 2 km of no fire stations, of the 1st fire station only, of the 2nd fire station only, or of both fire stations); the conditional distribution $\Pr(X_1=x_1, \ldots, X_{2^k-1}|T=t)$ becomes a multivariate hypergeometric, or a multinomial, distribution. Of course if you want to calculate only, say, the probability of one or more incidents within 2 km of any fire station, you can just define two sets of buildings appropriately.
Answer: Goal:  Probability of a fire incident within a 2 km radius of a fire station
Data:  $x$ fires in $N$ homes per month.  There are $m$ homes within a 2 km radius
$P$(one or more fires within a 2 km radius in a month)$ = 1 - P$(exactly zero files within a 2 km radius within a month)
Assume the occurrence of a fire in a home is distributed as a Poisson random variable
$P$(k events in interval t)$ = \frac{(rt)^k}{k!} e^{-(rt)}$
$P$(0 events in a month) = $\frac{(\frac{x}{N}m)^0}{0!} e^{-(\frac{x}{N}m)}$
R Code:
<code># exact calc
1 - exp(-80/15000*200) = 0.6558462

# simulation
set.seed(103400)
x <- sapply(1:10000, function(z) rbinom(n = 200, size = 1, prob = 80/15000))
y <- apply(x, 2, function(x) all(x == 0))
1 - mean(y)
# 0.6557
</code>
Comment: Other (unstated) assumptions are (a) that all fire incidents are independent; (b) the rate of incidents is the same at every home; and (c) the rate per unit time does not vary.  With sufficient data, these assumptions can be checked (and ought to be if one wants defensible results). You also don't solve the stated problem: you approximate a conditional probability with an unconditional probability based on estimates.  That works, but requires justification. Why not use the hypergeometric probability instead? In your formulas could you explicitly indicate what "$r,$" "$t,$" and "$k$" refer to?


React-apollo mutation writeQuery doesn't update ui

Question: I learn GraphQL with howtographql.com, but when use mutation for vote the UI doesn't update. I use readQuery and writeQuery on store, after search I test  use readQuery and writeQuery on client but doesn't work again.
Package use and version :
├─ email@example.com
├─ firstname.lastname@example.com
├─ firstname.lastname@example.com
├─ firstname.lastname@example.com
├─ email@example.com
├─ firstname.lastname@example.com
├─ email@example.com
├─ firstname.lastname@example.com
├─ firstname.lastname@example.com
├─ email@example.com
├─ email@example.com
LinkList.js
import React, { Component } from 'react';
import Link from './Link';
import { Query } from 'react-apollo';
import gql from 'graphql-tag';

export const FEED_QUERY = gql`
    {
        feed {
            links {
                id
                createdAt
                url
                description
                postedBy {
                    id
                    name
                }
                votes {
                    id
                    user {
                        id
                    }
                }
            }
        }
    }
`

class LinkList extends Component {
    _updateCacheAfterVote = (store, createVote, linkId) => {
        const data = store.readQuery({ query: FEED_QUERY })

        const votedLink = data.feed.links.find(link => link.id === linkId)
        votedLink.votes = createVote.link.votes

        store.writeQuery({ query: FEED_QUERY, data })
    }
    render() {
        return (
            <Query query={FEED_QUERY}>
                {({ loading, error, data }) => {
                    if (loading) return
Fetching

                     if (error) return
Error

                    const linksToRender = data.feed.links

                    return (

                            {linksToRender.map((link, index) => (
                                <Link
                                    key={link.id}
                                    link={link}
                                    index={index}
                                    updateStoreAfterVote={this._updateCacheAfterVote}
                                />
                            ))}

                    )
                }}
            </Query>
        )
    }
}

export default LinkList

Link.js
import React, { Component } from 'react'
import { AUTH_TOKEN } from '../constants'
import { timeDifferenceForDate } from '../utils';
import { Mutation } from 'react-apollo';
import gql from 'graphql-tag';

const VOTE_MUTATION = gql`
    mutation VoteMutation($linkId: ID!) {
        vote(linkId: $linkId) {
            id
            link {
                votes {
                    id
                    user {
                        id
                    }
                }
            }
            user {
                id
            }
        }
    }
`

class Link extends Component {
    render() {
        const authToken = localStorage.getItem(AUTH_TOKEN)
        return (

                    {this.props.index + 1}
                    {authToken && (
                        <Mutation
                            mutation={VOTE_MUTATION}
                            variables={{ linkId: this.props.link.id }}
                            update={(store, { data: { vote } }) =>
                                this.props.updateStoreAfterVote(store, vote, this.props.link.id)
                            }
                        >
                            {voteMutation => (

                                    ▲

                            )}
                        </Mutation>
                    )}

                        {this.props.link.description} ({this.props.link.url})

                        {this.props.link.votes.length} votes | by{' '}
                        {this.props.link.postedBy
                            ? this.props.link.postedBy.name
                            : 'Unknown'}{' '}
                        {timeDifferenceForDate(this.props.link.createdAt)}

        )
    }
}

export default Link

Comment: No, the mutation work correctly without error but doesn't update UI
Comment: Is there any error or warning shown in the console after the mutation runs?
Answer: I change _updateCacheAfterVote function like this and it's work
_updateCacheAfterVote = (store, createVote, linkId) => {
    const data = store.readQuery({ query: FEED_QUERY })
    data.feed.links.find(link => link.id === linkId).votes.push(createVote)
    store.writeQuery({ query: FEED_QUERY, data })
}


Bug ao adicionar elementos à lista e transforma-la em string

Question: Estou tento dor de cabeça no decorrer de um mini-projeto para desenvolver um jogo da forca, na função que retornaria a string contendo a palavra escondida, mostrando apenas as letras adivinhadas. Já tentei de tudo, já pesquisei sobre transformar em string com a função str() e join(), caso tenham uma outra sugestão para o código, também vai ajudar muito. Segue o código:
def char_check(char, word):
    newWord_list = []
    newWord_ = ''
    for i in range(0, len(char)-1):
        if char == word[i]:
            newWord_list.append(char)
        else:
            newWord_list.append('_'))
    newWord_ = ''.join(newWord_list)
    return newWord_

Comment: `char` é para ser apenas uma letra, certo? Se sim, a função não está entrando no loop já que `len(char)-1`=0
Answer: Além do já explicado sobre o laço de iteração...
for i in range(0, len(char) - 1):

...que deveria ser modificado para...
for i in range(0, len(word) - 1):

... seu código está desproporcionalmente verboso a dificuldade da tarefa a ser realizada.
Use uma expressão regular para esconder as letras ainda não descobertas de uma string.
A função re.sub(pattern, repl, s, count=0, flags=0) faz a substituição na string s dos caracteres encontrados pelo padrão de correspondência pattern pela string repl.
O padrão de correspondência [^caracteres] instrui a expressão a corresponder todos os caracteres exceto aos caracteres entre [^ e ].
A flag re.IGNORECASE executa uma correspondência que não diferencia maiúsculas de minúsculas.
A função re.escape(pattern) escapa caracteres especiais no padrão pattern aqui usada para prevenir a injeção de metacaracteres no padrão para evitar trapaças.
import re

def char_check(char, word):
    return re.sub(fr"[^{re.escape(char)}]", "_", word, flags=re.IGNORECASE)

Exemplo:
>>> print(char_check("p","Paralelepipedo"))
P_______p_p___

Teste o exemplo abaixo no ideone.com
import re
import random

def char_check(char, word):
    return re.sub(fr"[^{re.escape(char)}]", "_", word, flags=re.IGNORECASE)

palavra = random.choice(["Python", "Haskell", "Javascript", "Scheme", "Lisp", "Visual Basic", "Clipper", "Assembly", "Cobol", "Forth" ])
tentativas = " "

print("Você tem cinco tentativas.\n")
print(char_check(tentativas, palavra))
print("\n")
for i in range(1,6):
    tentativas += input(f"Tentativa {i}: ")
    jogada = char_check(tentativas, palavra)
    print(jogada)
    if jogada == palavra:
        print("!!!TEMOS UM VENCEDOR!!!")
        break
else:
    print("Você morreu enforcado")

#Você tem cinco tentativas.

#_____

#Tentativa 1: p
#_____
#Tentativa 2: m
#_____
#Tentativa 3: o
#_o___
#Tentativa 4: frth
#Forth
#!!!TEMOS UM VENCEDOR!!!

Answer: O problema do seu código está no bloco de repetição. Você está utilizando o tamanho da string char — que teoricamente deve conter apenas um caractere — na função range() como ponto de parada, quando deveria estar utilizando o tamanho da string word.
for i in range(0, len(word) - 1):
    ...

Além disso, um outro problema do seu código, ainda na mesma linha, é a utilização da subtração -1 no ponto de parada da função. Você não deve subtrair o valor do stop, porque a função define esse valor como o seu limite "definitivo". Veja o exemplo abaixo:
list(range(5))      # [0, 1, 2, 3, 4]
list(range(5 - 1))  # [0, 1, 2, 3]

Dito isso, o seu código deveria ficar assim:
def char_check(char, word):

    newWord_list = []
    newWord_ = ''

    # O valor padrão de "start" é zero. Sendo assim, não precisa especificá-lo.
    for i in range(len(word)):

        if char == word[i]:
            newWord_list.append(char)
        else:
            newWord_list.append('_')

    newWord_ = ''.join(newWord_list)
    return newWord_

Além disso, é possível melhorar ainda mais a sua função, sem precisar criar uma nova lista. Para isso, percorra cada caractere da sua string através do laço for e verifique se a letra é a mesma de char. Se sim, adicione-a para a nova string. Se não, adicione a string "_". Veja como ficaria:
def char_check(char, word):

    new_word = ""

    for letter in word:
        if char == letter: new_word += char
        else: new_word += "_"

    return new_word

É possível também fazer tudo isso em apenas uma única linha, utilizando list comprehension, da seguinte forma:
 def char_check(char, word):

    return "".join([char if char == letter else "_" for letter in word])


Weird list assignment

Question: I'm trying to write program that will find all palindromes in a word. For example word "radar" has got 2 palindromes radar and ada. We skip single letters, so r, a, d, etc. aren't palindromes.
import copy

def ILEP(word):
    lista = list(word)
    counter = 0
    pali = []
    def isPalindrome(listaWord):
        backup = copy.deepcopy(listaWord)
        backup.reverse()
        a = ''.join(backup)
        b = ''.join(listaWord)
        if(a == b):
            return True
        else:
            return False

    for i in range(len(lista)):
        current = [lista[i]]
        for j in range(i+1, len(lista)):
            current.append(lista[j])
            if(isPalindrome(current)):
                print(current)
                pali.append(current)
                counter+=1
    print(pali)
    return counter
print(ILEP("radar"))

The program is finding all palindromes correctly, but it assings them wrong to the list pali. Console:
['r', 'a', 'd', 'a', 'r']
['a', 'd', 'a']
[['r', 'a', 'd', 'a', 'r'], ['a', 'd', 'a', 'r']]
2

As U can see it prints palindromes ['r', 'a', 'd', 'a', 'r'] and ['a', 'd', 'a'], but the list pali has got wrong value [['r', 'a', 'd', 'a', 'r'], ['a', 'd', 'a', 'r']]
Answer: You are changing your list current after appending to pali. You have to make a copy:
def is_palindrome(word):
    return word[::-1] == word

def ILEP(word):
    pali = []
    for i, ch in enumerate(word):
        current = [ch]
        for ch in word[i+1:]:
            current.append(ch)
            if is_palindrome(current):
                print(current)
                pali.append(current[:])
    print(pali)
    return len(pali)

print(ILEP("radar"))

Comment: can U explain to me the `is_palindrome` function?
Comment: `word[::-1]` gives a copy of `word` in reversed order.

Weird list assignment


Custom data generator

Question: I have a standard directory structure of train, validation, test, and each contain class subdirectories.
...
  |train
      |class A
          |1
              |1_1.raw
              |1_2.raw
              ...
          |2
              ...
      |class B
          ...
  |test
      ...

I want to use the flow_from_directory API, but all I can find is an ImageDataGenerator, and the files I have are raw numpy arrays (generated with arr.tofile(...)).
Is there an easy way to use ImageDataGenerator with a custom file loader?
I'm aware of flow_from_dataframe, but that doesn't seem to accomplish what I want either; it's  for reading images with more custom organization. I want a simple way to load raw binary files instead of having to re-encode 100,000s of files into jpgs with some precision loss along the way (and wasted time, etc.).
Answer: Tensorflow is an entire ecosystem with IO capabilities and ImageDataGenerator is one of the least flexible approaches. Read here on How to Load Numpy Data in Tensorflow.
import tensorflow as tf
import numpy as np

DATA_URL = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz'

path = tf.keras.utils.get_file('mnist.npz', DATA_URL)
with np.load(path) as data:
  train_examples = data['x_train']
  train_labels = data['y_train']
  test_examples = data['x_test']
  test_labels = data['y_test']

train_dataset = tf.data.Dataset.from_tensor_slices((train_examples, train_labels))
test_dataset = tf.data.Dataset.from_tensor_slices((test_examples, test_labels))

Comment: I specifically want to load in small batches, because there is too much training data to hold in memory at one time. I don't really need too much flexibility here, just want to imitate the mentioned API. I guess you have a good point, I'll take a look at more generic TensorFlow stuff rather than stick to Keras.

Custom data generator


How can I get some more RDBMS features but still use SQLite?

Question: I've decided to use SQLite for my personal development project, because it just sprung up out of my computer seemingly of its own volition and I wanted to learn more about it. The problem is, I'm starting to really miss a lot of the features I'm accustomed to with heavyweight RDBMS's: stored programs, constraints, DRI, complex datatypes like DateTime, etc.
I really like the "database as a file" concept, but I'm finding myself implementing a lot of integrity features from scratch as I go along.
So, as the title says, I'm curious: are there more features built into the product that I just don't know about? Are there tools or libraries (preferably for .Net) that add in features as-needed? Is there another version out there that's a little more robust?
I'm using Mono 2.4 and Mono.Data.SQLite.
Answer: There's at least a few ways to enforce foreign key constraints.  That page explains how to do it using triggers, and it links to at least two sites that will convert your normal foreign key constraint to a trigger, programmatically, for you.
Because SQLite uses manifest typing, you can store any type in any column.  You don't precisely need "complex datatypes like DateTime," because you can store a blob (serialized data) anywhere, or you can store whatever you want as a string.  Note that there are a number of datetime functions in the SQLite core as well -- they just operate on numbers or strings (or both, due to automatic casting), depending on the function.  There's not a real need for a date "type" when a string suffices here.  That's one of the ways SQLite remains so small and portable.
Answer: I think the clue is in the name, SQLite!
It's designed to have just enough functionality for embedded use, but little else. But it's fine to layer on additional functionality if your application needs it.
There are alternative databases you could embed though.
Answer: SQLite unfortunately just doesn't support some of the nice features you're used to.  You just have to get used to working without them, if you want to use it.
However, there are other single-file DBs that work this way.  For example, VistaDB supports Mono (it's 100% managed), and provides stored procedures, constraints, etc.  It shares most of the same feature set as MS SQL, including having a very similar interface (although there are subtle differences).
Answer: Some of the features you mention are there mostly because of the usual client/server separation.  with an embedded DB library like SQLite, it's no longer client/server, it's a layered architecture.
For example, stored procedures.  What difference does it make if SQLite manages them or if your program does it? they're both on the same process and the same memory space!  it's just a layer on top of the storage.  Even better, you can use your own language instead of some 'proceduralized SQL'.  Likewise for complex types and constraints.
just a few caveats:

You have to write the missing layers, SQLite doesn't provide them.  (OTOH, they'll be specific to your taste and needs).
To really handle constraints in your own layer you have to be sure to do all accesses through your layer.
Comment: Maybe the user actually WANTS the stored procs!  Maybe they have more than one app using the same database (even as a file) and want to encapsulate the logic into the database...
Comment: @Jason Short: as with any feature, if you want it, choose the products that have it.  My post aims only to explain why on an embedded DB stored procedures aren't as important as on a DB server.
Comment: Still, in your example (with more than one app using the same DB), the 'business logic' layer would be encapsulated in a library, shared by all apps.  You still get the benefits of using the same language and the best performance both in the DB<->logic and logic<->app interfaces.


Change of Summation and Differentiation

Question: I am looking explicitly for a proof that that infinite summation of sequence of functions, uniformly convergent and differentiation are interchangable.
$$\frac{\mathrm{d}}{\mathrm{d}x}\sum_{n=1}^{\infty}f_n(x)=\sum_{n=1}^{\infty}\frac{\mathrm{d}}{\mathrm{d}x}f_n(x)$$
and an explicit example where pointwise convergent series fail to do so.
THIS  post has same question but no proof. The refered link in 3rd edition of rudin has related but different proof.
Comment: uniform convergence is not sufficient to switch limits and differentiation http://www.mathcs.org/analysis/reals/funseq/proofs/uconvdiff.html
Comment: the link you give lists several examples that show the uniform convergence does not imply differentiation and limits interchange.
Answer: The classical theorem is that if each $f_n$ and $f_n'$ are continuous on an interval, the series
$$
f(x) = \sum_{n=1}^\infty f_n(x)
$$
converges pointwise, and the series
$$
g(x) = \sum_{n=1}^\infty f_n'(x)
$$
converges uniformly, then $f$ is differentiable and $f' = g$.  This uses the fundamental theorem of calculus and the ability to interchange uniform limits with integrals.

Change of Summation and Differentiation


Pushing large commit to GitHub results in a fatal write error: Bad file descriptor

Question: I'm using GitHub to manage my repository and I'm getting the following errors while attempting to push a large commit (1.5 GB).
error: pack-objects died of signal 9
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
fatal: write error: Bad file descriptor

Any ideas how to resolve this?
Comment: Are you using https/ssh/* for pushing? Is there any application on the other side (like gitlab)
Comment: As I first assumption it might be caused by the remote host
Comment: possible duplicate of [Git push "error: index-pack died of signal 9"](http://stackoverflow.com/questions/7985124/git-push-error-index-pack-died-of-signal-9)
Comment: can you try pushing it segments and see if you still get a signal 9 error?
Comment: Is the disk full on the server?
Comment: @frlan: I'm using HTTPS and GitHub
Comment: Are you using proxy or transparent proxy?
Comment: @BorisBrodski: No, I'm not using a proxy of any kind...
Answer: I had this problem with a git pack file. To get around it I repacked and specified the max size of the pack.
git repack --max-pack-size=100M -a -d

Answer: Github drops the connection because of the large commit size. Consider this help page:
https://help.github.com/articles/working-with-large-files
If you use SSH you will see something like this

remote: warning: Large files detected.
remote: error: File giant_file is 123.00 MB; this exceeds GitHub's file size limit of 100 MB

In this case your commit will be rejected. Using HTTPS there is currently no way to transmit the error message to your client.
Comment: I switched to SSH but I was getting the same errors. I just committed in several chunks and I was eventually able to get everything synced.
Answer: This tip may apply to I was working with git trying to push to github on Bluehost but this could generically apply to a lot of hosting companies. Previous tips didn't work.
After getting such errors as
Counting objects: 3532, done.
Delta compression using up to 24 threads.
fatal: unable to create thread: Resource temporarily unavailable
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
fatal: write error: Bad file descriptor

This let me send git commits on the shared host. It must forbid additional threads.
git config --global pack.threads "1"

Related issues and solution here: git push fatal: unable to create thread: Resource temporarily unavailable


Translate not working in Velocity.js

Question: I'm having some trouble animating an element using Velocity.js. My current code does not work (it's meant to translate the element 100 pixels to the right)...
$("#example").velocity({ translateX: "100px" });

However, interestingly it does work when I change it to the following...
$("#example").velocity({ transform: "translateX(100px)" });

My example seems to be the same as the code given at http://velocityjs.org/#transforms. Is there any obvious reason why this might be happening?
Here's a JSFiddle to test out my problem, https://jsfiddle.net/zwtoxxfL/2/.
Comment: @CertainPerformance I think this may be different, I am using the jQuery integration of Velocity.js. I've also added a JSFiddle to illustrate my problem more clearly.
Answer: You're using version 2.0.2 in your fiddle, which looks to not support that sort of syntax. Velocity hasn't updated their docs - their provided working example on codepen uses version 1.5.0, rather than their newest version.
If you want to use the transform shorthand like that, downgrade to a lower version:

$("div").velocity({ translateX: "100px" });
div {
  background: green;
  width: 100px;
  height: 100px;
}

Comment: Specifically Velocity v2 is still in beta, and I'm not wanting to update the public docs to it until it's out of beta - the new documentation is all in the Velocity Github wiki though :-)

Translate not working in Velocity.js


Apache forward vs reverse proxying

Question: After reading this question, I roughly understand what forward and reverse proxies are. However, apache can be configured as a forward or reverse proxy. I thought it would be up to the client to configure forward proxying, then why is the apache server handling forward proxying? From the perspective of the client, both forward and reverse proxying look the same.
Also, why can't I use a forward proxy to behave as a reverse proxy? They both sound conceptually the same almost. How do I decide wether to go with one or the other?
Comment: They don't fill the same functional role - a forward proxy is generally a system that a client uses to pass all of its web traffic; a reverse proxy is a system that acts as a front-end server that handles client connections and routes them to backend servers.  Can you clarify what you're trying to achieve?
Answer: the best solution that you going to use reverse proxies for more performance and for more security and i think that enginx that will be the best
The second partition of ur question that i think u can't do that , it's will reduce the
performance and use ur bandwith ==> This is my opinion
Regardds

Apache forward vs reverse proxying


Where can I find software to approximate very large square roots?

Question: I'm looking for an efficient tool that can help me approximate the square roots of large numbers to the nearest integer. (By large, I'm talking about numbers with several hundred digits.) Other than that, I don't really have any further constraints - it could be online or available as a download. Does anyone know where I could find one?
I've seen methods listed online, but those can get quite tedious after a while. I've also seen algorithms listed online, but I don't have the software needed to run the code and I don't want to spend money on it.
Thanks in advance!
Comment: Try [bc](https://en.wikipedia.org/wiki/Bc_(programming_language)). Its sqrt function should do exactly what you want.
Comment: How quickly does it need to work?
Comment: I don't really care, to be honest - as long as it's something semi-reasonable.
Answer: If you have access to Maple, the built-in function isqrt does what you want.
Syntax:

y = isqrt(x)
x must be a nonnegative integer, but size is arbitrary (no limit)
y is the closest nonnegative integer to sqrt(x)

From Maple Help:

The isqrt function computes an integer approximation to the square root of x. The approximation is exact for perfect squares, and the error is less than 1 otherwise.

However Maple isn't free -- far from it, but if you have access rights to a university, you should be able to find a lab which has Maple.
Comment: Thanks, but unfortunately, I don't have access to Maple or access rights to a university.
Comment: @NotAShoeStore For an online calculator you can use the free Wolfram Alpha. [Here is](http://www.wolframalpha.com/input/?i=floor(sqrt(floor(pi+*+10%5E500))%2B0.5)) for example the nearest integer to the square root of $\lfloor \pi \cdot 10^{500} \rfloor$.
Answer: Try gnu bc.
It's a free, arbitrary precision calculator.
There are versions for various operating systems.
For a Windows version, here's a link:
http://gnuwin32.sourceforge.net/packages/bc.htm
Comment: Seems to work very well.  Was already installed on my Ubuntu distro, and `sqrt(5.283*10^(400))` returned
`22984777571253544762896494402042951152028698330270828253442904899267\
65026536638690484532480170934622222009873755304493891106534146892915\
95196934610411476360351881398226440125266282644932860973368880127.82\
9`
 very quickly (well under a second).
Answer: Try this.
http://www.azillionmonkeys.com/qed/sqroot.html
It's free and works fine.
Comment: Thanks for the link, but that doesn't seem to approximate to the nearest integer - it only provides a certain amount of digits for large roots.
Comment: You can always calculate it mechanically :)
Comment: Like I said, that gets a bit tedious after a while - I'm doing this for more than one large number.


Twitter Typeahead/Bloodhound Suggestions from Ajax-Source: how manage multiple values?

Question: I'm using typeahead/bloodhound for suggestions pulling from an ajax source:
var protags = new Bloodhound({
datumTokenizer: function(protags) {
return Bloodhound.tokenizers.whitespace(protags.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/ajax/getinfo.php?q=%QUERY',
wildcard: '%QUERY',
filter: function(response) {
return response.protags;
}
}
});

JSON result from getinfo.php looks like this:
{
"protags": [
{"tag": {
"tagid": "1",
"tagtitle": "titleone"}
},
{"tag": {
"tagid": "2",
"tagtitle": "titletwo"}
},
{"tag": {
"tagid": "3",
"tagtitle": "titlethree"}
}]}

I'm able to retrieve all the information i want (tagtitle AND tagid) and display it using:
$('.typeahead').typeahead(
{ hint: true,
highlight: true,
minLength: 1
},
{
name: 'protags',
displayKey: function(protags) {
return protags.tag.tagtitle+'-'+protags.tag.tagid;
},
source: protags.ttAdapter()
});

But i'm confused about that: how can i display just the tagtitle in the suggestion field, but getting the protags.tag.tagid as well for more serverside actions?
Comment: do you want to use the data after user makes a selection?
Comment: yeezzz: yes, that's exactly what i want
Comment: try my answer... I forgot about the suggestion field so I 'll edit in a minute
Comment: sorry, but i can't make it work within my typeahead block :-(
Comment: well maybe you can post a fiddle?
Comment: argh, got it - and saw that you're already mentioned the problem:
on('typeahead:select' vs. on('typeahead:selected'
thank you very much!
Answer: Use the :select event (v 0.11.x), or :selected event (v.0.10.x). Read the bloodhound/typeahead docs as they made a lot of changes between 0.10.x and 0.11.x
I'm using 0.10.5 and in my case it looks like this:
EDIT: looking at your json, I'm not sure what data goes into template and :selected function. You may need to use data.protags.tag etc
$(selector).typeahead(
    // options, key, source etc

    templates: {
        suggestion: function (data) {
            return '
' + data.tag.tagtitle + '
';
        }
    }
    // end of options
)
.on('typeahead:selected',
    function(event, data) {
    // you should be able to get your data here, if I'm correct like so:
    console.log(data.tag.tagid);
   }
);

Comment: everyone, take care of your typeahead version as yeezzz mentioned above!

.on('typeahead:selected' vs. .on('typeahead:select'


Filtrar valor de coluna e extrair destas linhas de outra coluna o valor e escrever numa nova coluna

Question: Preciso de um help, to apanhando pacas. Tenho o titulo como mostra a tabela da esquerda e preciso transformar com o Pandas no formato da tabela em amarelo, será que o Pandas da conta?

Estou com 3 colunas e mais de 1000 linhas. Existem aleatoriamente linhas que possuem informação diferente de todas as demais. Nessas em questão, tem na primeira coluna todas o mesmo valor, vide abaixo essa linha inteira:
col1      col2      col3
-------------------------------------------------
FIG.      Item      Nomes diferentes nesta coluna

Em todas essas linhas que tem a coluna com o valor "FIG."; isto é, o que diferencia essas linhas das outras.
Preciso filtrar essas linhas (com o "FIG.") e pegar o valor desta linha que é um texto que esta na terceira coluna e criar uma quarta coluna com esse valor. Podem me ajudar com isso? Ficaria algo assim:
col1      col2      col3                               col4
------------------------------------------------------------------------------------
FIG.      Item      Nomes diferentes nesta coluna      Nomes diferentes nesta coluna

Após isso quero voltar ao DataFrame que contém todas as linhas antes de filtrar porém que fique com essa quarta coluna.
Fiz isso e o filtro funcionou:
df_mask = df['FIG.'] =='FIG.' filtered_df = df[df_mask] lista = filtered_df

E isso também funcionou:
df = pd.DataFrame(lista,columns=['FIG.','Item','Nomes diferentes nesta coluna'])

Mas não estou conseguindo criar uma nova coluna com os valores "Nomes diferentes nesta coluna".
Comment: Luiz, a descrição está um pouco confusa para entender. Você poderia atualizar seu post, colocando 3 linhas do seu dataframe original e a saída que você espera?
Comment: Luiz Notari, não rasure as perguntas.
Answer: Acredito que você esteja procurando stack() ou unstack()
Para lembrar o que cada um faz, o stack deixará seu data frame mais longo, e o unstack mais largo.
Uma vez que não tenho acesso aos dados, segue um exemplo.
>>> import pandas as pd

>>> frutas = ['banana', 'abacaxi', 'ameixa', 'banana', 'abacaxi']
>>> valores = [1.0, 1.0, 2.0, 5.0, 3.5]

>>> df = pd.DataFrame({"fruta": frutas, "valor": valores})

>>> df
     fruta  valor
0   banana    1.0
1  abacaxi    1.0
2   ameixa    2.0
3   banana    5.0
4  abacaxi    3.5

Criando o grupo
>>> df.groupby("fruta").agg('sum')
         valor
fruta
abacaxi    4.5
ameixa     2.0
banana     6.0

Stacking
>>> df.groupby("fruta").agg('sum').stack()
fruta
abacaxi  valor    4.5
ameixa   valor    2.0
banana   valor    6.0
dtype: float64

Unstacking
>>> df.groupby("fruta").agg('sum').unstack()
       fruta
valor  abacaxi    4.5
       ameixa     2.0
       banana     6.0
dtype: float64
>>>

Criando grupo pelas duas colunas
>>> df.groupby(["fruta", "valor"]).agg({'valor': 'sum'})
               valor
fruta   valor
abacaxi 1.0      1.0
        3.5      3.5
ameixa  2.0      2.0
banana  1.0      1.0
        5.0      5.0

Escolhendo a coluna para unstack
>>> df.groupby(["fruta", "valor"]).agg({'valor': 'sum'}).unstack()
        valor
valor     1.0  2.0  3.5  5.0
fruta
abacaxi   1.0  NaN  3.5  NaN
ameixa    NaN  2.0  NaN  NaN
banana    1.0  NaN  NaN  5.0

Preenchendo NaN com zero
>>> df.groupby(["fruta", "valor"]).agg({'valor': 'sum'}).unstack(fill_value=0)
        valor
valor     1.0  2.0  3.5  5.0
fruta
abacaxi   1.0  0.0  3.5  0.0
ameixa    0.0  2.0  0.0  0.0
banana    1.0  0.0  0.0  5.0

Veja a documentação dos dois: stack e unstack
Em tempo: este é apenas um exemplo sem nenhuma aplicação específica e serviu apenas para explorar os métodos stack() e unstack() que te ajudarão com seu caso.
Comment: Criei uma nova resposta para sua pergunta, mas resolvi manter esta pois pode ser útil para os demais
Answer: A grande dificuldade de usar o Pandas é pensar que se consegue fazer tudo em uma linha. Talvez seja possível, mas não é legível e é de difícil manutenção.
Sendo assim, vamos por partes
Criando base de teste
import pandas as pd
import numpy as np

df = pd.DataFrame({"FigField": ["FIG", "",  "",  "", "FIG",  "",  "",  "", "FIG",  "",  ""], "CatFilme": ["Categoria 1", "filme a",  "filme b",  "filme c", "Categoria 2",  "filme x",  "filme y",  "filme z", "Categoria 3",  "filme h",  "filme k"]})

Temos:
   FigField     CatFilme
0       FIG  Categoria 1
1                filme a
2                filme b
3                filme c
4       FIG  Categoria 2
5                filme x
6                filme y
7                filme z
8       FIG  Categoria 3
9                filme h
10               filme k

Criando coluna auxiliar "zerada"
df["ColAux"] = np.nan

Temos
   FigField     CatFilme  ColAux
0       FIG  Categoria 1     NaN
1                filme a     NaN
2                filme b     NaN
3                filme c     NaN
4       FIG  Categoria 2     NaN
5                filme x     NaN
6                filme y     NaN
7                filme z     NaN
8       FIG  Categoria 3     NaN
9                filme h     NaN
10               filme k     NaN

Copiando a categoria para a coluna auxiliar somente onde existe FIG
df["ColAux"] = df.apply(lambda row: row["CatFilme"] if row["FigField"] == "FIG" else np.nan, axis=1)

Temos
   FigField     CatFilme       ColAux
0       FIG  Categoria 1  Categoria 1
1                filme a          NaN
2                filme b          NaN
3                filme c          NaN
4       FIG  Categoria 2  Categoria 2
5                filme x          NaN
6                filme y          NaN
7                filme z          NaN
8       FIG  Categoria 3  Categoria 3
9                filme h          NaN
10               filme k          NaN

Preenchendo os NaN da coluna auxiliar com a categoria
df["ColAux"].fillna(method="ffill", inplace=True)

Temos
   FigField     CatFilme       ColAux
0       FIG  Categoria 1  Categoria 1
1                filme a  Categoria 1
2                filme b  Categoria 1
3                filme c  Categoria 1
4       FIG  Categoria 2  Categoria 2
5                filme x  Categoria 2
6                filme y  Categoria 2
7                filme z  Categoria 2
8       FIG  Categoria 3  Categoria 3
9                filme h  Categoria 3
10               filme k  Categoria 3

Apagando linhas que contenham FIG
df = df[df["FigField"] != "FIG"]

Temos
   FigField CatFilme       ColAux
1            filme a  Categoria 1
2            filme b  Categoria 1
3            filme c  Categoria 1
5            filme x  Categoria 2
6            filme y  Categoria 2
7            filme z  Categoria 2
9            filme h  Categoria 3
10           filme k  Categoria 3

Ainda pode ser feito o reset_index() caso ache interessante.
Comment: @LuizNotari, que bom que funcionou. Sendo assim, marque a resposta como aceita.


Database design - How should we design a teacher/student relationship when student records themselves also need to be associated to each other

Question: So this is something that we've been struggling to try and figure out how to optimize.

In a simple world, this might be solved by a simple many-to-many bridging table like this:

teachers_students_mappings

id
teacher_id
student_id

1
1
1

2
1
2

3
1
3

4
2
1

However, we have another complexity here to grapple with. A student record can come from different "sources", i.e.:

The student was created by another system transferring the records of that student and their classes to us (most student and teacher-student relationship records are created this way).
The student registered on their own (through an app), or
The student was manually created by a teacher (via a teacher portal)

We therefore have cases where student records, from different sources, should be related to each other too:

students

id
name
id_number
source_type

1
Rachel Doe
9898123
created_by_system

2
Rachel Doe
9898123
app_user

3
John Doe
9833456
created_by_teacher

e.g. Above, we have a case where student_ids 1 & 2, Rachel Doe, are actually the same person. The first record was generated automatically by the system, and the 2nd record was created when Rachel registered in the system on her student app. Both records share an id_number, which is a unique identifier in the school.

If we made it so both student_ids 1 and 2 were linked to all of Rachel's teachers, her teachers would be seeing duplicated records, i.e. both Rachel's app account, and her record created by the system. It seems it might therefore be smarter to relate both these student_id records to each other, but how would that impact the teachers_students_mappings table?
It is also theoretically possible that 3 unique student records exist for the same student (i.e. the teacher manually created a record, then the system created it, then the student created an account on the app).
Comment: Does this answer your question? [How can you represent inheritance in a database?](https://stackoverflow.com/questions/3579079/how-can-you-represent-inheritance-in-a-database)
Comment: The logic needs `id_number` column to be unique. Create according UNIQUE index, and MySQL will not allow to insert the row with the value which is already present. Your client software must process this duplication error and point the operator to tthe existing row.
Answer: Since you already have an id_number that is unique and provides the mechanism to realize that you have one, not two Rachel Does, use it as the PRIMARY KEY of the Students table.  Do not also have another id for each student.
On the other hand, if you have a StudentHistory table that records various actions taken by or for each student, it would need its own PRIMARY KEY.  This seems to be a separate topic.
So, when "inserting" or "Updating" a row for a student, use
INSERT INTO Students (id_number, name, foo, ...)
    VALUES ("9898123", "Rachel Doe", 123, ...)
    ON DUPLICATE KEY UPDATE
        foo = VALUES(foo), ...;

Or (if coming from a SELECT):
INSERT INTO Students (id_number, name, foo, ...)
    SELECT id_number, name, foo, ...
        FROM other table ...
    ON DUPLICATE KEY UPDATE
        foo = VALUES(foo), ...;

Answer: Before entering the data of a new record you have to check if the id_number exists. In that case you have to return the identification and not insert that record.


Why doesn't my text filter strip out the tags I don't want?

Question: I thought I understood text filters, but it appears I don't.
I am using a filter on my node's "body" field that is supposed to restrict tags. I have entered the allowed HTML tags as

Yet in my WYSIWYG editor I can switch to source view and save text that includes  (or worse, ) tags.
Why aren't these tags stripped out when the node is saved?
Comment: Are you using CKeditor?
Comment: Yes, CKEditor. Version 4.4.7 I believe.
Comment: check your [/admin/config/content/formats/filtered_html](http://i.stack.imgur.com/ewjvd.jpg) and make sure those tags are in the allowed tags. (Assuming you are using Filtered HTML as your format)
Comment: The string of tags in my question above is the one for my text filter, copied and pasted from the text filter config. I've been able to add "script", "img", and "a" tags with no issues, even though they should be stripped out when saving the node (if I understand the text filtering system correctly).
Answer: Okay, I've found my own answer. The problem was with my understanding of how text filters work. Text is saved into the database with no changes, and filters are only applied when the text is output.
When using Entity Metadata Wrappers, as I am, when you get $wrapper->body->value(), it gives you an array with several elements. One is the "value", which is the raw, unfiltered text. Another is the "safe_value", which has had filters applied.
So in my case I needed to use the "safe_value" when displaying the text. Makes sense once you understand it!


How to dump Chef attributes as JSON locally

Question: How can I dump the structure from Chef cookbook from attributes/default.rb on the machine with the source code?
Let's say, I have a cookbook source code. And all the recipes are executed on the target node. I would like to parse the attributes/default.rb which creates the node.default and alike, which is then merged to just node tree. And then print it as JSON.
Something along the lines of
  json = "#{Chef::JSONCompat.to_json_pretty(node.to_hash)}"
  File.open("/tmp/node-dump.json", 'w') { |file| file.write(json) }

  yaml = node.to_yaml
  File.open("/tmp/node-dump.yml", 'w') { |file| file.write(json) }

  file '/tmp/chef/node-dump2.json' do
    source json
  end

But I want it to happen locally.
Is there a way? Chef 12.21.26
Answer: As with your last question, there is no such thing as "locally" in Chef. All execution of cookbook code happens on the instance being converged. What you probably want is something like knife node show -l -fJ, but that wouldn't help with Test Kitchen since there is no Chef Server to query.


Deciding whether a number is rational (2 examples)

Question: 1) Prove that number irrational $\sqrt{7-\sqrt{2}}$
I created a polynomial $x=\sqrt{7-\sqrt{2}}$ so
$P(x)=x^4-14x^2+47$ and since $47$ is prime we check $P(x)$ for $ {1,-1,47,-47}$ and since all of them are $P(x)\neq0$ it means our number is irrational.
Is my prof OK ?
2) Decide if the number $\sqrt{\sqrt{5}+3}+\sqrt{\sqrt{5}-2}$ is rational or irrational. I don't know how to tackle this one. I'd be grateful for hints
Comment: If you square your number, you get 7 - sqrt (2) which is irrational. Squaring a rational produces a rational, so you must have squared an irrational number.
Comment: 1) That's the correct idea, but check your numbers.
Comment: It should be $P(x) \equiv x^4 - 14 x^2 \color{red}{+ 47}$ and not $-47$ there.
Comment: The approach in your first proof is correct, though it could be a bit more polished: $P(x)$ certainly has this number as a root, and then you apply the Rational Root Theorem. As for the second, think about how you created the polynomial in 1) so that it'd include that root.
Comment: 2) Since there are four square-roots, I suspect the polynomial is going to be degree $2^4=16$!
Comment: Whenever tasked with a proof like this, you can be pretty sure that your working to a point where a known irrational number equals an integer over an integer (i.e. rational), which is a contradiction -> QED.
Comment: http://joaomaths.blogspot.com.au/2014/07/proof-that-solutions-to-xnan-1xn-1an.html see this proof and then try to show that your expression isn't an integer.
Comment: I corrected the error reported by @hjpotter92
Answer: You don't need all that! If $\sqrt{7-\sqrt 2} = \dfrac{p}{q}$ is rational, then $\sqrt 2 = 7 - \dfrac{p^2}{q^2}$is rational. Which it isn't.
Answer: For 2).
If $p=\sqrt{\sqrt 5+3}+\sqrt{\sqrt 5-2}$ is a rational number, then
$$\begin{align}p-\sqrt{\sqrt5+3}=\sqrt{\sqrt5-2}&\Rightarrow p^2-2p\sqrt{\sqrt5+3}+\sqrt5+3=\sqrt5-2\\&\Rightarrow 2p\sqrt{\sqrt5+3}=p^2+5\\&\Rightarrow 4p^2(\sqrt 5+3)=(p^2+5)^2\\&\Rightarrow \sqrt5=\frac{(p^2+5)^2}{4p^2}-3\end{align}$$
implies that $\sqrt 5$ is a rational number. This is a contradiction.
Comment: @Just_a_fool The reason that the trick works here is that the 'inner' roots are the same, so after two squaring steps you're left with a single square root.  OTOH, the method that you used for 1) (with the rational root theorem) can be used as an algorithm to determine the rationality or irrationality of an arbitrary algebraic expression (since the equation gives you a finite number of possible values to test against and all roots can be computed to sufficient precision).  OTOH, there's a lot of subtlety in this; look up the 'sum-of-square-roots' problem in computational geometry for details..
Comment: Very smooth! I am curious - can the irrationality of all algebraic irrationals, no matter how complex the number, be demonstrated by this "inductive" method (given the irrationality of all prime roots is a given) or are there any exceptions?


Serving static resources with Ktor GraalVM

Question: I found example of Ktor GraalVM https://ktor.io/docs/graalvm.html which works perfectly well. But how to serve static resources like images or even more important js (javascript) files?
I have:
<code>    routing {
        get("/") {
            call.respondText("Hello GraalVM!")
            call.application.environment.log.info("Call made to /")
        }

        static("/") {
            resources("img")
        }
    }
</code>
The new code is 'static("/")...' part and the question again: Is it possible to serve static content? Of course I still want to have native GraalVM output (executable).
http://0.0.0.0:8080/ works and serves: "Hello GraalVM!" output.
But http://0.0.0.0:8080/img/test.png (in resources -> img folder I have a file test.png) returns 404 not found.
Comment: https://ktor.io/docs/serving-static-content.html#serve-all-files should be configured for static content serving.
Comment: You need to integrate resources into a native executable https://www.graalvm.org/22.1/reference-manual/native-image/Resources
Answer: I've made it work... and found why it is not working with only classical code:
<code>    static("/") {
        staticBasePackage = "static"
        static("img") {
            resources("img")
        }
    }
</code>
...but first, fragments of the call, i.e. logs:
<code>>>> url.protocol = resource
</code>
and here's the answer ... it normally works as a file, but in native GraalVM this is sought as a resource.
Original code:
<code>@InternalAPI
public fun resourceClasspathResource(url: URL, path: String, mimeResolve: (String) -> ContentType): OutgoingContent? {
    return when (url.protocol) {
        "file" -> {
            val file = File(url.path.decodeURLPart())
            if (file.isFile) LocalFileContent(file, mimeResolve(file.extension)) else null
        }
        "jar" -> {
            if (path.endsWith("/")) {
                null
            } else {
                val zipFile = findContainingJarFile(url.toString())
                val content = JarFileContent(zipFile, path, mimeResolve(url.path.extension()))
                if (content.isFile) content else null
            }
        }
        "jrt" -> {
            URIFileContent(url, mimeResolve(url.path.extension()))
        }
        else -> null
    }
}
</code>
and here, as you can see, the resource is not supported here. I had to rewrite the code like this:
<code>// "new version" of: io.ktor.server.http.content.StaticContentResolutionKt.resourceClasspathResource
    fun resourceClasspathResourceVersion2(url: URL, path: String, mimeResolve: (String) -> ContentType, classLoader: ClassLoader): OutgoingContent? {
        println(">>> url.protocol = ${url.protocol}")
        return when (url.protocol) {
            "file" -> {
                val file = File(url.path.decodeURLPart())
                println(">>> file = $file")
                if (file.isFile) {
                    val localFileContent = LocalFileContent(file, mimeResolve(file.extension))
                    println(">>> localFileContent = $localFileContent")
                    localFileContent
                } else null
            }
            // ... here are other things which are in original version
            "resource" -> {
                println(">>> in resource")
                val resourceName = url.path.substring(1)
                println(">>> resourceName = $resourceName")
                val resourceAsStream = classLoader.getResourceAsStream(resourceName)
                val cnt = ByteArrayContent(resourceAsStream.readAllBytes(), ContentType.parse("image/gif"), HttpStatusCode.OK)
                cnt
            }
            else -> null
        }
    }
</code>
All the code for the Routing class (Routing.kt) looks like this:
<code>package io.ktorgraal.plugins

import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.io.File
import java.net.URL

fun Application.configureRouting() {

    // I use println not some Logger to make it simple... in native also
    // (there are different problems in native compilations with loggers)

    // "new version" of: io.ktor.server.http.content.StaticContentResolutionKt.resourceClasspathResource
    fun resourceClasspathResourceVersion2(url: URL, path: String, mimeResolve: (String) -> ContentType, classLoader: ClassLoader): OutgoingContent? {
        println(">>> url.protocol = ${url.protocol}")
        return when (url.protocol) {
            "file" -> {
                val file = File(url.path.decodeURLPart())
                println(">>> file = $file")
                if (file.isFile) {
                    val localFileContent = LocalFileContent(file, mimeResolve(file.extension))
                    println(">>> localFileContent = $localFileContent")
                    localFileContent
                } else null
            }
            // ... here are other things which are in original version
            "resource" -> {
                println(">>> in resource")
                val resourceName = url.path.substring(1)
                println(">>> resourceName = $resourceName")
                val resourceAsStream = classLoader.getResourceAsStream(resourceName)
                val cnt = ByteArrayContent(resourceAsStream.readAllBytes(), ContentType.parse("image/gif"), HttpStatusCode.OK)
                cnt
            }
            else -> null
        }
    }

    // Starting point for a Ktor app:
    routing {
        get("/") {
            call.respondText("Hello GraalVM!")
            call.application.environment.log.info("Call made to /")
        }

        // not working... so we need below "reimplementation"
        /*static("/") {
            staticBasePackage = "static"
            static("img") {
                resources("img")
            }
        }*/

        // "new version" of: io.ktor.server.http.content.StaticContentKt.resources
        // ... because I need to call different function no resourceClasspathResource, but resourceClasspathResourceVersion2
        get("/{pathParameterName...}") {
            println(">>> this endpoint was called")
            val relativePath = call.parameters.getAll("pathParameterName")?.joinToString(File.separator) ?: return@get
            val mimeResolve: (String) -> ContentType = { ContentType.defaultForFileExtension(it) }
            val classLoader: ClassLoader = application.environment.classLoader
            val normalizedPath = relativePath // here I do not do normalization although in Ktor code such code exists
            println(">>> normalizedPath = $normalizedPath")
            val resources = classLoader.getResources(normalizedPath)
            for (url in resources.asSequence()) {
                println(">>> url = $url")
                resourceClasspathResourceVersion2(url, normalizedPath, mimeResolve, classLoader)?.let { content ->
                    if (content != null) {
                        println(">>> about to return content")
                        call.respond(content)
                    }
                }
            }
        }
    }

}
</code>
And here, too, I had to have a "new version" of io.ktor.server.http.content.StaticContentKt.resources not to change the entire library.
Then the

http://localhost:8080/static/img/test/test.gif

call works and returns a file.
The whole code change "https://github.com/ktorio/ktor-samples/tree/main/graalvm" is the above listed Routing.kt class. You should also add a file such as gif to resources -> static -> img -> test -> test.gif (nesting only to show the structure).


Converting an EC2 AMI to vmdk image

Question: I've come quite close to getting Amazon Linux to boot inside VirtualBox, thanks to this answer and these websites. A quick overview of the steps I've taken:

Launch EC2 instance with Amazon Linux 2011.09 64-bit AMI
dd the contents of the EBS volume over ssh to a local image file.
Mount the image file as a loopback device and then to a local mount point.
Create a new empty disk image file, partition with an offset for a bootloader, and create an ext4 filesystem.
Mount the new image's partition and copy everything from the EC2 image.
Install grub (using Ubuntu's grub-legacy-ec2 package, not grub2).
Convert the image file to vmdk using qemu-img.
Create a new VirtualBox VM with the vmdk.

Now the VM boots, grub loads, and the kernel is found. But it fails when it tries to mount the root device:
dracut Warning: No root device "block:/dev/xvda1" found

dracut Warning: Boot has failed. To debug this issue add "rdshell" to the kernel command line.

dracut Warning: Signal caught!

dracut Warning: Boot has failed. To debug this issue add "rdshell" to the kernel command line.
Kernel panic - not syncing: Attempted to kill init!
Pid: 1, comm: init Not tainted 184.108.40.206-107.1.39.amzn1.x86_64 #1

I have tried changing /boot/grub/menu.lst to find the root device by label and UUID, but nothing works. I'm guessing the xen kernel is not compatible with VirtualBox.
The reasoning behind all this effort is to make a Vagrant box that is as close to possible as the production enviroment, so deploys can be tested locally. I know it's cheap to do test runs on EC2, but poor connectivity often ruins the experience. Plus it would be really nice to have a virtual machine with the production environment so that co-workers don't have to install everything under the sun just to get up and running with app development.
If I were to try running a different kernel, what kernel could I get to be as close as possible to Amazon Linux 2011.09?
Comment: Was doing work similar to you and found the solution on other link .. sharing with you as well. Tested this and it worked for me ... http://blog.zorangagic.com/2015/03/converting-ec2-ami-to-virtualbox-vdi.html?view=snapshot
Answer: I tried so much and I was giving up, but at the end I succeed!
I've managed to boot with an Amazon Linux AMI ported under vmware!
I'm almost a newby, but I did it, after hours of trials, substituting the original amazon kernel with a vmlinuz-2.6.32-38-generic taken from an ubuntu 64 10.04 distro.
I just get a lot of errors because the amazon configuration inside the AMI is looking for something in an internal address that obviously it doesn't find. It's the /usr/bin/cloud-init, I think.
But I can login inside, and it seems that everything is working!
Thanks for your help!!
I've written this blogpost with step by step instructions to migrate from AMI to Vmware.
Hope this helps!
Comment: BTW, Reed, I arrived exactly at the point you stated (dracut telling "no root device found"... did you move any further??
Comment: I came to basically the same solution you did: copying the kernel from Ubuntu. It works, but at that point I don't know how similar the system will perform to the Amazon Linux AMI.
Comment: Please also see my answer [here](http://stackoverflow.com/a/28201388/675721), which provides 2 alternative updated methods for exporting to VirtualBox/VMWare VMDK, as well as instructions on using your newly created VMDK with Vagrant
Answer: The official kernel Amazon derived theirs in their 2011.09 distribution, ie 220.127.116.11.
You can probably get the source package for the Amazon one with get_reference_source, but I wouldn't expect it to work outside of Amazon anyway.
Answer: The people over at Cloudify have shared how they create a VirtualBox ready Vagrant box, without access to bare metal machines - they use AWS.
9 steps to heaven:

Create a source image (AMI) [...] using Packer.
Launch a worker instance in AWS with the snapshot or source image as one of its disks.
On the worker image: Create a raw image volume as a file and create an ext4 partition on it.
Copy over the data from the source image disk to the previously created ext4 partition.
Install the bootloader (extlinux) on the ext4 partition.
Convert the raw image into a VMDK.
Bundle the VMDK using an OVF descriptor and Vagrant metadata and create a tar file with the content and .box extension.
Upload to S3 [or whatever you like].
Clean up.

Source: Blog post at http://www.developer.com/design/creating-a-reproducible-and-portable-development-environment.html with the above 9 steps
Code: https://github.com/cloudify-cosmo/cloudify-packager/tree/3.2m4/image-builder

Converting an EC2 AMI to vmdk image


Is this proof of the fundamental theorem of calculus correct?

Question: A student friend of mine recently gave me a proof of the fundamental theorem of calculus which does not correspond to any I can find in the textbooks. It starts by considering an increasing continuous function and taking the area of a thin rectangle topped with a triangle created by adding to the $x$ value (like the wikipedia entry for the theorem):
$$
\begin{align}
A(x + h) & = A(x) + hA'(x)\\
hA'(x)& = A(x + h) - A(x)\\& = hf(x) + \frac12h\cdot hf'(x)
\end{align}
$$
where $A$ is the area function, $h$ is the added value, the first term on the RHS is the area of the rectangle and the second term on the RHS is the area of the triangle. The $hf'(x)$ term is the projection that forms the vertical side of the triangle. Apparently the curve can be composed of small straight lines making the triangle possible. The next step is:
$$\begin{align}
    hA'(x) &= hf(x)\\
    A'(x) & = f(x)
\end{align}$$
RHS 2 is discarded because $h^2$ is negligible. Is this proof legitimate? If so why isn't it in the textbooks? It seems much simpler than the alternatives.
Comment: You seem to assume that $A'$ exists, whereas I would have taken that to be part of what was to be proved.
Answer: It's a good start. But there are three problems.

There's an assumption that integrals and areas are the same. It's true that the integral was defined to try to generalize the standard area computations, but are you certain that it succeeds? If not, then proving things about areas doesn't prove things about integrals (which involve lower and upper sums, etc.).
The claim that A(x + h) = A(x) + hA'(x) is false. What's true is that the right hand side is a very good approximation of the left, under certain assumptions, and it gets better and better as $h$ gets smaller.
That same claim assumes implicitly that the area function $A$ is differentiable. While most uses of the FTC depend on the fact that the derivative of $A$ is $f$, the deeper part of the theorem is that $A$ is differentiable at all. Once you know that, actually computing the derivative isn't so hard. :)

The details that are hidden in these two things are precisely what all those "book" proofs actually handle.
On the other hand, a picture and proof-sketch like this is a great idea for motivating the claim of the theorem, and for guiding the student to a more complete and correct proof.
Comment: "It's not proving it's true, but proving that it's plausible" is a nice slogan for this.
Comment: An alternative (jokey) version: "Could you convince a physicist with it?"
Comment: Agreed...although Taylor's theorem wants your function to be differentiable, and part of the conclusion of the FTC is that $A$ actually *is* differentiable. I'll add that to my answer.
Comment: Regarding point 2, might I draw the OPs attention to Taylor's theorem: http://en.wikipedia.org/wiki/Taylor's_theorem
Comment: That's a *great* way of putting it. And it's not a bad first step for any mathematical question: before you try to write a full proof, at least convince yourself that the thing you're trying to prove is plausible.
Comment: @Semiclassical Are there are proofs for plausibility which we don't have proofs of truth for? Or better yet, that we have proofs to the contrary?
Comment: @Cruncher: Quite a few: the Collatz conjecture, the non-existence of any additional Fermat primes, the Riemann hypothesis...each of those have quite plausible evidence, but no proof is known.  Not sure I know what you're asking for with the latter part of your query.
Comment: @JohnHughes how are integrals and areas not the same??The integral as it is defined on a continuous function is the exact area under the curve(one variable)(not an approximation). Can you explain more?
Answer: The theorem asserts that $A'$ exists and equals $f$.  The argument given appears to assume $A'$ exists, rather than treating that as a part of what was to be proved.
You can argue as follows.
Suppose $f$ is continuous.
$$
\frac{A(x+h)-A(x)}{h} = \frac 1 h \int_x^{x+h} f(t)\,dt \tag 1
$$
Given $\varepsilon>0$, we can say that $f(t)$ stays between $f(x)\pm\varepsilon$ if $h$ is close enough to $0$. Hence the expression on the right side in $(1)$ is between
$$
\frac 1 h \int_x^{x+h} (f(x)\pm\varepsilon)\,dt = \frac 1 h (f(x)\pm\varepsilon)h = f(x)\pm\varepsilon.
$$
So we can make $\dfrac{A(x+h)-A(x)}{h}$ as close as desired to $f(x)$ by making $h$ close enough to $0$.
In other words $\lim\limits_{h\to0}\dfrac{A(x+h)-A(x)}{h}=f(x)$.  Thus $A'(x)$ exists and is equal to $f(x)$.
Answer: Maybe it was in the early books.
This geometric argumentation is reminding of early work on geometric curves from around 1650-1700, those scientists (Gregory, Barrow, Leibniz, Newton) discovered and knew that relationship between the area under a curve and that curve.
To quote from this nice talk:

David M. Bressoud: Historical Reflections
on the Fundamental Theorem Of (Integral) Calculus

The modern statement of the FTIC is the result of centuries of
  refinement of the original understanding and requires
  considerable unpacking if students are to understand and
  appreciate it.

So there are reasons why it is not done this way in modern texts.
In the end even the idea of assigning meaningful "area" to all subsets of the plane has been given up, after recognizing some tricky cases.
See
Maßproblem
Here are some historic links if you want to see that early methods.

See Newton here or
Leibniz here.


Assume $f(n)=O(g(n))$ with $g(n)\geq 2$ for all $n$

Question: Assume $f(n)=O(g(n))$ with $g(n)\geq2$ for all $n$
implies $f(n)+g(n)=O(g(n))$
the answer which teacher offer is false ,but I think it is true
this is my think
$f(n)=O(g(n))$ so $f(n)\leq c\cdot g(n)$  ,$f(n)+g(n)\leq (c+1)\cdot g(n)$
So $f(n)+g(n)=O(g(n))$
Am I wrong?
Comment: Your answer looks right. What answer did your teacher give?
Comment: You're not wrong, you can be more formal by stating all the quantifiers but besides that you're fine.
Comment: I'm not sure what the purpose of $g(n)\geq 2$ is in the question.
Answer: You are correct, and just as a general rule of thumb when there is a linear combination of terms, for example $f(x)=ag(x)+bh(x)+...$ the only term that matters for the asymptotic is the leading(Largest) term. For example $3x^2+99x$ is $O(x^2)$
This can be used to show that you are right since $f(x)\sim O(g(x))$ by assumption and $g(x)\sim O(g(x))$ trivially then $f(x)+g(x)\sim O(g(x))$


How to show a and hide a widget when a special symbol is inputted on the textfield

Question: I am listening to changes of the textfield using the onChanged property of the textfield to detect when @ symbol is pressed. It's just like a mention feature in every other social apps. I want to know when @ symbol is pressed alongside other values and then show a mention widget until space is entered, then remove the mention widget.
What i want to achieve

Detect when @ symbol is pressed, then show the mention widget, if another value is entered then remove the mention widget.

If @ is detected in the middle of texts show mention widget

What i have tried
I use regEx to detect the values with @ and print the matched value. I don't really know how to show the mention widget at the first regEx logic. I then split the textfield values and use a different regEx pattern to check if any value matched then show the mention widget.
It doesn't work as expected. When scrolled to the middle of the texts in the textfields and add @ to a text, the mention widget doesn't trigger.
onChanged property code
 void onChanged(String value) {
    final _mentionRegEx = RegExp(AppUtils.mentionPattern, caseSensitive: false);
    final _checkRegEx = RegExp(
      r"^@[a-zA-Z0-9_ ]+[a-zA-Z0-9_]*$",
      // caseSensitive: false,
      multiLine: true,
    );
    Iterable<Match> matches = _mentionRegEx.allMatches(value);

    for (var m in matches) {
      String match = m[0]!;
      final withoutMentonTag = match.substring(1);
      state = state.copyWith(matched: withoutMentonTag);
      print('MENTION => ${state.matched}');
    }

    final sentences = value.split(' ');
    for (var sentence in sentences) {
      print('SENTENCE => $sentence');
      final words = sentence.split(' ');
      final withMentionTag = words.last;

      if (_checkRegEx.hasMatch(sentence)) {
        toggleMentionWidget(true);
        String withoutMentionTag = withMentionTag.substring(1);
        print('MENTIONED USER => $withoutMentionTag');
      } else {
        toggleMentionWidget(false);
      }
    }
  }

Comment: Have you check this package: https://pub.dev/packages/flutter_mentions?
Comment: "the mention widget doesn't trigger" - it's not clear whether you mean `toggleMentionWidget(true)` is not getting called, or it is getting called but is failing to show the widget.
Comment: @ChuckBatson it doesn't get called
Answer: You can try this package from pub.dev. It provides mention feature in an Input Text Field
FlutterMentions(
   key: key,
   suggestionPosition: SuggestionPosition.Top,
   maxLines: 5,
   minLines: 1,
   mentions: [
      Mention(
      trigger: "@",
      style: TextStyle(color: Colors.purple),
      data: [
         {
           "id": "61as61fsa",
           "display": "somename",
           "photo": "https://images.pexels.com/photos/220453/pexels-
            photo-220453.jpeg"
         },
         {
           "id": "61asasgasgsag6a",
           "display": "username",
           "photo": "https://images.pexels.com/photos/220453/pexels-
            photo-220453.jpeg",
            style: TextStyle(color: Colors.green),
          },
      ],
    )
  ],
)

Comment: Copy of package example code
Comment: Just found out this one easier.
Comment: Already mention in comment of questions
Comment: @MilanSurelia I don't want to use packages. Moreover,  this package is no longer maintained.
Answer: Your regular expression is incorrect:
    final _checkRegEx = RegExp(
      r"^@[a-zA-Z0-9_ ]+[a-zA-Z0-9_]*$",
      // caseSensitive: false,
      multiLine: true,
    );

Refer to the spec:

^ always matches only at the beginning of Input, or (if Multiline is true) at the beginning of a line.

Since your regular expression specifies ^ and multiLine: true, it will match only when the @ character is at the beginning of the text, or the beginning of a line.
You may want to use a regular expression more like (^@|\s@)[a-zA-Z0-9_]+. You may have to experiment to find a regular expression that does exactly what you want. You can try out different regular expressions at the site https://regex101.com.
If you continue to have difficulty, I suggest you open a new question tagged for regular expressions, since this has nothing to do with Dart or Flutter at this point.
Comment: How can I make it to match only the beginning of each words in the textfield?
Comment: Hello @MElochukwu, I've updated the answer with some information about regular expressions.


ActivityNotFound even when Activity is present

Question:
Possible Duplicate:
Intent for editing plain text file with the installed file editor (if any)

I am trying to open some text file which I have downloaded. When I start the activity with intent it gives ActivityNotFound Exception.
try {
    Uri path = Uri.parse(path+"/sampletext.txt");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    PackageManager packageManager = ctx.getPackageManager();
    intent.setType("text/plain") ;
    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if (list.size() > 0 ) {
        intent.setDataAndType(path, "text/plain");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ctx.startActivity(intent) ;
    }

} catch (Exception e){
    e.printStackTrace() ;
}

When I debugged, I found that the list.size is 1.
Is there any other information which I am missing?
Any kind of points would help me.
Thanks.
Comment: I am able to open the same file from the file browser, but not from my app.
Comment: @Merlin I do not want to edit the file.. I need to open the file for reading..
Comment: @Merlin, There the Mimetype is wrong, but here I am able to see the activity and still not able to launch..
Answer: ActivityNotFound Exception is generally encoutered when there is no matching activity declared in the manifest file or registered by another application as a shared activity.
You may need to edit your path:
Uri path = Uri.parse("file://" + path + "/sampletext.txt");
a better way to do this is to use the convenience method:
Uri data = Uri.fromFile(file);
but you would need to create a File object to use that method
Comment: When I debuged I found that quick office [On my HTC phone] is listed in the response which I got from queryIntentActivities(..).
Comment: Do you think file path would trigger a ANF Exception and not FileNotFound Exception?
Comment: Not really, but you never now what android does behind the scenes ... it's worth a try
Comment: No problem ... you're right though ... a FileNotFoundException or InvalidIntentDataException would make more sense and ultimately more helpful


Android location manager permissions to be used

Question: I have the following code in my android project:
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location currentLocation = locationManager.getLastKnownLocation(bestProvider);
location = currentLocation.getLatitude() + " " + currentLocation.getLongitude();
MyLocation.setText(location);

I am getting an provider == null  error. what permissions do I need to use?
My android manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.DuckTag"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".DuckTagActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
</manifest>

Thank you
Answer: Here is what you need to add to your manifest file
GPS-based location
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Network-based location
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Previous posters are wrong, if you want to use both, then only ACCESS_FINE_LOCATION is required, as detailed here: http://developer.android.com/guide/topics/location/obtaining-user-location.html

Note: If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then
  you need to request only the ACCESS_FINE_LOCATION permission, because
  it includes permission for both providers. (Permission for
  ACCESS_COARSE_LOCATION includes permission only for NETWORK_PROVIDER.
Answer: You need this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Comment: You _don't_ need both Permissions. ACCESS_FINE_LOCATION includes ACCESS_COARSE_LOCATION.
Comment: Just for reference, you don't actually need both these permissions unless you use both (which the OP does in this case). See the developer [reference](http://developer.android.com/reference/android/Manifest.permission.html) for more information.
Answer: Here is what you need to add to your manifest file :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

for GPS-based location or
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

for network-based location
You can require both if you want to build a more versatile application.
Greetings,
 Stéphane


What kind of property does a continuously differentiable function has?

Question: Is there any differences between a continuously differentiable function and a common function? I want ask this question because I have seen many exercises telling me that f(x) is continuously differentiable.
For example, suppose f(x) is continuously differentiable, and f(0)=0
$$f'(x)+\int_0^x f(t)\,\mathrm{d}t=e^x$$
Find out the expression of f(x).
Why do I need f(x) to be continuously differentiable?
Answer: The equation you have quoted does not make sense if $f$ is not differentiable. If $f$ is differentiable and the integrable (so that the RHS makes sense) then automatically $f'(x)=e^{x}-\int_0^{x} f(t) \, dt$ is continuous. Hence there is no hope of any solution to the equation unless $f$ is continuously diffrentiable.
Comment: @TheoBendit We even get fore free that $f$ is twice continuously differentiable ... :)
Comment: Well, if $f$ is a (differentiable) function that is a solution to this equation, it will be continuously differentiable for free, since $$f'(x) = e^x - \int_0^x f(t) \,\mathrm{d}t,$$ both terms of which are differentiable, by the fundamental theorem of calculus.
Comment: But that's not I want to ask initially. I want to know the property of continuously differentiable. I'm sorry to mislead you.
Comment: Well, this example show that $f$ being continuously differentiable is a natural assumption in some problems.


Derivative of trig function

Question: Find the second derivative of $ \arcsin(2x^3) $
The solution says for the first derivative :
$ \dfrac{1}{\sqrt{1-(2x^3)^2}} \cdot 6x^2 = \dfrac{6x^2}{\sqrt{1-4x^6}}  $
When i answered the first derivative i got to :
$ \dfrac{\cos(2x^3) \cdot 6x^2}{\sin^2(2x^3)} $
So what am i missing ?
Comment: @Tennisman: Hint: What is the derivative of $\arcsin(x)$, see http://www.math.com/tables/derivatives/tableof.htm. You can also see this nice approach: http://ocw.mit.edu/courses/mathematics/18-01sc-single-variable-calculus-fall-2010/1.-differentiation/part-b-implicit-differentiation-and-inverse-functions/session-15-implicit-differentiation-and-inverse-functions/MIT18_01SCF10_Ses15c.pdf
Comment: You assumed that $\sin^{-1}x$ means $\frac{1}{\sin x}$. It doesn't. It means the angle (number) between $-\pi/2$ and $\pi/2$ whose sine is $x$. Another name for it, better I think, is $\arcsin x$. By the way, if it is, you missed a minus sign.
Comment: Do not confuse $\sin^{-1}{x} = \arcsin{x}$ with $(\sin{x})^{-1}=\csc{x}$
Comment: $\arcsin(x)=y$ means $-\pi/2 \leq y \leq \pi/2$ and $\sin y = x$. Do not confude $\arc \sin(x)$ and $1/sin(x)$.
Answer:
simply derivative of $\arcsin{x}$ is $\frac{1}{\sqrt{1-x^{2}}}$ don't get confused in $sin^{-1}x$  and $(sinx)^{-1}$

Derivative of trig function


How is latency / travel time determined when you execute a traceroute?

Question: This is simply a question placed out of curiosity.  When you execute a traceroute, and get some time durations back for the latency/travel time, how are those calculated?  It would seem more than likely that the 'current time' on each stop in the route would be variable, and you can't exactly ask a server for what current time it has to figure out the offset, because you don't know how long it takes to make/receive that request.
Answer: It has nothing to do with the wall-clock time on the systems involved.
Whatever system you're doing the traceroute from knows when it sent the ICMP request, and knows when it received the reply. It can then calculate how long the reply took to arrive.
Comment: You were thinking too hard. :)
Comment: Wow, I feel ... really silly now. So obvious.  Thanks.
Comment: All other variables being equal, the simplest answer is usually the correct one
Answer:
Time is relative to the host performing the trace.
It doesn't matter what the actual time is at any of the hops or what their time offset is.
It doesn't matter what time it is on the host or what it's time offset is. A trace determines the amount of time it takes for the ICMP packets to be sent out and for the replies to be received. As such, the system time and time offset are irrelevant.


Recursividade números pares em C++

Question: O objetivo do código abaixo é, através de um método recursivo, retornar a quantidade de numeros pares entre dois números colocados pelo usuário. Não consigo entender por que o meu método quant só retorna 0.
#include <iostream>

int quant(int num1, int num2){
    int resul = 0;
    if((num1<num2) && (num1%2==0)){
        resul += quant((num1+1),num2);
        return resul;
    } else {
        return resul;
    }
}

int main(int argc, char** argv) {

    int n1,n2;

    printf("Digite o primeiro numero: ");
    scanf("%d", &n1);
    printf("Digite o segundo numero, maior que o primeiro: ");
    scanf("%d", &n2);

    int pares;
    pares = quant(n1,n2);
    printf("A quantidade de pares entre  %d %s %d %s %d",n1," e ",n2," e: ",pares);
    return 0;
}

Comment: Olhe seu caso básico. O `else`. Ele só pode retornar 0. O caso recursivo retorna 0 + valor da chamada recursiva. O que resulta em apenas 0.
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 (quando tiver pontuação suficiente).
Answer: Como eu disse em comentário, seu valor básico é 0. O resultado recursivo é 0 + retorno do próximo passo recursivo. Então você não consegue sair do 0. Pode fazer quantos passos recursivos quiser, sempre retornará 0, pois em nenhum momento há acréscimo de valores.
A correção envolve duas coisas:

o caso base é apenas é unicamente apenas quando o primeiro argumento for menor do que o segundo, retornando 0
quando encontrar um par no primeiro argumento, marque como par e retorne 1 + resultado da chamada recursiva; caso não for par, retorne só o resultado da chamada recursiva

Essa condição de parada evita imediatamente que se entre em recursão infinita.
Simplesmente com essas condições, o código seria escrito assim:
int contaParesRecursivo(int num1, int num2) {
  if (num1 > num2) {
    return 0;
  }
  int ehPar = num1 % 2 == 0? 1: 0;
  return ehPar + contaParesRecursivo(num1 + 1, num2);
}

De toda sorte, como esse problema é claramente não recursivo, eu preferiria resolvê-lo em o(1). No caso, a resposta de apenas um passo seria assim:
int contaParesO1(int num1, int num2) {
  if (num1 > num2) {
    return 0;
  }
  return (num2/2) - ((num1 -1)/2);
}

Explicando:

x/2 em operação inteira retorna exatamente quantos números pares há no intervalo (0, x]
num1-1 nesse caso serve para pegar tornar o intervalo aberto no limite superior; a fórmula então para a quantidade de pares se aplicará então ao intervalo (0, num1 - 1], que no caso é idêntico a (0, num1) nos inteiros
assim, a quantidade de pares no intervalo [num1, num2] é transformado na quantidade de pares no intervalo (0, num2] menos a quantidade de pares no intervalo (0, num1)
a condição inicial que retorna 0 garante que não seja passado um intervalo invertido

sem essa condição o resultado de contaParesO1(10,1) seria -4, o que não faria muito sentido

essa fórmula só funciona para números naturais diferentes de 0
Answer: Eu costumo dizer que recursão é abusada. Fazem onde é mais simples fazer um laço. Mas se é para fazer recursão tem que ser no estilo funcional. Funções recursivas com mais de uma linha costumam estar filosoficamente erradas, mesmo que o resultado esteja certo:
#include <stdio.h>

int quant(int num1, int num2) {
    return num1 < num2 ? quant(num1 + 1, num2) + (num1 % 2 == 0) : 0;
}

int main(int argc, char** argv) {
    int n1,n2;
    printf("Digite o primeiro numero: ");
    scanf("%d", &n1);
    printf("Digite o segundo numero, maior que o primeiro: ");
    scanf("%d", &n2);
    printf("A quantidade de pares entre %d e %d e' %d", n1, n2, quant(n1, n2));
    return 0;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Agora a função está com cara de recursiva. Foi difícil enxergar assim porque este não é um problema tão claramente adequado para recursão.
Toda função recursiva tem que ter um branch, ou seja, uma decisão que indique quando deve terminar a recursão, assim como todo laço tem uma condição de saída. Se não fizer isto ou entra em loop infinito ou dá um valor padrão se fizer algo que impeça a recursão infinita.
O que eu fiz é estabelecer qual é a condição que termina a recursão e ela é uma só:
num1 < num2

Esta é a condição que terminaria o laço e é isso que eu usei para decidir o fim, e só no fim é que o valor deve ser 0. No seu código ele vale 0 em todos os casos, por isso dá 0.
Mas tem uma condição que determina se deve somar 1 ou não. Isso em código mais imperativo seria um if e não poderia estar junto da condição de saída da recursão. Juntar ambas foi um outro erro. Isso seria a verificação se é par ou não:
num1 % 2 == 0

Na verdade em C é comum fazer apenas:
num1 & 1

Não usei if porque é um pouco caro e neste caso não é necessário, afinal o resultado desta conta será 0 ou 1, que é o mesmo resultado que um if gera, então melhor não usá-lo já que o custo será menor (se o compilador não conseguir otimizar).
Use o operador condicional para ficar em uma linha. Em código estilo funcional o estilo imperativo com if fica esquisito.

Recursividade números pares em C++


How to open anchor in a modal window, not a new tab

Question: This site demos Social Sharing code such as 'share to Facebook'.  Here, clicking  the links on the left opens the sharing in a modal window.  Their code:

I want a similar effect and I have the following anchor but this opens in a new tab.  I want it to open in a modal window:

How can I achieve this please?  Possibly using Bootstrap?
Answer: Replace your code with this::

It will work..
Comment: Thanks.  That's exactly what I was looking for!
Comment: @DaveChambers If it helped you please upvote the answer and accept it to help others.
Comment: I can...in 4 seconds - just waiting ;-)
Answer: You can use this. I hope it helps.
<button>Click FB</button>

Comment: Happy Coding :)
Comment: Thanks.  That does work but I had to adapt the code slightly so I accepted Rana's answer as that was more 'ready to use'.  But thank you for your help.  I upvoted your answer
Comment: @DaveChambers Thanks


Techniques for memorizing a musical idea and "saving it to paper"

Question: Sometimes I have a very nice musical idea, with orchestration too, and I clearly hear it in my mind as if I was listening to a CD.
But I cannot retain it. The only way is to play it over and over in my mind, but then I cannot even walk or drive.
Cold you suggest some technique for "saving to hard disk"? (Somehow so that as I have time I can later write it down.)
I have a degree in classical piano, I also studied classical composition for some years, so I have a musical background.
Comment: I occasionally have moments where I think up a melody and my brain fleshes it out into an orchestral piece -- no idea how -- but I know very little about composition, so I can't write *anything* down.  Very frustrating.
Comment: @Matthew Read: I highly, highly recommend practicing transcribing your ideas.  The ability to turn melody into notes is highly complimentary to the ability to turn notes into melodies.  Developing that skill has vastly improved my sight-reading.
Comment: I always find it easy to read the notes but I don't find a similar ease with writing them.  When reading the key is always implied and deviations from it are clearly indicated.  When writing you have to take time to figure out what key you're in, and you have to logically analyze each time you go outside of it.  I find this extremely detrimental to my own creative process, although I wouldn't disagree that this is because I lack practice and discipline.
Answer: This won't help with full orchestration and the like -- if you're hearing all that clearly then you're way ahead of me.  But for melody, shape of harmony, rhythms you want to capture, etc, a voice recorder can help.  I've found that sometimes a melody deteriorates as I try to transcribe it from my mind, so I start by singing/humming/la-la-laing it into a recorder and then I work on it, falling back to that copy if I need to.  If you have a smartphone, there's an app for that. :-)  (I don't, so I can't tell you its name.)
Of course, the process of writing it down can improve it, such that I no longer care about the version on the recording.  It's ok; I wasn't going to share that recording with anybody else anyway.
Comment: Thanks, it is probably the only thing to do. Now smartphones are very popular and what you suggest is doable. In the past it was mandatory to always have a tape recorder at hand... Not very pratical at all. Yes singing some melody at least it can be a sketch. By the way hearing a full orchestration in the mind is somehow also a self-illusion, it is not a real composition, it is a kind of illusion, this means that anyone it must be re.composed from scratch, but having a line to follow (recorded on smartphone) it can help.
Comment: By the way for anyone interested in trasnscribing music by ear there is a non ortodox approach in this book I read in the past (the author is dead): http://www.rongorow.com/
Answer: The best solution is probably going to be just transcribing the idea in musical notation but if you are able to sing the melody, any multi-track recording software on a smartphone should suffice to get enough down to jog your memory enough to get back to where you were (look out for software that has a looped recording capability as this is especially good for getting down harmonic ideas fast)


Change size of subplot that are on the same axis

Question: I have created a plot that contains two plots within the same axis similar to this: https://matplotlib.org/1.5.1/examples/pylab_examples/ganged_plots.html
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))

x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))

Is there a way to change the size of the subplots when they are on the same axis? For example, right now the subplots are both equal in size, is there I can reduce the top plot to be only a quarter of the size?
Comment: Change `0.8` to `0.8/4` ?
Comment: You're looking for fig.add_subplot(). I recommend giving [this](http://jonathansoma.com/lede/algorithms-2017/classes/fuzziness-matplotlib/how-pandas-uses-matplotlib-plus-figures-axes-and-subplots/) a read.
Answer: Positioning by hand is fine, but the more modern way to do this would be to use gridspecs:
import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 1,
    gridspec_kw={'height_ratios':[1, 4], 'hspace':0}, sharex=True, sharey=True)

x = np.linspace(0, 10)
axs[0].plot(np.sin(x))
axs[1].plot(np.cos(x))
axs[0].set_ylim(-1.2, 1.2)
plt.show()