Git alias para o nome do branch atual

Question: No meu trabalho é muito comum alternar entre feature branches e stage/develop branches várias vezes durante o dia. E muitas dessas vezes eu preciso escrever ou usar tab pra completar o nome do branch mesmo estando dentro dele. Eu queria algo que agisse de forma semelhante a um this em programação: uma referência ao nome do branch atual.
Problema:
$ git checkout -b feature/nova-feature
// aqui eu trabalho na nova feature ate ficar ok
$ git push origin feature/nova-feature (*)
$ git checkout stage && git merge feature/nova-feature (*)
$ git push origin stage (*)
$ git checkout feature/outra-feature
// trabalho em mais alguma coisa
$ git push origin feature/outra-feature (*)
$ git checkout stage && git merge feature/outra-feature (*)
$ git push origin stage (*)

 etc

Em 8 interações com o git eu tive que escrever 6 vezes o nome do branch em que eu estou (em 3 branches diferentes).
O que eu já tenho hoje no meu .gitconfig
[alias]
    mg = merge --no-ff --no-edit
    mc = commit -a --no-edit
    df = "!git diff --color | diff-so-fancy"
    ck = "!git checkout $1 && git pull origin $1"
    gr = "!git branch | !grep $1"
    msp = "!git ck $1 && git mg $2 && git push origin $1"

ck, gr e msp são alias que me permitem escrever uma vez só o nome do branch quando vou concatenar.
O que eu queria:
$ git checkout -b feature/nova-feature
// aqui eu trabalho na nova feature ate ficar ok
$ git push origin this
$ git checkout stage && git merge this
$ git push origin this
$ git checkout feature/outra-feature
// trabalho em mais alguma coisa
$ git push origin this
$ git checkout stage && git merge this
$ git push origin this

De forma que eu pudesse criar alias pra essas ações mais comuns e que funcionem em qualquer branch, sem precisar escrever o nome. Tem jeito?
Comment: veja se isso te ajuda https://www.reddit.com/r/git/comments/1v16qc/how_do_i_reference_the_current_branch_in_a_git/
Comment: Isto pode ajudar um pouco no seu fluxo: se quiser voltar para a branch anterior, você pode usar `git checkout -`
Comment: Perfeito, vou apagar meus comentários daqui então, pra não deixar bagunça na sua postagem.
Answer: Ricardo você pode usar os alias da seguinte forma:
[alias]
#Pega seu branch
branch-name = "!git rev-parse --abbrev-ref HEAD"
#Publica seu branch
publish = "!git push -u origin $(git branch-name)"
#Deleta a versão remota do seu branch
unpublish = "!git push origin :$(git branch-name)"
Dessa forma você usaria assim:
$ git checkout -b feature/nova-feature
// aqui eu trabalho na nova feature ate ficar ok
$ git publish
$ git unpublish

De uma olhada nos alias utilizados neste link do @robmiller usuário do github, que acredito que você conseguira implementar um workflow de trabalho bem produtivo.
Comment: Adicionei o formato que fiz funcionar, ficou massa. Valeu!
Comment: opa, não resolveu 100% não mas acho que me levou pro lugar certo, vou ver aqui e atualizo
Comment: Tranquilo Ricardo, acredito que desta forma da para você reduzir bastante a digitação e mudar o fluxo seu para ficar mais pratico :)
Answer: Solução Encontrada
seguindo os passos da resposta do Diego Garcia, cheguei à seguinte configuração, que me permite nunca precisar escrever o nome do branch atual:
[alias]
    branch-name = "!git rev-parse --abbrev-ref HEAD"
    mg = merge --no-ff --no-edit
    ck = "!git checkout $1 && git pull origin $1"
    cm = "!BRANCH=$(git branch-name); git ck $1 && git mg $BRANCH"

Forma de usar concatenando os aliases (pra todos os outros comandos que precisarem desse mesmo padrão, basta usar o formato do alias cm acima)
$ git cm stage

Equivale a:
$ git checkout stage && git pull origin stage && git merge branch-atual --no-ff --no-edit

Comment: Ficou show Ricardo :)
Answer: Você pode controlar isso através da configuração push.default.
A opção que você quer é a current.
git config --global push.default current

Então você pode usar apenas git push e vai conseguir esse comportamento.
Para ver outras opções possíveis consulte o man page do git-config (ou clique aqui)

Git alias para o nome do branch atual


How to get a location data from photos from iPhones?

Question: I am having a trouble with extracting a location data from photos from iPhones by using PHPhotoLibrary. Can anyone teach me how?
Is it similar to how to do the same thing by using ALAssetsLibrary? Please.
Answer: You can use PHAsset location property   to retrieve location data of image .
see PHAsset
Here is code:
  let CameraImages = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: nil)
    CameraImages.enumerateObjectsUsingBlock({
        (obj, idx, bool) -> Void in
        var asset = obj  as! PHAsset

        let locationData = asset.location

    })

EDIT:
@Ryo comment: retrieve location data from the image that i choose from imagePickerController?
You can do as
   func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{

    self.dismissViewControllerAnimated(false, completion: nil)
    var arrayURL:[NSURL] = []
    var url = info[UIImagePickerControllerReferenceURL] as! NSURL
    arrayURL.append(url)
    let ImageAsset =  PHAsset.fetchAssetsWithALAssetURLs(url1, options: nil)

    ImageAsset.enumerateObjectsUsingBlock({
        (obj, idx, bool) -> Void in
        var asset = obj  as! PHAsset
        let locationData = asset.location
        print(locationData)

    })

}

edit 2 :
@ Ryo comment : how can i get a longitude and altitude from this location data?
just add this line
  if locationData != nil {
            let longi = locationData?.coordinate.longitude
            let lati = locationData?.coordinate.latitude
        }

Comment: now how can i retrieve location data from the image that i choose from imagePickerController? I mean,, how can i get a data from one specific image?
Comment: I just tried it but what i got from "print(locationData)" was nil. what should i do? Thnak you for answering my questions and helping me out!
Comment: check your image has GPS data or not. it is giving nil because your image does not have GPS data.
Comment: and it may be a silly question but how can i get a longitude and altitude from this location data? i want them separately.


Query: Find most recent 5 posts from distinct users

Question: Let's say that we have a users table, and a user can have many posts (posts have the user_id column).
I want to retrieve posts for the first 5 users, but only one post per user. So, at the end I want to have 5 posts, where each post belongs to a different user. How can I do that in SQL?
Comment: By "first 5 users", do you mean the users with the five lowest `user_id`s (0-4; 1-5; 1,3,4,5,8; or whatever they happen to be)?
Comment: `select` with a `join` and some distinct/grouping magic.
Comment: PostgreSQL. The ordering doesn't matter.
Answer: You should have two tables
Table : users ; Columns : users_id , user_name
Table2: posts ; Columns : post_id , post_description , users_id

And now to retrieve all user with one post for each
SELECT * FROM users as u
LEFT JOIN (SELECT * FROM posts LIMIT 1)  as p on p.users_id = u.users_id
LIMIT 5 ORDER BY ASC

If you want to get the oldest post for each user
SELECT * FROM users as u
LEFT JOIN (
    SELECT
        MIN(post_id) as post_id ,
        post_description ,
        users_id  FROM posts
    )  as p on p.users_id = u.users_id
LIMIT 5 ORDER BY ASC

And for latest post use MAX(post_id) instead of MIN(post_id)
Answer: Maybe it will help you:
select *
  from users u
  join posts p on p.idUser = u.id
               and p.id = ( select max(id) from posts where p.id=u.id )
 ORDER BY i.id LIMIT 5

Answer: This will give you the latest five postings (assuming a higher ID post is "newer"), forcing each result to be from a different user.
SELECT p.user_id, MAX(p.post_id) AS post_id
FROM posts AS p
GROUP BY p.user_id -- get unique users
ORDER BY p.post_id DESC -- sort results by post_id number, descending
LIMIT 5

With this method, if you need to load other user or post data, it would be best to load it separately after you get the desired user ids and post ids.


Pullback of 2 functors one of which creates limits and the other preserves

Question: I have been solving this problem and do not know what to do next and if I am thinking in the right direction.
Suppose we have this pullback square and know that $H$ creates and $G$ preserves limits.
The exercise is to prove that then $H'$ creates limits.
$$
\require{AMScd}
\begin{CD}
A' @>H'>> A \\
@VG'VV @VVGV\\
X' @>H>> X
\end{CD}
$$
Here is my (unfinished) solution:
Let $R: J \to A'$ be a functor such that the composite $H'R$ has a limit in $A$. Now I need to show that $R$ has limit in $A'$.
Since $G$ preserves limits, the composite $GH'R$ has a limit. But $GH'R = HG'R$, so $HG'R$ also has a limit. Since $H$ creates limits, it means that $G'R$ has a limit.
Then I look at 2 constant functors $F:J \to A$ and $F':J \to X' $, taking anything to $\lim H'R$ and $\lim G'R$ respectively.
Since this is a pullback diagram, there exists $T:J \to A$ such that $F = H'T$.
That means that the image of $T$ in $A$ is some object $y$ such that $H'y = \lim H'R$.
Now I am trying to prove that this $y$ is in fact $\lim R$.
$T$ acting on morphisms brings cone.
But I do not know how to prove that this cone is universal. I would be very grateful for your help!
Thank you in advance.
Note: this is an exercise from MacLane, V.6.3
Answer: Suppose $D:J\to A'$ is a diagram in $A'$.
Let $(x,\sigma : \Delta_x \to H'D)$ be a limiting cone in $A$.
Since $G$ preserves limits,
$(Gx,G\sigma : \Delta_{Gx}\to GH'D)$ is a limiting cone for $GH'D=HG'D$.
Since
$H$ creates limits, there is a unique cone $(y,\tau:\Delta_y\to G'D)$ such that
$Hy=Gx$ and $H\tau = G\sigma$, and moreover, this cone is a limiting cone for $G'D$.
Then $((x,y),(\sigma,\tau))$ is a cone over $D$ in the fiber product (given by components). Moreover, by uniqueness of $(y,\tau)$, this cone is the unique cone with
$H'(x,y)=x$ and $H'(\sigma,\tau)=\sigma$.
If we had any other cone (again, given by components) $((x',y'),(\sigma',\tau'))$,
then by definition, $(x',\sigma')$ would be a cone over $H'D$
and $(y',\tau')$ would be a cone over $G'D$ such that $(Gx',G\sigma')=(Hy',H\tau')$ is a
cone over $GH'D=HG'D$. Therefore there are unique maps
$a : x'\to x$ and $b:y'\to y$ such that $Ga=Hb$, and $\sigma \circ \Delta_a =\sigma'$,
and $\tau\circ\Delta_b = \tau'$. Thus $(a,b) : (x',y')\to (x,y)$ is a valid map in the fiber product, and has the property that
$(\sigma,\tau)\circ \Delta_{(a,b)} = (\sigma',\tau')$, and moreover $(a,b)$ is unique with this property.
Thus $((x,y),(\sigma,\tau))$ is a limiting cone, as required.
Some comments on your approach
You need to be a bit more careful about the uniqueness statement in the definition of creates limits. Also $T$ doesn't act on morphisms in the cone. $T$ is a diagram. Not sure what's going on with that stuff. You may be struggling to finish the proof, since you don't seem to have an explicit description of the morphisms in the limit cone you claim to have constructed in your question.
Comment: Recall that the fiber product category can be thought of as the subcategory of the product category of objects $(x,y)$ such that $Gx=Hy$ and morphisms $(f,g)$ such that $Gf=Hg$.
Comment: Alternatively, consider $J_0$, meaning $J$ with a freely adjoined initial object. Then a diagram of $J_0$ is a diagram of $J$ together with a cone on it. So if we have cones $J_0\to A$ and $J_0\to X'$ which become equal when we apply $G$ or $H$ respectively, then there is a unique functor (cone) $J_0\to A'$ projecting to both of our original cones.
Comment: What does this:"((x,y),(σ,τ)) is a cone over D in the fiber product (given by components)" mean? Or rather, how exactly to find it in A`?


Show that if $k \in \mathbb{N}$ is fixed and $|b| < 1$, then $n^kb^n \longrightarrow 0$ when $n\longrightarrow \infty$

Question: Show that if $k \in \mathbb{N}$ is fixed and $|b| < 1$, then $n^kb^n \longrightarrow 0$ when $n\longrightarrow \infty$
I have been struggling with this prove. Any suggestions would be great!
Comment: Write $n^{k}b^{n}=\frac{n^{k}}{1/b^{n}}$, then apply L'Hopital's rule to the limit repeatedly. As a simple case, consider the limit as $n\to\infty$, for $n/b^{n}$. It certainly tends to $0$ upon one application of$L-Hopital's rule.
Answer: You may apply the ratio test:
\begin{align*}
\limsup_{n\rightarrow\infty}\left|\frac{(n+1)^{k}b^{n+1}}{n^{k}b^{n}}\right| = \limsup_{n\rightarrow\infty}\left(\frac{n+1}{n}\right)^{k}|b| = \limsup_{n\rightarrow\infty}\left(1 + \frac{1}{n}\right)^{k}|b| = |b| < 1
\end{align*}
Consequently, the corresponding series
\begin{align*}
\sum_{n=1}^{\infty}a_{n} = \sum_{n=1}^{\infty}n^{k}b^{n} = b + 2^{k}b^{2} + 3^{k}b^{3} + \ldots
\end{align*}
converges. Hence we conclude that $a_{n}\to 0$ just as desired.
Answer: This is a method using the binomial formula only. We may assume that $0<b<1$. Accordingly $b=(1+\varepsilon)^{-1}$ with $\varepsilon>0$. But $(1+\varepsilon)^n=\sum_{j=0}^n \binom{n}{j}\varepsilon^j>\binom{n}{k+1}\varepsilon^{k+1}$ for $n>k$. Then $0<n^k b^n<\frac{n^k}{\binom{n}{k+1}\varepsilon^{k+1}}\leq c (\frac{n}{n-k})^k \frac1{n-k}$ with some positive constant $c$. But the last expression tends to $0$ for $n\to\infty$ implying the desired result.
Answer: Let
$$c = \frac{1}{b} \tag{1}\label{eq1A}$$
Since $|b| \lt 1$, you have $|c| \gt 1$. You are thus trying to determine
$$\lim_{n \to \infty}\frac{n^k}{c^n} \tag{2}\label{eq2A}$$
The numerator and the absolute value of the denominator both go to $\infty$. As Representation's question comment indicates, use L'Hôpital's rule $k$ times on the numerator and denominator to get the limit is $0$ since the numerator will be the fixed $k!$ then, but the absolute value of the denominator will still be going to $\infty$.


Limit of difference quotient of $\frac{t^4}{2}+t^3-\frac{t^2}{2}+1$

Question: I am trying to compute the limit of the difference quotient of the function $x(t)=\frac{t^4}{2}+t^3-\frac{t^2}{2}+1$ at $t=1$, i.e. $$\lim_{\ \Delta t\to 0}\frac{x(1+\Delta t)-x(1)}{\Delta t}$$.
Since $x(1+\Delta t)=\frac{\Delta t^4+6\Delta t^3+11\Delta t^2+8\Delta t+4}{2}$ and $x(1)=2$ we have $$\lim_{\ \Delta t\to 0}\frac{x(1+\Delta t)-x(1)}{\Delta t}=\lim_{\Delta t\to 0}\frac{\frac{\Delta t^4+6\Delta t^3+11\Delta t^2+8\Delta t+4}{2}-1}{\Delta t}=\frac{1}{2}\lim_{\Delta t\to 0}\frac{\Delta t^4+6\Delta t^3+11\Delta t^2+8\Delta t+2}{\Delta t}$$.
Now, I have tried factorizing the polynomial, changing variables, etc. but I haven't been able to obtain the value $4$ (which I know is true by differentiating the polynomial and setting $t=1$) and worse, I haven't been able to not make it diverge to infinity.
So, I would appreciate if someone could tell me how to handle this limit, thanks.
Answer: You made a mistake in that step, the correct is as below
$$\lim_{\ \Delta t\to 0}\frac{x(1+\Delta t)-x(1)}{\Delta t}=\lim_{\Delta t\to 0}\frac{\frac{\Delta t^4+6\Delta t^3+11\Delta t^2+8\Delta t}{2}}{\Delta t}=\frac{1}{2}\lim_{\Delta t\to 0}\frac{\Delta t^3+6\Delta t^2+11\Delta t+8}{2}=4$$.


Time Independent Schrodinger equation

Question: $-k^2f''(x)=(E^2-V(x))f(x)$
I have checked for many V(x) that the set of solutions to this differential equation are complete and have an orthogonal basis set, is this always true for all V(x)?
Comment: Complete means every square integrable function can be written as int a(k)z(k,x) dk , where z(k,x) is all solutions parametrized by k, and a(k) is allowed to be a delta function
Comment: orthogonal means int z(k,x)*z(b,x) dx vanishes when b not equal to k
Answer: I'm not sure what you mean by "complete and have an orthogonal basis set".  If $V(x)$ is continuous, there is always a two-dimensional vector space of solutions.  The solutions may or may not be in $L^2$ near $+\infty$ or near $-\infty$.  You might look up
http://en.wikipedia.org/wiki/Spectral_theory_of_ordinary_differential_equations#Limit_circle_and_limit_point_for_singular_equations
Comment: Complete means every square integrable function can be written as int a(k)z(k,x) dk , where z(k,x) is all solutions parametrized by k, and a(k) is allowed to be a delta function
Comment: In order to use the Spectral Theorem, you want a self-adjoint operator.  For your operator to be essentially self-adjoint on $C_0^\infty$ (the smooth functions of compact support) you need $V(x)$ to be in the limit point case at $+\infty$ and $-\infty$.

Time Independent Schrodinger equation


How to filter a wchar_t array?

Question: given:
wchar_t filter_chars[] = L".+,?=&";
wchar_t haystack[] = L"words+punctuation&special_chars?";

desired result:
wordspunctuationspecialchars

how could i remove special chars from a given (unicode) string?
i'm using win32 c (no c++)
here is what I tried:
void filter(wchar_t str[]) {

    wchar_t buf[80];
    ZeroMemory(buf, 80);

    UINT i, j;

    for(i = j = 0; i < wcslen(str); i++) {
        if (!wcschr(filter_chars, str[i])) {
            wcscpy((wchar_t*)buf[j], (wchar_t*)str[i]);
        }
    }

    wcscpy(str, buf);
}

Comment: Wide string literals need the `L` prefix, `L"like this"`.
Comment: oops, sorry, i actually had that in my original code, but still not working.
Comment: Your loop also seems to make no sense. What's the point of `j`? And why do you always copy the entire string tail, rather than just one character?
Comment: Is there any string copy(wcscpy((wchar_t*)buf[j], (wchar_t*)str[i]); ). I think only charector wise copying is required. Also increment the valu of j too
Answer: The same way you do it for an ordinary string:

/*dest must be at least strlen(src) wide*/
wchar_t *filter(wchar_t dest[], wchar_t const src[], wchar_t const filter_chars[])
{
    size_t iSrc=0, iDest=0;
    for(iSrc=0 ; src[iSrc] != L'\0' ; ++iSrc)
    {
        if(NULL == wcschr(filter_chars, src[iSrc]))
            dest[iDest++] = src[iSrc];
    }
    dest[iDest] = L'\0';
    return dest;
}

You can also add a version with a specified buffer size for dest. I don't remember how aliasing works in the standard, so you may or may not be "legally" able to call this function with dest equal to src.
Comment: You're missing the `return`.

How to filter a wchar_t array?


Update label text with timer on UI Thread, without blocking the UI

Question: I have a label that i want to update with every 10 sec. Unfortunately, as it is right now, the event blocks the UI which means that i can't interact with the application.
I tried to make a new Thread, to run the task, but the application tells me that I can't make UI specific changes from a non-main thread.
The code is as follows:
Public partial class FrontPage : ContentPage
{
    public FrontPage()
    {
        updateLabel();
    }
    updateLabel()
    {
        while(true)
        {
            test.Text = i;
            Thread.Sleep(10000);
            i++;
        }
    }
}

Since I need to run this asyncronously in order to not block the UI, I suspect that the solution involves await/async operators. Unfortunately i'm not sure how to implement it, in this case.
Answer:
to understand how i can run a method on my UI thread, and still interact with the UI. Therefore, using a Timer is not a possibility in this case i'm afraid.

You can use a thread (via Task.Run) and then use Device.InvokeOnMainThreadAsync or Device.BeginInvokeOnMainThread to execute UI updates within that "background" thread:
Task.Run(async() =>
{
    while (true)
    {
        await Device.InvokeOnMainThreadAsync(() =>
        {
            test.Text = i;
        });
        await Task.Delay(10000);
        i++;
    }
});

Note: Also do not use Thread.Sleep as that will hang the entire thread, including its message pump (a really bad thing when it is the UI/main thread).
Comment: Uh, your code above doesn't do _anything_ to address any of what you describe. Indeed, it makes such problems _worse_ because it adds new transitions between threads, and additional objects. The fact that the OP wants a "non-timer" solution doesn't excuse the extra layers of useless thread-switching your suggestion has.
Comment: What is the point of using `async` and `await` if you're not going to actually take advantage of it? It would be much better to just remove the `Task.Run()` and the `await Device.InvokeOnMainThreadAsync()`. The `await Task.Delay(10000);` will yield the thread back to the caller, and when the delay expires, the method will continue running in the main thread, just as desired. You don't need all that other stuff.
Comment: @PeterDuniho The whole point it to remove as much processing from the Main/UI thread as possible and in a mobile env. w/ multi-core|large|small-core scheduling, consuming Main/UI thread cycles comes with producing "laggie" apps, UI yank, higher battery usage, etc...
Comment: @PeterDuniho And he is not looking for a "Timer" solution... see his comments in the other answer.
Comment: See the non-timer example, the second suggestion in [this answer for the marked duplicate](https://stackoverflow.com/a/25212213). It shows what your answer _should_ have been (ignoring for a moment that your answer never should have been in the first place, given how easily found the duplicate question was).
Comment: @PeterDuniho Well, I will totally disagree with your statement, my perspective is from practical usage to benchmarking UI yank on 100s of mobile devices over 10 years (in a testing suite, we have access to 1000+ Android|iOS devices, so yea, I would absolutely not do it the way you are describing...)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/198088/discussion-between-sushihangover-and-peter-duniho).
Answer: use a Timer instead, and use BeginInvokeOnMainThread to force execution of UI updates on the UI thread
System.Timers.Timer t = new System.Timers.Timer(10000);
t.Elapsed += OnTimedEvent;
t.AutoReset = true;
t.Enabled = true;

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
  Device.BeginInvokeOnMainThread( () => {
    test.Text = i;
    i++;
  });
}

Comment: This is just an example I made up, to understand how i can run a method on my UI thread, and still interact with the UI. Therefore, using a Timer is not a possibility in this case i'm afraid.
Comment: "use BeginInvokeOnMainThread to force execution of UI updates on the UI thread"


TLS certificates for various domains in organisation

Question: At our organisation we have one main domain plus a few other secondary domains, which are not subdomains of the former. Something like this:

Main domain: mycorp.org
Secondary domain: another.org
Secondary domain: yetanother.org

We are hosting various web sites on these domains on our own server, using Windows Server and IIS.
We would like to deploy TLS certificates for all domains. From my preliminary research, I gather than most certificate vendors offer company-wide certificates that cover any subdomain from a given one, such as *.mycorp.org, but this wouldn't work for us as we work with totally different domains. In principle I would think that we need multiple single-domain certificates, but as I don't have much experience with certificates, I would like some expert advice:

Do we really need to get separate single-domain certificates?
Can we deploy multiple certificates (one per domain) on to the same IIS server, which is hosting all the web sites?
Is there any additional best practice or recommendation I should be aware of in this setting?

Many thanks.
Comment: You can have a single certificate cover unrelated names like yours, but I strongly suggest to instead use 3 separate certificates. Otherwise the fate of all 3 names is shared: to generate the certificate with the 3 names the CA has to validate each name at the same time. If any does not work then either the certificate is not generated at all or generated with only 2 out of 3 names. There are ample solutions to monitor certificates so having 3 instead of 1 is not a problem. (Just leaving that as a comment because I have no idea to reply to your point 2 about IIS)
Comment: For item #2: In general, you can install as many certificates as you want on your IIS server. You can then bind one certificate to each site, based on whatever hostname the site is listening for.
Comment: @PatrickMevzek Many thanks, that is very useful information.
Comment: @DougDeden: Thank you, that sounds perfect!
Answer: 1-
To host multiple domain names with a single certificate, you will need to use Subject Alternative Names. SANs allow you to specify several hostnames for an SSL certificate. So you could have mycorp.org, www.mycorp.org, another.org, yetanother.org, test.yetanother.org, etc. Some certificate vendors have their own limitations, but generally you should be able to have sites with wildcards and several dozen hostnames listed on a single certificate.
You can see SANs in action by going to www.google.com, then view the certificate details for google.com and view the Subject Alternative Names values. You can see google has several extra domains in their cert.
2-
Yes, you can have several certificates on a single server, each certificate can be assigned to specific IIS sites via the Bindings settings for each site.
3-
It is pretty common practice to use SANs, but as others have mentioned you do somewhat have more secure eggs in one basket. Something happens to that basket and all those eggs are busted.


How do you interpret your features when you standardize your data?

Question: Let's say I have built a boosting tree or neural network and I standardized my features beforehand.  When I built my model, I split my data into training, validation, and test sets - each with their own means and standard deviations for normalization.  This is based on the recommendation of a book, which says it is important not to mix your data, even when it comes to standardization.
Anyways, let's say I have a final model.  Now, I have a new observation and I want to predict the outcome.
What do I do with the new observation? The feature values are obviously not standardized.  Since it is one data point, it doesn't have a standard deviation.  Are there any issues with prediction if I feed this new single observation into my model?  The scaling would be completely off from the ones I fed into the model.
If I need to standardize it, what should my mean and standard deviation be?
Answer: One usual approach would be to use the partitioned data to locate your most optimal model hypothesis. Once you have found your model, ie choice of algorithm, hyperparameters etc you can train it on the entire dataset.
The train and validation sets are there to simulate an environment of unknown data. So you want to make sure that the process you choose for creating val and test sets mimicks how you will receive new data in the real world.
Another point is that in practice you often have some time dependence in your data and you want to incorporate the latest data in your model. However, this latest data is in this case the data you should use for validation and testing. So in the end you want to include this data in the final model.
Once you have done this you can use your final dataset as a basis for normalisation also for incoming data.
If you have no time dependence this might not be needed and you can use the most robust estimates. Since the train data often is many times larger than the test set, this should be used to provide the estimate.
The key takeaway is to make sure that you treat your val and test sets in a way that realistically reflects how new data will appear in reality. And this will also dictate how you do normalization.


In visual studio, how can I write a macro that will insert the date into a comment?

Question: My question is as exact as it is. I am wondering if it would be possible to insert the date or the date and time into a comment without having to manually write it out. But what I would really like to know is, is there a way to do this and will I have to implement something with visual studio to do this for me and if so, how can I do this? Any help will be greatly appreciated! :)
Also, I am coding in C-Sharp and am using Visual Studio 2010.
Comment: What programming language would you be using?
Comment: I am currently writing in C-Sharp.
Answer: In Visual Studio 2010 you write macros in Visual Basic and add them to the Macro Explorer.  Then  call the macros while working in your C# code editor.  I bind my favorite macros to key combinations, so I can quickly run them when needed.
If you are new to macros and the Visual Studio Macro editor check out this link.
MSDN docs for Macros
Here is the code to add a comment and date to your C# code.
 Public Sub AddCommentWithDate()
    Dim doc As Document = DTE.ActiveDocument
    ' only modify the doc, if it is a text document in VS
    Dim textDoc As TextDocument = _
       CType(doc.Object("TextDocument"), TextDocument)

    ' verify that the code editor is C#
    If doc.ProjectItem.ContainingProject.Kind = _
       VSLangProj.PrjKind.prjKindCSharpProject Then
        textDoc.StartPoint.CreateEditPoint()
        textDoc.Selection.Insert("// A comment " & Date.Now)
    End If
End Sub

Here's the results in a C# file.
// A comment 3/18/2013 2:13:38 AM

Answer: You could either write a macro in Visual Studio or use some external program (such as AutoHotKey) to type the text for you.
Answer: When someone posts a comment and you process the form data on your serverside,
maybe you would add a hard return ( or  chr(13)) and then add the date BEFORE persisting the comments to a database or xml file.
so you would end up with something like....
Comments == Comments + Strings.Chr(13) + System.DateTime.Today

or
Comments == Comments + ("
") + System.DateTime.Today

Comment: I think the OP is looking for a Visual Studio macro to insert the date into their C# source code when they add a comment.


How to use Google +1 in a content script without Content Security Policy error?

Question: I'm trying to build chrome extension that uses +1 google api.
My manifest.json looks like:
"manifest_version": 2,
"content_security_policy": "script-src 'self' https://apis.google.com; object-src 'self'",
...
"matches": ["http://demosite.com/*"],
"js": ["js/jquery.js","js/social/plusone.js"]

As you can see I've whitelisted apis.google.com.
My plusone.js looks like:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://apis.google.com/js/plusone.js";
head.appendChild(script);

$('li.subscription').before('<g:plusone></g:plusone>');

As you can see I just inject script tag from whitelisted site.
Unfortunately, when I load a page I got an error:

Refused to load the script
apis.google.com//scs/apps-static//js/k=oz.gapi.ru.Fqrb4MMzOT8.O/m…sv=1/d=1/ed=1/am=IQ/rs=AItRSTNEKbnLkdtNZVz4hKH7VV4tY98scw/cb=gapi.loaded_0'
because it violates the following Content Security Policy directive:
"script-src 'self'".

All similar questions here say I should whitelist site with content_security_policy, but I've done it as you can see. Are there any ideas what's wrong?
Answer:
The extension's Content security policy only applies to extension pages, not content scripts.
When you insert a


Qual é a diferença entre Model::lists() e Model::all()->lists() no Laravel?

Question: No Laravel, temos um método que podemos listar campos de uma tabela no estilo chave valor.
Posso fazer isso de duas formas
Assim:
Usuario::lists('nome', 'id');

E Assim:
Usuario::all()->lists('nome', 'id');

O resultado disso seria:
 [1 => 'Wallace', 2 => 'Guilherme', 3 => 'Bigown', 4 => 'Miguel']

Mas, tendo em visto que existe duas maneiras de fazer isso, qual é a diferença entre as duas?
Answer: Bem, a diferença é a seguinte: Quando você invoca lists você faz com que apenas os campos específicos sejam especificados na query do Orm do laravel e os trás num array.
Exemplo:
Usuario::lists('nome', 'id');

É o mesmo que :
SELECT nome, id FROM usuarios

Já o caso do método all seguido de lists ocorre outra coisa.
Quando chamamos Usuario::all() trazemos todos os resultados existentes na tabela usuarios e com todos os campos selecionados.
SELECT * FROM usuários

O método all retornará um objeto chamado Illuminate\Database\Eloquent\Collection. Esse objeto, por sua vez, possui o método all. Porém internamente, ele utiliza a função chamada array_pluck para capturar apenas os dois itens passados, como chave e valor.
Performance
A diferença de performance é notável entre as duas explicações. lists saí ganhando tanto na execução da query como na quantidade de dados trazidos para o PHP.
Se você for apenas trazer uma lista contendo o par chave-valor do banco, você deverá usar lists.
Porém há casos onde, além de trazer os dados completos do usuário, por questões de necessidade de um tipo determinado, você desejaria transformar um objeto Eloquent\Collection em um array.
Nesse caso, estamos falando de um conceito da orientação a objetos chamado de Reutilização.
Um exemplo disso é precisar de trazer todos os dados do usuário para fazer uma listagem numa tabela, porém ao mesmo tempo precisar de uma listagem desses usuários em um select (aí será necessário usar lists nessa coleção, para não fazer outro SELECT no banco).
Vou dar um exemplo:
 $usuario = Usuario::all();

 // Preciso da lista de nomes e ids para passar para um "select" no html

$usuarios_lista = $usuarios->lists('nome', 'id');


Financial year Statement for All Fiscal year (April to March) in SQL Server

Question: Where can I generate the Financial year report for last 10 years dynamically like this using T-sql:
Months |2007-2008 |2008-2009|   2009-2010 |2010-2011 | Average
-------------------------------------------------------------------
April
May
June
July
August
September
October
November
December
January
February
March
Average

Comment: We need your table structure with sample data to be of any help
Comment: ID, Year, Month, Expense, Datetime, monthorder where my SQL table columns
Answer: I'm not sure what [DATETIME] represents, I'm assuming it is a indicator of month or year year, if not you 'll need to change the where statements to incorporate YEAR and MONTH.
Try something like this:
SELECT '2007-2008' AS FISCALYEAR, SUM(EXPENSE) AS EXPENSE
FROM YOURTABLE
WHERE [DATETIME] BETWEEN '4/1/2007' AND '3/31/2008'
UNION ALL
SELECT '2008-2009' AS FISCALYEAR, SUM(EXPENSE) AS EXPENSE
FROM YOURTABLE
WHERE [DATETIME] BETWEEN '4/1/2008' AND '3/31/2009'
UNION ALL
SELECT '2009-2010' AS FISCALYEAR, SUM(EXPENSE) AS EXPENSE
FROM YOURTABLE
WHERE [DATETIME] BETWEEN '4/1/2009' AND '3/31/2010'
UNION ALL
SELECT '2010-2011' AS FISCALYEAR, SUM(EXPENSE) AS EXPENSE
FROM YOURTABLE
WHERE [DATETIME] BETWEEN '4/1/2010' AND '3/31/2011'

That should get you close to getting the expense for each fiscal year.  To get the average, just do the same and aggregate it.


Crashing almost every minute

Question:
I have no idea why it's crashing. But here is some of my error log:
[Thu Dec 29 03:23:45 2011] [error] [client 188.8.131.52] File does not exist: /var/www/phpMyAdmin
[Thu Dec 29 03:24:38 2011] [error] [client 220.127.116.11] File does not exist: /var/www/crossdomain.xml, referer: http://s.nsdsvc.com/App/DddWrapper.swf?c=4
[Thu Dec 29 03:36:19 2011] [error] [client 188.8.131.52] File does not exist: /var/www/crossdomain.xml, referer: http://s.nsdsvc.com/App/DddWrapper.swf?c=4
[Thu Dec 29 03:48:00 2011] [error] server reached MaxClients setting, consider raising the MaxClients setting
zend_mm_heap corrupted

More
[Wed Dec 28 19:17:32 2011] [error] [client 22.214.171.124] File does not exist: /var/www/sitemap.xml
[Wed Dec 28 19:19:36 2011] [error] [client 22.214.171.124] File does not exist: /var/www/crossdomain.xml
[Wed Dec 28 19:20:38 2011] [error] [client 126.96.36.199] Invalid URI in request 8th-2011-a.html HTTP/1.1
[Wed Dec 28 19:23:08 2011] [error] [client 184.108.40.206] Invalid URI in request 7e12e6845d73e4e HTTP/1.1

This is from my error.log.
My access log is 800MB, do you guys delete your access.log after a while?
Any idea what causes the crash?
Thanks!
EDIT: Surprising it hasn't crashed for 30 minutes now.
Comment: @B14D3: I don't agree! If you disable the access logs, you will not be able to monitor your server usage and see possible errors/hack attempts, etc..
Comment: 800mb log!?!?! logrotate often?
Comment: @Lamar B `# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4
` Should it put it daily?
Comment: On hight load web servers its good to disable access logs.  (Enabling only for testing and diagnoze).
Comment: @Khaled on web server with large number connections enabling access logs can result IO problems. For error you always have error logs. About server usage you have right but thats why I wrote "Enabling only for testing and diagnoze" You can monitor all other server parameters and when you are alarmed that something is going wrong you can always enable access log. I'm talking about hight load web servers if you have server with small amount of connections then disabling access logs gives you nothing
Comment: @B14D3: So, how will you be able to use tools like awstat and webalizer?
Answer: Your screen shot and your error logs are telling two totally different stories.
As per your screenshot you are trying to run apache on 0.0.0.0 on port 80 which is already binded. Check who is listening there. Run the following:
netstat -tanlp | grep 80

After this your logs are stating that server reached MaxClients setting, consider raising the MaxClients setting that means that you have too many connections. Either your website is really popular or someone is trying to bombard your apache with requests to crash it intentionally. You can increase the connections from httpd.conf. Increase MaxClients there to a higher value.
Regarding zend_mm_heap corruptedcheck out this bug report. Some one on stackoverflow fixed it by increasing output_buffering= value in php.ini.
Please use logrotate to reduce the size of your logs. It'll split your logs on the basis of parameters you specify in conf/ Check out other logrotate conffiles in /etc/logrotate.d/
Comment: Since you have not crashed since last 30 minutes, Zend bug might not be the issue. Increase MaxClients for sure.
Answer: I've seen those types of entries in my access logs. It's someone trying to sniff for known exploits, for example the /var/www/phpMyAdmin entry means someone is trying to test to see if you have phpMyAdmin installed under it's default path. If you did they would probably proceed to try to crack the admin password.
It seems like your site is under attack (Denial of Service) in that someone is trying to flood your server so you receive errors like 'MaxClients' being reached.
Here is a pretty good article about setting up some filters to protect you from these types of requests.

Crashing almost every minute


CSS em uma página HTML

Question:
Eu tenho essa página HTML, mas não sei como fazer no meu CSS para conseguir caber 2 desses Retângulos em uma Linha

Aldous

                        Mostrar

Código do CSS
#area-principal {
width: 920px;
padding: 15px;}

#area-postagens {
width: 660px;
float: left;}

.caixa-conteudo {
width: 15%;
background: #fff;
padding: 5px;
margin: 0 auto;
margin-top: 5px;
position: relative;
display: flex;}

.sub-left{
left: 0;}

#nome {
margin-left: 15px;}

#caixa-mini-texto {
margin-top: 13px;
margin-left: 7px;
padding: 5px 9px;
display: block;
background: #f7b600;
color: white;}

Comment: Consegue montar um [mcve] na pergunta?
Answer: Só pra mim entender melhor como tentar te ajudar.
Tu queres fazer com que tu tenha  2 blocos de lado, certo?
No caso:
Miya | Belmond
Saber | Alice
Dessa forma?

  <link href="custom.css" type="text/css" rel="stylesheet" />

.bloco {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-left: 10px;
  display: inline-block;
}

Dessa forma, tens 2 blocos um do lado do outro.
https://prnt.sc/x5nr07
Comment: Vlw mano, consegui arrumar o código e o seu código ajudou, não sabia desse tipo de display
Comment: Isso mesmo, mas não sei como fazer
Comment: Editei minha primeira pergunta pra facilitar a visualização da resposta. Vê se é isso que tu precisa.
Comment: Só uma dica a respeito do teu código.
Tenta organizar ele da seguinte forma:

Div do personagem > nome do personagem (><) foto dele > link de mostrar.
Fica inclusive mais fácil de tu conseguir visualizar e editar teu código depois. Se quiser, eu mando uma resposta com um exemplo
Answer: Tu consegue também manter em duas colunas usando o column-count.
Ver se isso te ajuda.
#area-postagem {
  width: 660px;
  column-count: 2;
  padding: 10px;
  float: left;

/*display: block;*/
/*float: left;*/

}

CSS em uma página HTML


How do I test for significant change when looking at a metric such as "average products added to cart in per session"?

Question: I will try to ask this question via an example. Let us assume we have two groups. Group A & Group B.

Group
Total Products added to Cart
Total Sessions
Avg. products added to cart per session

A
25,000
21,000
1.1905

B
27,500
21,955
1.2526

What I want to understand is, is the difference in avg. products added to cart per session between Group A and Group B, statistically significant?
My initial thoughts was to use unpaired 2-sample t-test. But I am questioning this more and more...mainly because I am getting confused as to whether it is actually appropriate to calculate the std. deviation of the 'average prod. added to cart per session'? Usually in t-tests you calculate the std. deviation of a value such as weight, test scores and not average weight or average score.
Could any one please advise and help me?
Answer: This is like, THE QUESTION, in AB testing.  There are a bunch of ways to answer this, each of which have their pros and cons.  I'll give my thoughts here for posterity.
The t-test
Perhaps the most common approach, even among enterprise software which offer experimentation platforms, is to use the t-test.  Yadayadayada Central Limit Theorem, Yadayadayada asymptotic normality, yadayadayada t-test.  The rationale for using this approach can be found here so I won't belabour the point.
Here is the thing.  In internet experiments, it is very common that the distribution from which your data come from is long tailed.  This means that the normality assumption underlying the t-test can fail and can fail in such a way that the validity of the inference comes into question.  Remember, the CLT tells us that the sampling distribution of the mean is normal, but it doesn't tell us when that happens.
Poisson Regresson and Variants of a GLM
You're counting stuff in the end, so it makes sense that a model like
$$ \log(E(y)) = \beta_{0} + \beta_1 \mbox{Txt} + \log(\mbox{Total Sessions}) $$
could be applied using Poisson regression or Negative binomial regression.  Here, $\beta_1$ is the effect of the variant and the quantity in the log is called an "offset".  Its meant to account for the fact that more products will be added to the cart if you have more sessions.
The benefit of this approach is that you can adjust for customer level variables (like age, past spend, etc) which can further reduce the variance in the outcome, increasing the power of your experiment.  You'd probably need to compute a marginal effect to get an estimate of the average treatment effect however, but that is very easy with R packages.
Winsorization and Adaptive Trimmed Means
Most people will probably reach for winsorization, but I'm dubious of that approach.  I'm dubious because most approaches I have seen just winsorize the data at the 1% and 99% percentiles (or similar) and then go on computing the t test or similar.  However, I'm not convinced that is correct, because the resulting estimate of the standard error does not account for the winsorizing process and is likely an underestimation of the sampling variance of the test statistic.  Now, there may be a solution around this.  I just haven't seen it.
What I have seen is an approach specified in this thread and in this paper.  The approach is similar to winsorization, but instead of clipping the data at percentiles we simply discard the data above and below these quantiles.  The best part is that we can analytically calculate the variance of this procedure, and the simulations shown in that twitter thread I've linked looked very promising.
Which to Use
I don't know.  I'm quite fond of the second approach, but only because we reduce the variance quite a lot by controlling for pre-exposure average products added to the cart per session.  This is a process called "CUPED" in recent papers and should remove the need to adjust for other customer level factors.  All you would need is the treatment effect, the effect of pre-exposure items per session, the intercept, and the offset, which sounds enticing but is subject to assumptions on the likelihood.
Its going to depend on your domain expertise and your data.  In any case, you will need to validate the assumptions you make.
Comment: Thank you for the detailed response. I will be honest, I am starting to learn stats by myself at work, so some of that stuff above flew over my head!

But, I was doing more reading on my problem after I read your response yesterday. What I have now done is looked at the distribution of number of products added to cart for each session - it is heavily right skewed. Based on this, I decided to use Wilcoxon rank sum test.


Uniform Convergence and Equicontinuity

Question: I am reading the proof that is $\{f_n\}$ is uniformly convergent then $\{f_n\}$ is equicontinuous here
at the bottom on page 1.
I understand everything in the proof except when he writes for $j \leq N$ the function $f_j$ is uniformly continuous. What is the justification for this?
Answer: A finite collection of uniformly continuous functions is always equicontinuous.  Can you see why?
Comment: Is the space you are working on compact?  If it is, any continuous function is uniformly continuous.  That is the stated assumption on the PDF you linked above.
Comment: That's not my question. I want to know why they are uniformly continuous in the first place.
Comment: Ok, missed that, thanks.

Uniform Convergence and Equicontinuity


General categorical notion of "structure induced by a map"?

Question: In topology, we can speak of the "[topology induced by a function][1]", which is the (coarsest) topology on $X$ such that $f:X\to Y$ is continuous, given a topology on Y, or vice versa.
I can imagine that there are similar notions of "induced group structure" which gives a set a group structure such that a given function is a group homomorphism, and an "induced vector space structure" and so forth.
Is there a general (categorical) notion of this?
 https://en.m.wikipedia.org/wiki/Induced_topology
Answer: This is actually dramatically different in algebraic than topological situations. If $A$ is equipped with some algebraic structure and $f:A\to B$ is a function, $B$ may not admit any algebraic structure for which $f$ is a homomorphism. Indeed, if $f$ is surjective then such structure is well known to be unique when it exists: $f$ becomes a quotient map, and the operations on $B$ are induces by the operations on $A$. But it doesn't always exist, as the equivalence relation induces by $f$ must respect the algebraic operations of $A$. For instance if $A$ is a group and $f(a)=f(b)=f(e),$ we must also have $f(ab)=f(e)$, which an arbitrary function will not satisfy.
If $f$ is not surjective then the partially ordered set of algebraic structures on $B$ making $f$ into a homomorphism may have multiple elements, but it's discrete, at least if the partial order is defined using homomorphisms given by the identity function on $B$. This is the key difference with topology: the identity map can be continuous without being an isomorphism, which is impossible in algebra.
There is a general theory here, although as I explained above it doesn't apply to your examples. This is the theory of topological concrete categories. Important examples are not that abundant, but uniform spaces and measure spaces are a couple beyond topological spaces.


How to convert Binary Srtring into an integer array in java?

Question: I am reading a file as byte and converting them into binary string using
String.format("%8s", Integer.toBinaryString(resultByteArray[i] & 0xFF)).replace(' ', '0')

After that, using StringBuilder I have combined all strings into one string. Now I want to convert this string into an array like [1,0,1,0....].
Is there any way to do so?
Comment: Yes there is. Now go ahead and give it a try. If you get stuck, you can show us the code, explain where the problem is, and we'll be able to help.
Comment: Yes, there is a way, but why go through `String` as an intermediate representation? Why not convert bytes directly to "bit-array" using bit manipulation?
Comment: @Andreas likely because the OP is a beginner. If it's already in a String of 1's en zeroes, rather than a byte[], then the OP doesn't need to understand about bitshifts and bit masking - it's just a for-loop now.
Comment: @ErwinBolwidt OP is already doing `& 0xFF`. That's bit manipulation.
Comment: @Andreas True. There's a bit of a mismatch between that first expression and the rest of the question. I would guess that the OP just copied the first part from somewhere, but who is to tell..
Comment: @ErwinBolwidt I have solved it using toCharArray() method. I have tried another method before, but, I was getting error related dereferenced. Thank you for your input
Answer: Since you've already compiled it into one big String, you can immediately convert it to a char array. There's a method called .toCharArray() that you can use to return a char array.
Here's an example of this:
http://www.javatpoint.com/java-string-tochararray
Additionally, if you want to convert it to a different type of array, you could iterate through and add it to an array that has the same size as the char array.
Best of luck!


Balanceamento de parênteses

Question: Estou fazendo uma atividade de programação em C envolvendo TAD e PILHA. A proposta da minha atividade é fazer uma biblioteca (pilha.c) utilizando apenas as funções da pilha.h.
Na lisp.c, devo fazer com que o meu programa receba do usuário a quantidade de caracteres, um numero para saber que nivel está determinado caractere e a frase, tendo como resposta se a frase está balanceada entre os parênteses. Caso sim, dizer qual nível está o caracter na frase. Caso não esteja balanceada, apenas informar que não está. Por exemplo:

(((a)(b)c))
7 caracteres
Caractere 2
Resposta do programa: A frase está balanceada e o caracter b está no nível 3.

lisp.c:
#include <stdlib.h>
#include <stdio.h>
#include "pilha.h"

int main(){
    int QtCar, idx, lvl;
    char charlvl[10];

    printf("Quantidade de caracteres:\n");
    scanf("%d",&QtCar);

    char Fr[QtCar];
    printf("Frase:\n");
    scanf("%s",Fr);

    printf("Verificar caracter no nivel?\n");
    scanf("%d",&idx);

    Pilha lisp = create();

    for(int i=0; i<QtCar;i++){
        if (Fr[i] == '(')
            push(&lisp, Fr[i]);
        if (Fr[i] == ')'){
            if (isEmpty(lisp)){
                printf ("A lista nao esta balanceada");
                break;
            }
            else
                pop(&lisp);
        }
        if (idx == 1){
            lvl = size(lisp);
            charlvl[1] = Fr[i];
        }
        else
            idx--;
    }
    if (isEmpty(lisp))
        printf ("A lista está balanceada! %s está no lvl %d",charlvl[1],lvl);
    else
        printf ("A lista nao esta balanceada");
}

pilha.c:
#include <stdio.h>
#include <stdlib.h>
#include "pilha.h"

Pilha create(){
    Pilha p;
    p->topo = -1;
    p->elementos[MAX];
}

int isFull(Pilha p){
    if (p->topo == MAX-1)
        return 1;
    else
        return 0;
}

char pop(Pilha *p){
    char c = p->elementos[p->topo];
    p->topo--;
    return c;
}

void push(Pilha *p, char c){
    if (isFull(p))
        return 0;
    else{
        p->topo++;
        char p->elementos[p->topo] = c;
        return 1;
    }
}
int isEmpty(Pilha p){
    if (p->topo == -1)
        return 1;
    else
        return 0;

}

int size(Pilha p){
    int tam;
    tam = p->topo; + 1;
    return tam;
}

pilha.h:
#ifndef PILHA_H_
#define PILHA_H_

#include <stdio.h>

#define MAX 100

typedef struct pilha {
    char elementos[MAX];
    int topo;
} Pilha;

Pilha create(); //cria pilha
char pop(Pilha *p); //desempilha
void push(Pilha *p, char c); //empilha
int isEmpty(Pilha p); //verifica pilha vazia
int isFull(Pilha p); //verifica pilha cheia
int size(Pilha p); //verifica tamanho da pilha

#endif

Sendo assim, estou tendo vários problemas. Inicialmente não estou conseguindo compilar, mas gostaria de saber onde posso estar melhorando o algoritmo.
Comment: Esta pergunta tem dois votos para fechar. Um destes votos como "*ampla demais*" e o outro como "*não está claro o suficiente*". Discordo desses votos de fechamento e votei por "*deixar aberta*". Alguém que é a favor do fechamento gostaria de explicar melhor?
Answer:
Boa parte dos seus erros de compilação é que ora você usa Pilha e ora usa Pilha *. Use sempre Pilha *.
Veja a sua função de criar pilhas:
Pilha create() {
    Pilha p;
    p->topo = -1;
    p->elementos[MAX];
}

O uso de -> serve para acessar ponteiros, então p deveria ser um ponteiro. Além disso, você deveria retornar um ponteiro (tal como disse no item 1). Se p não for um ponteiro, ele vai ser alocado na pilha e desalocado quando a função terminar, então você tem que alocá-lo no heap com malloc. Você deveria então fazer isso:
Pilha *create() {
    Pilha *p = (Pilha *) malloc(sizeof(Pilha));
    p->topo = -1;
    p->elementos[MAX];
    return p;
}

Entretanto, esse p->elementos[MAX]; não faz nada. O que você queria em seu lugar era isso:
    for (int i = 0; i < MAX; i++) {
        p->elementos[i] = 0;
    }

Sua função push é void, mas ela tem um return 0; e um return 1; dentro. Vamos fazer retornar int.
Na sua função push temos isso:
char p->elementos[p->topo] = c;

Esse char aí na frente não serve para nada. Retire-o.
Com as mudanças acima, no arquivo lisp.c, esssas linhas:
Pilha lisp = create();
push(&lisp, Fr[i]);
pop(&lisp);

Passam a ficar assim:
Pilha *lisp = create();
push(lisp, Fr[i]);
pop(lisp);

Com essas mudanças, o seu código já deve compilar. Mas ainda assim há outros erros:

Veja a sua função size:
int size(Pilha p) {
    int tam;
    tam = p->topo; + 1;
    return tam;
}

Acerca do * antes do p, já falei antes. Mas olhe a linha tam = p->topo; + 1; - há um ponto-e-vírgula a mais aí! Além disso, você não precisa dessa variável se você já vai retornar imediatamente. Logo, dá para simplificar tudo isso assim:
int size(Pilha *p) {
    return p->topo + 1;
}

Vejamos sua função isEmpty:
int isEmpty(Pilha p){
    if (p->topo == -1)
        return 1;
    else
        return 0;

}

O resultado de uma comparação com == é sempre 1 quando ela é verdadeira e 0 quando não é. Logo, se o resultado da comparação for 1, deve-se retornar 1, se for 0, deve-se retornar 0. Logo, é mais simples apenas retornar o resultado da comparação diretamente:
int isEmpty(Pilha *p) {
    return p->topo == -1;
}

O mesmo pode ser feito na sua função isFull.
Se você tem um if que sempre termina com um return, o else é desnecessário. Por exemplo:
if (condição) {
    return alguma_coisa;
} else {
    blablabla
}

É equivalente a isso:
if (condição) {
    return alguma_coisa;
}
blablabla

Com isso em mente, você pode simplificar a sua função push ao eliminar o else dela.
O caso da variável charlvl é curioso. Isso é um array de 10 posições, mas você só utiliza a posição 1. Logo, é melhor declarar isso como um char. Além disso, há um printf onde você imprime charlvl[1] usando %s. Você deveria usar %c. Além disso, a menos que a lista esvazie antes de ele chegar na posição do caractere procurado, teremos que charlvl[1] será Fr[idx - 1]. Assim sendo, é melhor mudar essa variável para o tipo char e atribuir Fr[idx - 1] a ela antes do for.
Você vai decrementando o idx até que quando ele for 1, você execute o lvl = size(lisp);. O idx vai ter o valor 1 apenas quando i == lvl - 1. Logo, é mais fácil você colocar essa condição no if, não mudar a variável lvl nunca e se livrar do else.
Você pede para verificar caracteres em um determinado nível. Na verdade, o que você olha é em uma determinada posição na frase. Assim sendo, a mensagem correspondente no printf deve ser alterada. A variável idx é a posição do caractere na frase.
Uma coisa muito importante em programação é dar nomes adequados a variáveis. Em especial se você está na faculdade, por que de vez em quando alguns professores pegam no pé e até tiram ponto se o programa tiver variáveis com nomes inadequados ou despadronizados. Assim sendo, sugiro você renomear Fr para frase, QtCar para quantidade, idx para posicao, lvl para nivel e charlvl para procurado.
O printf("A lista nao esta balanceada"); dentro do for do main não deveria estar lá. Ele já diz se a lista está ou não balanceada no final. Entretanto, a ideia aqui é interromper toda a análise. Então uma variável auxiliar que indique se a análise foi ou não abortada neste ponto se faz necessário.
Você não precisa de stdio.h dentro de pilha.c e nem de pilha.h. E também não precisa de stdlib.h dentro de lisp.c.

Eis como fica então o seu programa:
pilha.h:
#ifndef PILHA_H_
#define PILHA_H_

#define MAX 100

typedef struct pilha {
    char elementos[MAX];
    int topo;
} Pilha;

Pilha *create(); //cria pilha
char pop(Pilha *p); //desempilha
int push(Pilha *p, char c); //empilha
int isEmpty(Pilha *p); //verifica pilha vazia
int isFull(Pilha *p); //verifica pilha cheia
int size(Pilha *p); //verifica tamanho da pilha

#endif

pilha.c:
#include "pilha.h"
#include <stdlib.h>

Pilha *create() {
    Pilha *p = (Pilha *) malloc(sizeof(Pilha));
    p->topo = -1;
    for (int i = 0; i < MAX; i++) {
        p->elementos[i] = 0;
    }
    return p;
}

int isFull(Pilha *p) {
    return p->topo == MAX - 1;
}

char pop(Pilha *p) {
    char c = p->elementos[p->topo];
    p->topo--;
    return c;
}

int push(Pilha *p, char c) {
    if (isFull(p)) {
        return 0;
    }
    p->topo++;
    p->elementos[p->topo] = c;
    return 1;
}

int isEmpty(Pilha *p) {
    return p->topo == -1;
}

int size(Pilha *p) {
    return p->topo + 1;
}

lisp.c:
#include <stdio.h>
#include "pilha.h"

int main() {
    int quantidade, posicao, nivel;

    printf("Quantidade de caracteres:\n");
    scanf("%d", &quantidade);

    char frase[quantidade];
    printf("Frase:\n");
    scanf("%s", frase);

    printf("Verificar caracter na posicao?\n");
    scanf("%d", &posicao);
    char procurado = frase[posicao - 1];

    int abortado = 0;
    Pilha *lisp = create();

    for (int i = 0; i < quantidade; i++) {
        if (frase[i] == '(') {
            push(lisp, frase[i]);
        }
        if (frase[i] == ')') {
            if (isEmpty(lisp)) {
                abortado = 1;
                break;
            } else {
                pop(lisp);
            }
        }
        if (i == posicao - 1) {
            nivel = size(lisp);
        }
    }
    if (!abortado && isEmpty(lisp)) {
        printf("A lista esta balanceada! %c está no nivel %d", procurado, nivel);
    } else {
        printf("A lista nao esta balanceada");
    }
}

O seu programa deve então funcionar assim.
Entretanto, há ainda um segredinho: Uma vez que a única coisa que você empilha são abre-parênteses, logo, você pode eliminar a pilha e trocá-la por um contador. Isso mostra que esse exercício não precisa de fato usar uma pilha para verificar se os parênteses estão balanceados e uma solução mais simples existe. Isso também significa que o seu professor deveria bolar um outro exercício para pilhas que não pudesse ser resolvido sem utilizá-las. Eis como ficaria o seu programa sem usar pilhas:
#include <stdio.h>

int main() {
    int quantidade, posicao, nivel;

    printf("Quantidade de caracteres:\n");
    scanf("%d", &quantidade);

    char frase[quantidade];
    printf("Frase:\n");
    scanf("%s", frase);

    printf("Verificar caracter na posicao?\n");
    scanf("%d", &posicao);
    char procurado = frase[posicao - 1];

    int abortado = 0;
    int abertos = 0;

    for (int i = 0; i < quantidade; i++) {
        if (frase[i] == '(') {
            abertos++;
        }
        if (frase[i] == ')') {
            if (abertos == 0) {
                abortado = 1;
                break;
            } else {
                abertos--;
            }
        }
        if (i == posicao - 1) {
            nivel = abertos;
        }
    }
    if (!abortado && abertos == 0) {
        printf("A lista esta balanceada! %c está no nivel %d", procurado, nivel);
    } else {
        printf("A lista nao esta balanceada");
    }
}

Balanceamento de parênteses


Qual a melhor maneira de se fazer autenticação no banco de dados?

Question: Qual a melhor maneira de se fazer uma conexao ao banco de dados utilizando c#?
Criar uma tabela USUARIOS, ou criar um USUARIO no banco de dados para acessar?
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: Não existe a melhor maneira. Existe a mais adequada para sua situação.
Se quer saber qual é a mais segura é usar a autenticação do banco de dados, ainda que outras formas podem ser bem seguras se fizer certo.
Mas nem sempre isto possível. Nem sempre é o desejado. Você pode:

ter acessos anônimos
ter uma quantidade muito grande de usuários
permitir auto cadastro
dar acesso a partes do banco de dados que não deveria

enfim, tem várias situações que não é o ideal, aí uma solução própria pode ser mais adequada.
Uma quantidade imensa de aplicações só faz sentido ter sua própria tabela de usuários, especialmente para web e mobile.
Coloquei no GitHub para referência futura.
Comment: Entendi, estou fazendo uma aplicação Desktop c#, optei por autenticação no banco de dados em si, porem... (certeza que deve existir) uma forma de se manter uma conexão ativa com o banco até que o usuario saia da aplicação. Hoje eu abro e fecho a conexao em um simples select por exemplo. Existe alguma maneira? Ou qual o nome correto desse tipo de procedimento? Andei procurando por POOL mas nao obtive muito exito... Valeu
Comment: Pegar uma conexão é diferente de conectar no banco de dados.
Comment: especificamente, eu preciso manter a conexao do banco de dados ativa, e nao abrir e fechar simultaneamente varias vezes. Tudo que eu faço hoje, eu abro e fecho a conexao.
Obrigado por estar me ajudando, acima de tudo.
Answer: Para o caso de autenticação de usuários eu uso 3 soluções dependendo do caso e do cliente;

Todos os usuários possuem um usuário próprio no sql: passo na connection string o usuário, assim é possível colocar mais um nível de segurança. Por exemplo, o usuário não pode ler tabela x
Todos os usuários tem registro no AD: Usuário padrão na connection string e faço a validação com o AD;
Bagunçado: Utilizo o IdentityServer (atualmente na versão 4) é mais complicado de implementar e normalmente vale apena se você tiver "vários sisteminhas" e quiser autenticar tudo em um lugar só; caso venha a ter mais sistemas tudo autentica no mesmo lugar
Comment: Muito Obrigado!


DDD Bounded Contexts with Onion Architecture

Question: I have the following Onion Architecture framework.

Domain

Entities - For my domain entities
Interfaces - For my domain interfaces
Services  - For my domain services

Infrastructure

Data - For Fluent NHibernate persistence
Interfaces - For infrastructure interfaces
Logging - Just an interface for logging in case I want to switch out my logging library to something else.
Dependency Resolution - Most of my IoC registrations goes in here.

Services

Interfaces - Application service interfaces goes in here, they will get implemented in the UI project.

Tests

Infrastructure Tests - For testing infrastructure services etc.
Domain Tests - For testing domain models and services

Web

UI - User interface project where I implement application services, user interface, etc ...

With Domain Driven Development one would identify the Bounded Contexts. Most of the literature on the internet states that each Bounded Context needs to be abstracted into their own project or namespace.

Is my approach then incorrect for having all my Domain Models in one project and all my Domain Services in another project? Does it really matter not having different bounded context's in different namespaces or projects?
If you have a Model A which is used my Bounded Context A, but  Bounded Context B, Bounded Context C, etc also needs to use the exact same Model A, Do you allow them to use that exact same model, or do you create a new model for each Bounded Context?

I am new to DDD so sorry if this question is a dumb question. I find myself understanding something better if I ask a question and get a good explanation as an answer.
Any Help will be much appreciated.
Answer:
Is my approach then incorrect for having all my Domain Models in one project and all my Domain Services in another project? Does it really matter not having different bounded context's in different namespaces or projects?

Different namespaces is a conceptual and a practical solution, since otherwise you could have entity name collision when two neighboring concepts go by the same name in different subdomains.
Different projects/solutions is more of an organizational choice on top of that. It makes things a bit easier if separate teams work on the BC's, and the separate binaries mean the BC's are more independently deployable.

If you have a Model A which is used my Bounded Context A, but Bounded Context B, Bounded Context C, etc also needs to use the exact same Model A, Do you allow them to use that exact same model, or do you create a new model for each Bounded Context?

It would require some more domain analysis to tell, but the whole point of a Bounded Context is being able to view things from a totally different angle. In the rare cases when

the exact same entity is used in 3 different BC's
you don't see them evolving their own way in the future
the entity doesn't seem to naturally belong in a given BC

then you might want to use the Shared Kernel pattern. Otherwise, just copy the entity in each BC and let those live their own lives, or find the entity's true BC and link to its ID from other BC's.
Comment: Yes, I would definitely create 3 different models. BC 1, 2 & 3 might share the same concept behind `Model A` but it will be used in different part of the application. Drawing a simple [context map](http://www.infoq.com/articles/ddd-contextmapping) will help you to visualize models interactions and what's happening between the BCs.
Comment: Well, I would go with 3 different mapping files as well. Think of the _Customer_ concept. Depending on the context it might be a _prospective customer_, a _customer_ or a _client_. Those 3 models share the same idea but definitely don't share the same properties. There's no good unique model, no canonical model. DDD brings us the ability to create as much model as we have different contexts. But they will obviously share the same ID as the model goes through the contexts.
Comment: Thank you for the explanation it makes sense now. Just one question on top of this though, persistence related, for `Model A` in 3 `bounded contexts`, would you have 3 different mapping files, binding each context model to its own table, or have 1 mapping file?
Comment: Thanx @MaxS-Betclic ill take all this in consideration as I improve my solution.


Symmetric function (under rotation)

Question: I have a maybe silly question...
Consider the case that $f(x)=f(\lVert x\rVert)$.
My question is if $f\equiv 1$ is such a function.
For example this is used here:
https://math.stackexchange.com/questions/626181/dirichlet-boundary-problem-and-volume-potential
I am wondering about the domain of definition... because $x$ seems to be a vector, and $\lVert x\rVert$ is a real number...
Comment: I guess what you said was an abuse of notation. Lhs is a function of x, rhs is a function of norm of x, the argument you feed in the functions are different, so what you said technically makes no sense.
Comment: Why? I know it is maybe too easy. :-)
Comment: Note, i added the ...to make up the character number
Comment: What set kind of set is $x$ in, and what is $||x||$? Since you apply $f$ to both of these objects $x$ and $||x||$, am I to understand that they are both in the set serving as the domain of $f$?
Comment: I think the title "(under rotation)" means there is a specific norm 1 vector $v$ some where and $||x||$ really mean $||x||v$. I'm more annoyed with $f\equiv 1$. Does this means $f$ is constant function $1$ or $f$ is identity or $f$ is almost everywhere constant $1$? Why is the $\equiv$ there?
Comment: It means f is a constant function.
Answer: Absolutely.  For any $x$, both $f(x)$ and $f(\lvert x\rvert)$ are precisely $1$, and are therefore equal.
Comment: Why is $f(\lVert x\rVert)=1$?
Comment: @math12 Because you said that no matter what you plug in to your function, you always get back $1$.
Comment: But $x$ is a vector, $\lVert x\rVert$ is a real number. How can that be that I can put both into the function?!
Comment: @math12 I was interpreting $x$ as a complex number, in which case this is perfectly fine.

Symmetric function (under rotation)


Time series estimation, estimated values cannot be observed

Question: Assume we have an infinite time series $v_1,v_2,\dots,v_i,\dots,v_j,\dots,v_y,\dots,v_z,\dots$ and use Gaussian process for prediction. At time $i-1$, we want to use the previous observed data to predict the values for $\bar{v_i}$ to $\bar{v_j}$.
If these values are predicted, they cannot not be observed. We can continue to observe the data from $v_{j+1}$ to $v_{y-1}$ and use the historical observed data to predict $\bar{v_y}$ to $\bar{v_z}$.
My question is, since the data $v_{i}$ to $v_{j}$ are predicted instead of being observed, can we use these predicted data to adjust the model for better result?
Comment: "they cannot not be observed" - so they *are* observed?  ;)
Answer: Predictions are not data - they are functions of the observed data.  As such, they add no information to your knowledge of the process beyond what is already in the observed data.  If you make a prediction based on some observed values, and then observe the predicted value, the new information comes from the new observation, not the prediction you made using the original data.  Hence, in the absence of observing your predicted value, you still just have your original set of observed data, plus a known function of that data.
This general principle is easiest to understand in the context of Bayesian methodology (though the same applies in classical statistics).  Suppose you observe data $\mathbf{x} = (x_1, ..., x_n)$ and you use this to make a prediction $\hat{x}_{n+1} = h(\mathbf{x})$ but you do not observe $x_{n+1}$.  (It doesn't matter how you make this prediction - it is some function of the observed data.)  For any later value $x_{n+k+1}$ after the predicted value (i.e., for $k \geqslant 1$), you have the predictive density:
$$p(x_{n+k+1} | \mathbf{x}, \hat{x}_{n+1}) = p(x_{n+k+1} | \mathbf{x}, h(\mathbf{x})) = p(x_{n+k+1} | \mathbf{x}).$$
This shows that the prediction you have made has no effect on the predictive density for the new value $x_{n+k+1}$.  All information in this predicted value is already in the observed data $\mathbf{x}$.
Comment: Well, as I've said, the predictions can effectively be ignored - they are not data.  So the solution to the problem is to only use your data for prediction.
Comment: is there a method to solve this kind of problem is some data is predicted instead of being observed?
Answer: Have you searched for censored time series? Note that if the process is not observed for some reason, it is possible that the latent variable didn't cross a certain threshold to become observable. Hence, missing values indicate such a fact, and the likelihood estimation process can further benefit from such.
Indeed, not taking into account truncated observations results in an estimation bias, Green's Econometric Analysis has a nice discussion on truncated distribution, however, not specifically on censored (truncated) time series. You may find it helpful.
HTH
Answer: If the problem is that you have a stretch of missing data from $v_i$ to $v_j$, I think you could use a state space model, which is quite tolerant of this. You do not need to predict $v_i$ to $v_j$ (and, as one of the other answers points out, predicted observations cannot be used as if they were real data).
Good references include Durbin-Koopman, Shumway-Stoffer and many others. If you happen to use R, there is a wealth of packages that would help you to implement a state space model.
Comment: The data is not actually missing. Consider the case that observing the data costs resources and it tries to observe the data as few as possible if the accuracy of the predicted data is above a threshold. That's why I choose to use Gaussian Process because it outputs the confidence interval.


Parsing a JSON text

Question: With the following way...
<code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
                  [NSString stringWithFormat:@"/lkj/"]];

NSString *fileName = [NSString stringWithFormat:@"/sandbox/2012_05_11.json"];

[[self restClient] loadFile:fileName intoPath:path];

NSString *fileContent = [[NSString alloc] initWithContentsOfFile:path];

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];

// getting the data from inside of "menu"

NSString *message = (NSString *) [data objectForKey:@"message"];
 NSString *name = (NSString *) [data objectForKey:@"name"];

namegroup.text = [NSString stringWithFormat:@"%@  %@",name, message];
</code>
...I am trying to parse a document I have previously made with other code...
<code>{"message":["Untitled1a","Untitled2a","Untitled3a"],"name":["Untitled1b","Untitled2b","Untitled3b"]}
</code>
with the code above though, in name group.text, this appears...
<code>(untitled, untitled, untitled) (untitled, untitled, untitled)
</code>
...but what I would like to do is to allocate many UITextFields, each of them in pairs, (2, 2, 2..), one field which displays the name and the other the message, so pair up 1a with 1b, 2a with 2b... obviously the fields won't be Untitled1a, but "how are you"...
But I can't seem to fix this issue!! Please help!!
Answer: You may try something like this:
<code> NSArray *message = [data objectForKey:@"message"];
 NSArray *name    = [data objectForKey:@"name"];

 NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:message forKeys:name];

 for (NSString* Key in [Dictionary allKeys]){
    NSLog(@"%@ %@",Key,[Dictionary objectForKey:Key]);

 }
</code>

Parsing a JSON text


Pearson Correlation problem

Question: Let's assume that we have 2 people and 5 objects with the following ratings (scale 1-5):
John has rated obj1:5, obj2:1 , obj3:(unknown value), obj4:2 , obj5:2 and Jack
has rated obj1:1, obj2:5 , obj3:2, obj4:5 , obj5:5. Do i need  obj3:2 when calculating the mean of Jack's ratings or just hypothetically delete it and use the other objects that have been rated by both of them? I want to calculate Pearson correlation between John and Jack. Also, i know that the obj3 will not be used in Pearson correlation function.
Thank you for your time.
Answer: Yes, we do need to know all of Jack's ratings to calculate their mean.
And we need John's rating for object 3 to calculate correlation between John and Jack's ratings.
However, if Jack's rating for object 3 were equal to the mean of all of other Jack's ratings (which it is not), then we could calculate Pearson's correlation without knowing John's rating for object 3. You can look at the formula for covariance to see the reason.
Comment: Yes,  because  the subtraction will be zero. Thank you very much!

Pearson Correlation problem


Show that two intersecting curves on a regular surface with the same osculating plane that is not the tangent plane have the same curvature

Question: Let $\bf{p}$ be a point on a regular surface $S$.
Let $\boldsymbol{\alpha}(s)$ and $\boldsymbol{\beta}(s)$ be two curves parametrized by arc length on the surface $S$ such that $\boldsymbol{\alpha}(0) = \boldsymbol{\beta}(0) = \bf{p}$.
Denote the Frenet trihedron of $\boldsymbol{\alpha}(s)$ at $\bf{p}$ by $\bf{t}_{\alpha}$, $\bf{n}_{\alpha}$, $\bf{b}_{\alpha}$; the Frenet trihedron of $\boldsymbol{\beta}(s)$ at $\bf{p}$ by $\bf{t}_{\beta}$, $\bf{n}_{\beta}$, $\bf{b}_{\beta}$.
Suppose both curves have the same osculating plane at $\bf{p}$ and the osculating plane is not equal to the tangent plane at $\bf{p}$.
i) Show that $\bf{t}_{\alpha}$ and $\bf{t}_{\beta}$ are parallel, i.e. $\bf{t}_{\alpha} = \pm\bf{t}_{\beta}$.
ii) Show that $\bf{n}_{\alpha}$ and $\bf{n}_{\beta}$ are parallel, i.e. $\bf{n}_{\alpha} = \pm\bf{n}_{\beta}$.
iii) Show that both curves have the same curvature at $\bf{p}$.
I have only succeeded in showing i), where the strategy was to first assume they are not parallel. Taking the cross product of the two tangent vectors would then produce the normal of the osculating plane, a non-zero vector parallel to the Gauss map at $\bf{p}$. Since the tangent plane at $\bf{p}$ is defined by the normal vector at $\bf{p}$, i.e. the Gauss map, this implies that the osculating plane is the same as the tangent plane, which contradicts the setup.
This question was from an exam I took recently. Thank you.
Answer: You've done the hard part. Since the osculating planes of $\alpha$ and $\beta$ at $\mathbf p$ are the same and the tangent vectors are ($\pm$) the same, ii) follows. Here's a major hint for iii): Apply Meusnier's formula, which relates the normal curvature of $S$ in the direction of $\mathbf t_\alpha = \pm\mathbf t_\beta$ and the curvature of $\alpha$ (or $\beta$). What's the missing ingredient?
EDIT: Meusnier tells us that $\kappa_n = \kappa \mathbf n\cdot \nu = \kappa\cos\phi$, where $\nu$ is the surface normal and $\phi$ is the angle between the curve's principal normal and the surface normal. So if $\kappa_n$ is the same for both curves (as it depends only on the tangent direction of the curve), now what do you have?
Comment: Oh I see what's going on for ii). Since the osculating planes are the same, there's only one perpendicular direction(up to a sign) in which both normals can be in. As for iii), I googled Meusnier's formula which didn't give me anything(there was a Meusnier's theorem though, which doesn't seem right). The only relation I know of is one relating curvature, normal curvature and geodesic curvature. Clearly the normal curvature is the same since it comes from the second fundamental form of the same tangent vector. I have to think about why the geodesic curvature should be the same though.
Comment: I've added a bit more :) The geodesic curvatures only turn out to be the same up to sign, but that's not intrinsically obvious.
Comment: Nice I see it now. Thanks. That was actually directly from the definition of normal curvature.


Arpeggio-ish patterns for the right hand on classical guitar

Question: I ask this question tentatively, because I know next to nothing about the guitar in general, but have picked up classical guitar on the side. Actually, I've always loved classical guitar, and found a neat "teach yourself" book at guitar center while shopping for over-priced violin strings, so I picked up a copy and have been self-teaching.
On top of the classical music that I love, I've recently taken an interest in hymns and church music. I think it would be awesome to be able to figure out the chords for a good hymn and play them using classical guitar-technique. Like, roll them out and stuff. No melody, just, uh... "Fingerstyle?" Is that what it's called? Ahdunno, guitar jargon...
Basically, I like classical guitar, but would like to play chords written out for the acoustic with a classical twist. However that would work.
My point is, given a finger chart for an acoustic guitar, how can I use my fingers to play them out in a way that sounds fundamentally classical guitar. I've tried just choosing two or three strings with pitches that sound nice to cycle through, but I feel like it could be embellished, and if there's another right way to do it, I'd like to do it that way. Are there... "finger patterns" or something that I can practice so that I can just plug them in where it sounds good?
Once again, pardon my guitar illiteracy.
Comment: Sounds like you'd like something along the lines of Pachelbel's canon? That can be played simply as a series of arpeggioed chords on a guitar; it loses some of the melody, but keeps the general feel of the piece.
Comment: @Evert Sure. I'm not really certain what I want, but that sounds right. I think the most important thing would be if it's a technique that's applicable to different songs with minimal effort.
Answer: Since you already know arpeggiation on strings as a violinist, I suspect you are looking for right hand "picking patterns", akin to a harpist. If you explore any classical guitar method, such as the Carcassi Method that my teacher used, you will find the right hand digits annotated as p-i-m-a -- p=thumb, i=index, m=middle, and a=ring finger.
One of the easiest techniques may be the simple alternation between p-m-p-m-p-m... If you hold a full six string chord with the left hand, you might pick the strings 6(p)-4(m)-5(p)-3(m)-4(p)-2(m)-3(p)-1(m) and back again.
Experiment with different patterns, different string skips, rolls, etc. Above all, enjoy yourself!
Imho, a good teaching method will illustrate the rest stroke and free stroke techniques. The above description assumed a free stroke. The rest stroke is the way to achieve volume dynamics. However it dampens the neighboring string (which stops the stroke) and will not work well for sustaining arpeggiation, but it is generally the best for playing the melody.
Answer: I can really recommend Guiliani's 120 Arpeggio Study. It gives you a very thorough and systematic way to develop the finger picking technique.
Here is a link.
Answer: My guitar master thought me of these hand exercises:(1423)(1243)1st(1324)(1342)2nd... I wonder if you guys did these hand exercise  patterns that my guitar master taught. You know this hand stuff is really true; when I discovered that, while playing the guitar often, I found out that I can hit some notes often through the use of Hammering or which is called in a book "hammer on." Some guitar skills include tremolo, hitting a note with a tremolo lick or raising a note through hand release. Because of these, my guitar playing has improved. There is also "Vibration where a note is struck and allowed to vibrate...


The only group automorphisms of the additive group of real numbers that are also order isomorphisms are multiplication by positive real numbers

Question: I am looking for a proof of the fact that if $f:\mathbb{R}\to \mathbb{R}$ is a group automorphism of $(\mathbb{R},+)$ that also preserves order, then there exists a positive real number $c$ s.t. $f(x)=cx$ for all $x\in \mathbb{R}$. If anyone can point to a reference, that will be great.
Answer: IIRC this has been covered a handful of times on this site; the proof, in any case, is pretty straightforward.  Obviously $f(0)=0$ and $f(1)\gt 0$ by the order-preserving property; say $f(1)=c$.  Then $f(n)=cn$ for all $n\in\mathbb{N}$ ($f(1+1+\ldots+1) = f(1)+f(1)+\ldots+f(1)$) and $f(q) = cq$ for all $q\in\mathbb{Q}$ (if $q={r\over s}$, then $sf(q) = f(sq) = f(r) = cr$, so $f(q) = cr/s = cq$).  Now Cauchy sequences give you the full result.
Comment: You can use the sandwich theorem: choose two Cauchy sequences of rationals $p_n$, $q_n$ converging to your value $x$ such that $p_n \lt p_{n+1} \lt x \lt q_{n+1} \lt q_n$ for all $n$; the fact that $f$ is order-preserving then implies that $f(p_n) \equiv cp_n \lt f(x) \lt f(q_n) \equiv cq_n$ for all n.
Comment: Thanks. However, I don't quite see how to go from rationals to reals without requiring that $f$ commute with limits.
Comment: Thanks, that clears it up.
Answer: I don't have a reference, but here is an outline of how I would do this. Since we can approximate any real number from above and below by elements of $\mathbf Q$ and $f$ preserves the order, we can reduce to the case of rational $x$. Clearly we want $f(1) = c > 0$ to be our constant. Now, if $b$ is a positive integer then
$$
c = f(1) = f(b/b) = bf(1/b).
$$
It doesn't take much work to get from this to a proof that $f(x) = cx$ for each $x \in \mathbf{Q}$.
Comment: Thanks for the answer. I get it now.