Functorial modifications of a topology

Question: Let $S$ be a set. Then there are only two ways to attach
functorialy a topology $\mathcal{T(S)}$ to it: The discrete and the trivial topology. Functorial means in this case that all maps $f \colon S \to S$ are continuous with respect to $\mathcal{T}(S)$.
Now, let $X$ be a topological space with topology $\mathcal{T}(X)$. What topologies $\mathcal{T}'(X)$ can be attached to $X$ in a functorial way, i.e. such that all continuous maps $X \to X$ for $\mathcal{T}(X)$ are continuous for $\mathcal{T}'(X)$?
More generally, what are the endofunctors $\mathcal{Top} \to \mathcal{Top}$ of the category of topological spaces that fix the underlying set of the objects and the morphisms (as maps of sets)? In other words, what are the endofunctors of $\mathcal{Top}$ that are functors over the forgetful functor $\mathcal{Top} \to \mathcal{Set}$?
A proof for the statement in the beginning: Assume $\mathcal{T}(S)$ is not the trivial topology. Then there is a nonempty proper open subset $U \subset S$. Fix two points $x_1 \in U$, $x_2 \in S \setminus U$. For
an arbitrary set $V \subset S$, consider the "characteristic function" $f_V$:
$$f_V \colon S \to S$$
$$f_V(x) = \begin{cases}x_1 & x \in V \\ x_2 & x \not \in V \end{cases} $$
Because all functions $S \to S$ are continuous, $f_V$ is continuous, and $f_V^{-1}(U)=V$ is open. Because $V$ was arbitrary, every subset of $S$ is open, i.e. the topology is discrete.
Answer: Let $\mathcal C$ be a class of spaces. Call a continuous map $t:C\to X$ from a space $C\in\mathcal C$ to $X$ a test map. Then we can equip $X$ with the final topology with respect to all test maps to $X$ and call this new space $cX$, so a set $A$ in $cX$ is closed if and only if $t^{-1}(A)$ is closed for every test map $t$. Note that the test maps to $cX$ and those to $X$ are the same.
A space $X$ which already has the final topology for all its test maps will be called a $c$-space. These $c$-spaces and all continuous maps between them form a subcategory $c\mathbf{Top}$ of $\mathbf{Top}$.
Now given a map $f$ from a $c$-space $X$ to a space $Y$, the same underlying function is continuous as a map $f': X \to cY$ since $f't$ is continuous for every test map $t$ to $X$. It follows that $c$ extends to a functor $\mathbf{Top} \to c\mathbf{Top}$ right adjoint to the inclusion $c\mathbf{Top} \to \mathbf{Top}$, and $c$ is a functor over the forgetful functor $U:\mathbf{Top}\to\mathbf{Set}$. Then by composition with the inclusion functor we have a functor on $\mathbf{Top}$ over $U$.
For example, one could choose $\mathcal C$ to be the class of all compact spaces, then a $c$-space is a compactly generated space. If $\mathcal C$ is the class of all compact Hausdorff spaces, a $c$-space is what we call a $k$-space, and these form a Cartesian closed category (when we change the product topology on $X\times Y$).
This also works in the dual way, by equipping $X$ with the initial topology with respect to all continuous maps from $X$ to the spaces in the class $\mathcal C$. In that case, we get a functor which is left adjoint to the inclusion functor. A notable choice is $\mathcal C = \{\Bbb R\}$, in which case we obtain the category of all completely regular spaces.

Functorial modifications of a topology


How to dynamically generate a PayPal button with Rails?

Question: I have an e-commerce website with many different products with different prices, and I want to allow people to buy them using PayPal. This guide details how to create a PayPal Buy Now button, but you have to manually fill out a form. This would be very very time consuming to do every time I add a product.
I looked at the HTML of the Buy Now button, hoping to be able to inject my product information with ERB, but nowhere in the HTML is the product information like price listed. Instead, there's a very long "value" element, and I assume the product information is encrypted within this.
Anyone know how to dynamically generate a PayPal button with Rails? If not, does anyone know of am alternative I could use?
Answer: You can inject the data as below:
ERB sample (in case you are sending one product):

      product name: <%= @product.name %>

      product price: <%= @product.price %>
      Pay:
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" >
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="email@example.com*">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item_name" value="<%= @product.name %>">
<input type="hidden" name="item_number" value="<%= @product.id %>">
<input type="hidden" name="amount" value="<%= @product.price %>">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="button_subtype" value="products">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="shipping" value="<%= @product.shipping %>">
<input type="hidden" name="add" value="1">
<input type="hidden" name="bn" value="PP-ShopCartBF:btn_cart_LG.gif:NonHostedGuest">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit" >

</form>

Use below Paypal website link to customize your button then you can inject values as in Ruby code:
Design Paypal button
Comment: Where did you find this solution?
Comment: @JoeMorano if you follow the link of paypal there is a button **Create your button**, it will generate the html tags to be added to your page. regarding ruby, it is the normal way of injecting code in ERB files.


How do I specify an image style in my preprocess function?

Question: In my current project, whenever a node's image field is empty, I'm filling it with the image from an entity referenced in the node. To pull this off, I'm using this magical piece of code in template.php:
// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = field_view_field('node', $project, $field_name);
        }
      }
    }

It works superbly - but with one small problem: it doesn't give the image its correct image style. In fact it just spits out the original image.
How can I force it to use the field's image style?
Comment: I'm pretty sure you need to use the API function called `image_style_url` which can pull in specific image styles. I just don't have time right now to give a fully fleshed out answer.
Comment: Thanks for your help, Danny. That's going to be it. I'll investigate and see if I can work out how to incorporate it.
Answer: Have you tried render
// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = render($vars['content'][$field_name]);
        }
      }
    }

Comment: Thanks for taking the time to reply, Nikhil. Unfortunately, this breaks the original function - I assume it's because the $project variable is responsible for the image swapping.


JavaFXGL how to get the library for java from maven

Question: I am trying to use the javaFXGL library.  Which is the java gaming library.  I am not sure how to use maven to download the library to eclipse.  Does anyone know a step by step way to download this.  I need to this get some example code running.
Answer: I would be easier to get the help if you add your code in the question along with the problems/errors you are facing. Anyways I would suggest you to first read this and this to understand what is maven and how it works with Eclipse IDE.
After reading the articles you will understand that maven project has pom.xml file which is used for maven settings or you can say for Dependency Management, Build Management, etc.
To add the library you need to add its maven dependency in the pom.xml inside the <dependencies> tag like below:

<dependency>
    <groupId>com.github.almasb</groupId>
    <artifactId>fxgl</artifactId>
    <version>0.2.9</version>
</dependency>

You can also find other dependencies on www.mvnrepository.com


How to change search index for a view in the Views

Question: We made a lot views using Views module type of Search API index#1. Now, we realize that we need to go with another index#2. Is there any way to change indexes in existing Views? Can anyone point me in right direction?
Thank in advance!
Answer: I also had this problem after realizing switching indexes also requires changing the view's index. So to accomplish that quickest way I could think of was to change these values from the 'export' of the original index being used.
Main lines of original view:
<code>    $view = new view();
    $view->name = 'es_connector';
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_index';
    $view->human_name = 'ES Connector';
</code>
New search view:
<code>    $view = new view();
    $view->name = 'es_connector_rebuild'; // changed arbitrarily to my new view name
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_rebuild'; // changed to work - see below as to how determined
    $view->human_name = 'ES Connector Rebuild'; // changed arbitrarily
</code>
To find the name of base table click name of your new index (admin/config/search/search_api/index/) and append search_api_index_ with the machine name. Find and replace any occurance of your new view name.
Then paste all of the export into an import script. This will leave you with a new view based on the new index (with the original search view still available). Then just swap out the new search block for the old one. You also probably need to change the path under page settings of the  view.


Is $y = 2x + 1$ a linear system?

Question: Consider a system that is described by the linear equation: $y = 2x + 1$. Is this system linear or non-linear? From what I can tell, although the system is described by a linear equation is not linear, because the additivity property of the superposition principle does not stand.
Comment: See also: https://math.stackexchange.com/q/2054117/9464
Answer: It's an inhomogenous linear equation. Maybe that helps you.
But you're right in the sense, that $x\mapsto2x+1$ is not a linear map.
Answer: A linear system is of the form $A{\bf x}=b$ where $A$ is some matrix and $b$ is the known vector. The linearity is from $A$. Note that $y=2x+1$ is the same as $2x-y=-1$.

Is $y = 2x + 1$ a linear system?


Searching for signal in a somewhat noisy landscape

Question: I'm trying to implement a system to identify regions of high signal content in the presence of a noisy landscape. By high signal content, I simply mean intensity values significantly  above background intensity values.
Intensity readings are taken at $T$ contiguous locations; at each location, $t, \text{ for } t \in [1,T]$, the intensity count, $f(t) \in [0,\infty)$, is recorded.
My current strategy is this:
Mean-correct---or, simply, subtract the mean intensity---at each observed intensity with a view to removing background noise.

Move a sliding window along the landscape, such that:
For each position $i \in [1,T]$ and window interval $w_{i,i+s-1}$:
compute a test statistic from the $s$ observations within the current interval, $w_{i,i+s-1}$.
compare this test statistic to a preselected null distribution centred on $0$.
compute p-value corresponding to interval $w_{i,i+s-1}$; where the p-value corresponds to the probability of committing a type I error: assuming the region characterises high-signal content when,in fact, it doesn't.
Implement correction for multiple testing, say Benjamini and Hochberg FDR control.
If two overlapping window intervals, $w_{j+s-1},w_{k+s-1}: j+s-1 \geq k$, are both within the FDR threshold, concatenate regions to form one larger region-complex.

The figure given below illustrates this concept. In this figure, two regions, say $A$ and $B$, of the given landscape are covered by the sliding window. In each region, the window is depicted at $t_{A}$ and $t_{B}$ different coverage points respectively (hence the blurring effect). I'm looking for a procedure which which will determine whether the intensity levels at $A$ and $B$ are significantly different from background. The horizontal salmon line represents the mean intensity; upon mean-correction, anything below this line will be removed.

I should also mention that I am working with several landscapes, say $L$; hence, the number of window positions---and, further hence, the number of tests---will be $\sum_{l=1}^{L}pos_{l}$, where $pos_{l}$ is the number of window positions in landscape $l$.
For this approach to work, I need to define the test statistic and corresponding null and alternative hypotheses. Given the nature of the problem, I'm not sure what form an appropriate statistic/hypotheses scenario should assume.
Could somebody provide some assistance on how to define an appropriate hypotheses scenario or perhaps suggest a more robust approach to identifying high-signal content regions?
(P.S. I'm not sure that Poisson-based approaches will work as the data seem to be over-dispersed; perhaps a negative binomial assumption would work, but I'm guessing that a non-parametric/resampling/simulation based approach might be best. Having said that, if somebody believes that a Poisson approach is appropriate, please do suggest it!)
Answer: This sounds an awful lot like peak calling in *seq (ChIP-seq, clip-seq, etc) experiments.

A peak is called where either the number of reads exceeds a pre-determined threshold value or where there is a minimum enrichment compared to background signal, often in a sliding window across the genome. Some tools apply both methods.

from peak calling guide for chip-seq.
There are lots of different models which can be applied (after suitable bias correction)

Models used for the statistical assessment of enriched regions (peaks) range from Poisson (CSAR [85]), local Poisson (MACS), negative binomial (CisGenome [56]) to zero-inflated negative binomial (ZINBA [86]), or even extend to more sophisticated machine learning modeling techniques such as Hidden Markov Model (HPeak [87] and BayesPeak [88]).

From Practical guidelines for the comprehensive analysis of ChIP-seq
The discussion of the modeling assumptions and comparisons to other models present in each of these papers is probably far more informative than I could be.


Cant upload multilple images using django admin

Question: I have two models: one is the post model that can have multiple linked images. The image model has a foreign key to the post. That is, the images have a foreign key for a single post. When adding a new post I want to upload multiple images at the same time. Here is the code:
model.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    thumbnail = models.ImageField(upload_to='thumbnails')
    summary = RichTextField()
    body = RichTextUploadingField()
    created_at = models.DateField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at',]

    def __str__(self):
        return self.title

class Imagens(models.Model):
    img = models.ImageField(
        upload_to = "media/",
    )
    post = models.ForeignKey(
        "Post", on_delete=models.CASCADE, default=1)

admin.py
class ImageAdminForm(forms.ModelForm):
    class Meta:
        model = Imagens
        fields = ['img',]
    def __init__(self, *args, **kwargs):
        super(ImageAdminForm, self).__init__(*args, **kwargs)
        self.fields['img'] = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

class ImageInline(admin.TabularInline):
    model = Imagens
    extra = 1
    form = ImageAdminForm

class PostAdmin(admin.ModelAdmin):
   search_fields = ['title']
   inlines = [ImageInline,]
   def save_model(self, request, obj, form, change):
     obj.save()
     files = request.FILES.getlist('img') #he gets nothing
     print(files)
     for f in files:
        x = Imagens.objects.create(post=obj,img=f)
        x.save()

admin.site.register(Post, PostAdmin)

The problem is that if I save the post object it saves only one image and if I try to get the list of images it gives an empty list. Sorry I'm new to Django and even python. Every help is welcome.
Answer: Well, that's just a workaround. What I did was make the main model share the form with the inlined model. So, on the change page the files appear and I'm not obliged to post the images either, but it's full of fields.
class ImageAdminForm(forms.ModelForm):

    imgens = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    def __init__(self, *args, **kwargs):
        super(ImageAdminForm, self).__init__(*args, **kwargs)
        self.fields['imgens'].required = False
        self.fields['img'] = forms.ImageField()
        self.fields['img'].required = False

class ImageInline(admin.TabularInline):
    model = Imagens
    extra = 1
    form = ImageAdminForm

class PostAdmin(admin.ModelAdmin):
   search_fields = ['title']
   inlines = [ImageInline]
   form = ImageAdminForm
   def save_model(self, request, obj, form, change):
     obj.save()
     files = request.FILES.getlist('imgens')
     for f in files:
          x = Imagens.objects.create(post=obj,img=f)
          x.save()

admin.site.register(Post, PostAdmin)


Como filtrar o logcat por linha de comando?

Question: Estava lendo a documentação do android e vi que é possível monitorar o logcat por linha de comando, sem necessariamente estar com a IDE aberta.
Instalei uma versão minimalista do ADB(somente o necessário para ele funcionar em linha de comando) e estou tentando monitorar erros de aplicativos do meu celular, para facilitar a leitura, exporto para um arquivo de texto no prompt de comando, utilizando o comando abaixo:
adb logcat >> C:\\Temp\logcat.txt

Este comando já atende ao meu proposito, porém ele registra tudo que ocorre no celular, e gostaria de que fosse registrado apenas erros, e se for possivel filtrar isso, de aplicativos em execução.
Há alguma maneira de efetuar um desses filtros ou os dois por linha de comando?
Eu não estou sabendo aplicar as tags de privacidade na linha de comando.
Answer: É possível filtrar a saída do logcat por tag e nível de prioridade.
Uma entrada no logcat é registada através da chamada a um dos métodos da classe Log. O método chamado define o nível de prioridade(Log.i(), Log.e(), etc) sendo a tag definida pela string passada ao primeiro parâmetro:
Log.i("MyActivity","Passei no onCreate");

A expressão de filtragem tem o formato tag:priority, onde tag é a tag das entradas que queremos listar e priority é o nível mínimo de prioridade mínima a ser listado.
Pode usar mais de uma expressão de filtragem, separando-as por espaços.
O comando para listar as entradas com a tag MyActivity e nível de prioridade info ou superior é:
adb logcat MyActivity:I *:S

*:S evita que qualquer outra tag seja listada.
Para informação mais completa ver Como filtrar a saída do registro na documentação.
Comment: para o usuarios linux tambem pode se usar o pipe, algo tipo `$ adb logcat | grep "MyActivity"` que funfa blzura
Comment: Isso se eu estiver depurando um app em especifico, no caso, eu queria apurar dos apps em execução no meu aparelho, ai não tem como eu saber as Activities deles. Não tem como filtrar isso?
Comment: Por aquilo que vi na documentação, não. Apenas por *tag* e nível de prioridade. Até porque o nome da aplicação ou da Activity não existem no log. Pode ignorar a tag usando `*`, por exemplo listar todas as entradas com nível de prioridade "erro" ou superior: `adb logcat *:E`
Comment: Consegui utlizando o comando `adb logcat ActivityManager:I *:S >> C:\\Temp\logcat.txt `


What is the intuitive explanation for the CDF of any random variable to follow uniform distribution (0,1)?

Question: If $X$ is a continuously distributed random variable and $F$ is the c.d.f. of its distribution, then $F(X)$ is uniformly distributed in the interval $(0,1).$
While i'm clear with the mathematical proof, I'm looking for an intuitive answer to this.
Comment: It's really unclear what this is about. To ask for an intuitive explanation, it helps to give a clear statement of the mathematical fact you are interested in--the definition, formula, whatever, saying what all the parts of it are; explain the way in which you already understand it (in this case, what is the mathematical proof?), and _then_ ask for a more intuitive explanation. If you want to try this, use the "edit" link just below the question text to insert this information into the question; don't try to explain in comments.
Comment: This must be a duplicate, but cannot find it
Comment: Please give a tiny bit of hint about what you don't find intuitive.  Are you comfortable with CDF's in general but uniform RVs somehow baffle you, or the opposite, or both?
Comment: @MichaelHardy Yes, the language was so poorly organized that I completely missed the point. Now that you've helped OP out by fixing it, I think this is distinct from the linked question because this one asks for intuition rather than a proof. I'm voting to reopen.
Comment: This only applies to continuous cumulative distribution functions, i.e. for continuous random variables
Comment: What is the probability for an outcome to occur in an event whose probability is $y$?
Comment: @kjetilbhalvorsen - try https://math.stackexchange.com/questions/868400/showing-that-y-has-a-uniform-distribution-if-y-fx-where-f-is-the-cdf-of-contin or some of those linked to it
Comment: @DavidK : The language in which the posting was initially expressed was not up to passable standards of precision for mathematicians or even for homework being graded. But I have edited to clarify what I think must have been the poster's intent.
Answer: Assuming we are dealing with continuous random variables

the CDF $F(X)$ is a continuous increasing function of $X$ where the probability that $F(X) \le p$  for $p \in (0,1)$ is the probability that $X \le q$ when $F(q)=p$, which is $p$
so $F(X)$ has a uniform distribution on the unit interval, since the probability it is less than or equal to a given $p \in (0,1)$ is $p$
Comment: "Intuitive"? $ $


What is the predual of $L^1$

Question: Is there a nice characterization of the predual of $L^1$? So, what does the space $X$ look like, such that $X^*=L^1$, where the star denotes the dual of a Banach space. How do you start to find such preduals in general?
For some context, it is well known that given a measure space $(S, \Sigma, \mu)$, $L^p := L^p(S, \mu)$ is a Banach space for $p\in (1,\infty)$ and that $L^p \cong (L^q)^*$ where $q$ is the Holder conjugate of $p$, that is $\frac 1p + \frac 1q =1$. It is also known that $L^1$ is the predual of $L^\infty$. This leaves the above questions as the only remaining case.
When $S$ is (for example) finite of course the question is moot. If you like one can consider only very simple measure space, like $[0,1]$ with the Lebesgue measure.
Comment: Note also that the question what is "the" predual does not make sense in general. The space $\ell^1$ has many non-isomorphic preduals, for example $C(K)$ for $K$ countable and compact.
Comment: @ t.b: Thanks for pointing this out! To be honest, since I didn't know predual of $L^1$ I didn't think there could be various.
Comment: I think $K$ also needs to be Hausdorff no?
Answer: In fact, $L_1[0,1]$ has no pre-dual. More is true: $L_1$ cannot be embedded is a separable dual space. See, e.g., Theorem 6.3.7 in Kalton and Albiac's Topics in in Banach Space Theory.
Comment: David's comment expanded.  In a dual space, the unit ball has lots of extreme points (since, in the weak* topology, it is the closed convex hull of its extreme points: Krein-Milman theorem).  But the unit ball of $L^1[0,1]$ has no extreme points at all!  This shows $L^1[0,1]$ is not isometric to a dual space.  The isomorphic theorem is harder.
Comment: @Math: $\ell^1=L^1(\mathbb{N})$ (with counting measure) famously has predual $c_0$, the subspace of $L^{\infty}(\mathbb{N})$ consisting of sequences converging to $0$.
Comment: @math I should point out that it is not hard to show that $L_1[0,1]$ is not isometric to a dual space using an extreme point argument and the Krein-Milman Theorem.
Comment: @math A result due to Johnson and Zippen: Let $X$ be a separable $L_1(\mu)$ predual. Then there is a subspace $Y$ of $C(\Delta)$, where $\Delta$ is the Cantor set, such that $X$ is isometric to $C(\Delta)/Y$. Here is the reference: W.B. Johnson and M. Zippen, *Every separable predual of an $L_1$-space is a quotient of $C(\Delta)$*. Israel J. Math **16** (1973), 198-202.  See also [here](http://arxiv.org/pdf/math.FA/9204215).
Comment: @XanderHenderson I've added an answer for the Krein-Milman argument which should answer this question and the duplicate source: I'm afraid the more general argument in this answer is beyond me.
Comment: @DavidMitra This question was linked as the duplicate target of a [more recent question](https://math.stackexchange.com/questions/2867432/).  I think that the question is interesting, and I would really like to see a more complete, self-contained answer (in particular, there are a couple of key lemmata that I don't have access to via the link you provided–it is behind Google's "viewing limits" for the book).  It would also be nice to see the Krein-Milman argument added to the answer.  Is there any chance that I could twist your arm into expanding the answer that you have provided?
Comment: Can one show this for general $ L^1(X)$ ? I will check the book at the library and accept your answer afterwards.
Comment: @ David Mitra: Is there a link of the pages due to Johnson and M. Zippen? I could not find it.
Comment: @ GEdgar: Can the proof of "$L^1[0,1]$ has no predual" be found in a book?
Answer:
Banach-Alaoglu-Bourbaki: For $X$ a Banach space, the closed unit ball of $X^*$ is weak*-compact.
Krein-Milman:  For $X$ a locally convex topological vector space, and $K$ a compact convex subset, $K$ is the closed convex hull of its extreme points.

Suppose $X^* = L^1[0,1]$. By BAB, the closed unit ball of $L^1[0,1]$ is weak*-compact. In addition, weak* topologies are always locally convex (see, for instance, here) and $L^1[0,1]$ is clearly convex so Krein-Milman gives that it is the closed convex hull of its extreme points.
But the closed unit ball of $L^1[0,1]$ has no extreme points: Suppose $\|f\|_1 = \alpha \leq 1$, $f \neq 0$. Then $H(s) = \int_0^s |f(t)| \, dt$ is a continuous function, with $H(0) = 0$ and $H(1) = \alpha$. Thus there is some $s_0 \in (0,1)$ with $H(s) = \frac{\alpha}{2}$, so set
$$g(t) = 2f \chi_{[0,s_0]} \quad h(t) = 2f \chi_{[s_0,1]}$$
which satisfy $\|g\|_1 = \|h\|_1 = \|f\|_1 = \alpha$ and $\frac{1}{2}(g + h) = f$, so $f$ is not an extreme point. Clearly $0$ is not an extreme point either, so the unit ball of $L^1[0,1]$ has no extreme points.
Thus we have a contradiction, and $L^1[0,1]$ has no pre-dual.

What is the predual of $L^1$


Help finding mistake in this problem

Question: When I am doing math during free time, I produce a strange result when doing this:
$$(x^{\frac{1}{2}})^{2}=x+1$$ (definitely no solution)
$$x^{\frac {1}{2}}=(x+1)^{\frac{1}{2}}$$
$$1=\frac{(x+1)^{\frac{1}{2}}}{x^{\frac{1}{2}}}$$
$$1=\frac{x^{2}+2x+1}{x^{2}}$$
$$x^{2}=x^{2}+2x+1$$
$$2x+1=0$$
$$x=-0.5$$
Can you help find my mistake in this situation?Thanks.
Comment: At some point you raised both sides to the fourth power.  That picked up extra "solutions".
Answer: When you went from the third line to the fourth, you took the 4th power of both sides. (I'm not sure why -- you could have just squared both).
But $x^4 = y^4$ does not imply that $x = y$. (for instance $(-1)^4 = 1^4$, but $-1$ and $1$ are different.
So in taking 4th powers, you may have introduced new solutions that are not real solutions of the original equation.
Post-comment addition
To see why taking a 4th power introduces new solutions, let's look at the squaring function, $f(x) = x^2$, defined on the real numbers.
The function $f$ is not injective, i.e., there can be two different numbers $a$ and $b$ with $f(a) = f(b)$. For instance, $a = 2$ and $b = -2$ both have the property that $f(a) = f(b) = 4$.
If I tell you that I'm thinking of numbers $x$ and $y$ with $f(x) = f(y)$, can you conclude that $x = y$? No!
Why not? Well, suppose that $f(x)$ and $f(y)$ are both equal to $4$. Then $x$ could be $2$ and $y$ could be $-2$, and those are different.
Now let's go the other direction. Suppose I tell you that
$$
x = y = 2
$$
Then we can apply $f$ to get that
$$
x^2 = y^2 = 4.
$$
But that doesn't mean that every solution to the SECOND equation is a solution to the first one. For instance, $x = 2, y = -2$ is a solution to the second equation, but not a solution to the first.
The general principle to derive from this example is that if you have an equation, and apply a function $f$ to both sides to get a new equation, every solution of the original equation is still a solution of the new equation (provided that they are all within the domain of $f$). But not every solution to the new equation is a solution to the original. If you want to guarantee that a well, then the function $f$ must have an inverse, i.e., a function $g$ with $g(f(x)) = x$ and $f(g(x)) = x$ for every $x$.
Examples:
$f(x) = x + 1$; $g(x) = x - 1$. This example shows that you can "add 1 to both sides of an equation" without changing the set of solutions.
$f(x) = 2x$; $g(x) = x/2$. This example shows that you can "multiply both sides of an equation by 2" without changing the set of solutions.
But since $f(x) = x^2$ does not have an inverse function, you cannot ensure that squaring both sides of an equation leaves the solution set unchanged.
Comment: But isn't that the first line had shown that already no solution, so taking square means that this will form a solution? I take the 4th power as taking power of cube will return to first equation$x=x+1$
Comment: See post-comment addition.
Comment: So increase the power by 1 of the equation increase extra solution by one and decreasing power of solution has no effect, right?
Comment: No...it's rather more complicated than that, which is why I wrote that long explanation. But if you want a quick rule: raising both sides to an *even* power may introduce spurious solutions; raising both sides to an *odd* power will not. That's because odd-power functions, like $x \mapsto x^3$, have inverses, and even-power functions do not.
Comment: I rise the equation to the 5th power, although it has no real solution, but still exists two extra  complex solution, is the complex solution not counted as solutions?
Comment: The function $x \mapsto x^5$, defined on the reals, has an inverse; the corresponding function defined on the complex number field, does not. So if you're looking for real solution then, no, the complex solutions are not counted as solutions. Think of $x^2 + 1 = 0$. That has two complex solutions ... but it also has a single solution in the field with two elements. But we don't count that one, do we? Nor do we count the infinitely many quaternion solutions, or octonian solutions. That's why we specify the domain in which we're working when we ask for solutions to equations.
Comment: But even I count the complex solution as a solution, it doesn't plug into the original equation. (Is there are any complex solution for $x=x+1$?)
Comment: No -- there is no solution for this in any field, because in every field, the number $1$ is different from $0$ (that's one of the field axioms).
Comment: So, even I accept complex solution, the complex solutions I obtain by raising to odd number power is extra?
Comment: The MAY be extra, yes -- because odd powers (except 1) are not invertible over the complexes.
Comment: "So increase the power by 1 of the equation increase extra solution by one and decreasing power of solution has no effect, right?"This is still right including complex solutions, isn't?As the power of the equation reach 3,the extra solution increase from 1 to 2(including complex solution)
Answer: There is no need of all these intermediate steps to create the "paradox".
$$x=x+1\implies x^2=x^2+2x+1\implies2x+1=0.$$
Actually the squaring step is invalid, as it introduces the extra solution
$$-x=x+1.$$

When you use a squaring, like $a=b\implies a^2=b^2$, you must remember that $-a=b$ is ruled out.
Comment: Sorry to say, but this is a beginner's mistake.
Comment: I admit it.... I am a beginner....
Answer: But the domain gives $x>0$.
Which says that our equation has no solutions.
We can see this immediately:
$$\left(x^{\frac{1}{2}}\right)^2=x+1$$ it's
$$x=x+1$$ or
$$0=1,$$ which has no solutions.
Comment: So I am here to ask why I get the result above, I already know from the beginning there is no solution.
Comment: @lyk You have no mistakes in your computations. You need to write the domain before. You got $x=-0.5$, but the domain says: $x>0$. Thus, your equation has no solutions.
Answer: Note that you have the intermediate step $$1=\frac {x^{\frac 12}}{(x+1)^{\frac 12}}$$
Now that doesn't have a solution, and when you square it you get $$1=\frac {x}{x+1}$$ which again has no solution. However $$-1=\frac {x}{x+1}$$ has the solution $x=-\frac 12$, and these two equations combine into one when you square either.
In general if you have $x=y$ and square it to get $x^2=y^2$, the second equation can be rewritten $(x+y)(x-y)=0$ or $x=\pm y$. So the squared equation has a solution which does not belong to the original equation.

Help finding mistake in this problem


Classes get stripped out: why?

Question: I am pasting the following code into the text editor.

ABC

After the initial save everything looks fine in preview mode. However, if I go back in to edit the page, the styles applied to ul and li tags get stripped out, and the source looks like this.

ABC

How do I prevent this from happening?
Comment: See this thread: http://drupal.stackexchange.com/questions/74778/ckeditor-removes-class-names-even-with-the-exception-in-config

The suggestion there worked for me.
Answer: I haven't met this problem before. I did Google search and found this link Classes being stripped in CKeditor. Maybe your problems come from CKeditor and you just configure the allowedContent for CKeditor.

Classes get stripped out: why?


How do I understand this sentence in Hartshorne Chapter 2?

Question: It is in Hartshorne Chapter 2 theorem 4.3.(at the top of page 99)
The theorem (Valuative Criterion of Separatedness) claims that a morphism $f: X \rightarrow Y$ is separated if and only if the following holds. For any field $K$ and any valuation ring $R$ with quotient field $K$, let $T=\operatorname{Spec}R$ and $U=\operatorname{Spec}K$, let $i: U\rightarrow T$ be the morphism induced by inclusion $R\subset K$, given morphisms $g_1: U\rightarrow X$ and $g_2: T\rightarrow Y$ such that $f\circ g_1=g_2\circ i$ (i.e. the diagram commutes). Then there is at most one morphism from $T$ to $X$ making the diagram still commuted.
In the proof of the theorem, Hartshorne first notes that if $h$ and $h'$ are two different morphism from $T$ to $X$, then by universal property of fibre product, we have an induced morphism $h'':T\rightarrow X\otimes X$, then he claimed that 'since the restrictions of $h$ and $h'$ to $U$ are the same, the generic point $t_1$ of $T$ has image in the diagonal $\Delta (X)$.' Where this diagonal map,$\Delta: X\rightarrow X\otimes X$, is induced by two identities maps from $X$ to $X$.
I am confused that why the image is in the diagonal $\Delta (X)$? I think Hartshorne is saying $h(t_1)=h'(t_1)$, where $t_1$ is the generic point of $T$, because they restricted to the same map from $U$ to $X$, however I am not sure does this mean $h''(t_1)=\Delta(h(t_1))$?
Comment: Welcome to MSE. Not everyone has access to a copy of Hartshorne at the time they're reading your question. You'll have a better chance of getting help with your question if you put all the relevant parts of the text you're asking about in to your question - for instance, what are $U$, $h,h'$, $X$, $T$, etc.
Comment: What is $h''$ here?
Comment: Since there are two morphisms $h$ and $h'$ from $T$ to $X$, there is an induced morphism $h''$ from $T$ to $X \otimes X$.
Comment: Hi KReiser, sorry about that, I had updated the question, I am not entirely sure if this  is trivial but I must have missed something.
Answer: The restrictions of $h$ and $h'$ to $U$ are the same, let's call them $a: U\to X$. Then the induced map $U\to X\times X$ given by restricting $h''$ is the same as the map to the product induced by the restrictions of $h$ and $h'$; i.e., it is the product of $a$ with itself. But $a\times a: U\to X\times X$ factors as $$U\xrightarrow{a}X\xrightarrow{\Delta}X\times X,$$ so the image of $U$ lies in the diagonal. Explicitly, this does mean that $h''(t_1)=\Delta(h(t_1))=\Delta(h'(t_1))$.
Comment: May I ask are we doing the same thing? Because I was not completely clear about your steps here :)
Comment: @Rikka it looks like we are, but you've included more detail than I have showing that the maps I claimed agree actually do.
Answer: Let $g:U\rightarrow X\times X$ to be the morphism induced by $g_1:U\rightarrow X$ (i.e. $g=g_1\times g_1$). Let $\pi_1 : X\times X \rightarrow X$ and $\pi_2 : X\times X \rightarrow X$ be the projection to each of the $X$ respectively. Then by definition, $\pi_1 \circ g =g_1$.
Now notice $\pi_1 \circ \Delta \circ h \circ i =id \circ g_1 = g_1$, then by universal property of $g$ (i.e. $g$ is the UNIQUE map such that $\pi_1 \circ g =g_1$), we have $\Delta \circ h \circ i = g$.
Similarly, notice $\pi_1 \circ h'' \circ i = h \circ i = g_1$, therefore $h'' \circ i = g$.
This means $h ''\circ i = \Delta \circ h \circ i$, which is the same as saying $h''(t_1)=\Delta(h(t_1))$.
Comment: One small note - when you invoke the universal property of the product, it is not enough to only use $\pi_1$, you also need that $\pi_2\circ \Delta\circ h \circ i= g_1$ to conclude that $\Delta\circ h\circ i = g.$


Cv website development problems

Question: I am trying to achieve something like this http://www.vooshthemes.com/gallery/jamba/ in Drupal.
Its a CV website, what confuses me is how to deal with fields.
If u visit the link i provided above u'll see Experience, Expertise,Education and Training  Category in which u can mention from which year to which year u worked where and what was you task.
My problem is how do i enable the user to add more fields just like in the Cv example page??
i will be using Drupal 7.
any suggestion will be apppreciated.
Comment: Curriculum Vitae (résumé) may be confusing to some.  Re-working your question would likely bring more activity.
Answer: There are a number of ways you could do it, depending on how friendly you want the ui to be and how comfortable you are customising drupal.
I would look at the Field Collection module - http://drupal.org/project/field_collection. It should let you create a group of fields that can be treated as a single field.
ie you could create an 'Experience' field collection consisting of Title, Experience, Duration, Summary and whatever else you need. Then the end user should be able to add multiples of these if you set the field to allow multiple values.
I am saying should because I haven't directly used this module myself, in a similar situation I have created a custom form widget containing the multiple elements. Thats is potentially a more complicated exercise. You could see an example of what might be required there in the Examples for Developers module : http://drupal.org/project/examples
Comment: Thank you very Much, i tried the Field_collection Module and its doing exactly what i need.

Cv website development problems


Looking to modify a Wordpress theme to include home page header image similar to Quartz

Question: I am a big fan of how Quartz's site works (please visit qz dot com).
I found the Independent Publisher theme, where the author's GitHub page can be found here...
https://github.com/raamdev/independent-publisher
The theme includes the ability to auto-set a featured image as a post cover, with the post title overlaying the post cover (featured image).
In addition, as with most Wordpress themes, a function of the theme is to place the most recent post at the top of the home page. But I would like that first post to be the header image with overlaying title, linking to the full post, like what Quartz does. The second most recent post would then become the first post in the main content area of the home page.
I hope I am explaining myself clearly enough. I am unable to post more than one link or I would include others to help visualize what I am after.
I am able to do simple theme modifications but nothing like this. Please let me know if this looks possible or if too much work is required to pull it off.
I appreciate any help you can offer.
As a side note, I did contact the developer and asked if he would be interested in incorporating this or helping me modify the theme for my use, but he said he has not received any requests like mine, thus didn't want to take the time to do it, which I understand.
Answer: You can search in wordpress support. Check this styling-the-first-post-differently-from-the-rest


Cardinality function is measurable

Question: Let $f: [0,1] \rightarrow \mathbb{R}$ be a continuous function. Let also $g$ be a function, defined by the following condition:for each $a \in [0, + \infty]$ $$g(a)=\text{card} \{ x \in [0, 1] | f(x) = a \} \in [0, + \infty)$$ I would like to prove that $g$ is also a measurable function.  Are there any hints that might help?
Probably, it is worth trying to prove it more or less directly, by checking that $\{ a \in [0, + \infty] | g(a) < c \}$ is measurable for any $c$, but this approach does not seem to be clear enough, since the preimage of $g$ would be some cardinal number.
Comment: And what is $X?$
Comment: Do you know Lusin's separation theorem?
Comment: @zhw Fixed. Now $X = [0, 1]$
Comment: @tomasz So far -- no, i haven't bumped into the statement. I've just skimmed through it right now. If i got it correctly, it states that if $A$ and $B$ are disjoint analytic subsets (continuous images of Polish spaces) of a Polish space, then there is a Borel subset $X$ that separates them ($A \subset X$, $B \cap X = \emptyset$.)
Comment: Are you thinking of $g$ as a function with values in $\{0,1,2,\ldots\}\cup\{\infty\}$? ($\infty$ indicates that the level set in question is infinite.) Or do you wish to distinguish between cases when $\{x\in[0,1]\mid f(x)=a\}$ is countable and when it is uncountable?
Comment: @JohnDawkins  $g$ is a function with range $[0, + \infty)$, so, as you have written above, the $\infty$ means that the level set is infinite.
Answer: By the intermediate value theorem, for any interval $I\subseteq [0,1]$, the
set $A:=\{f(x),x\in I\}$ is an interval, and so is a Borel set.
Fix $n$ and let $I_i=[i/n,(i+1)/n)$ for $i=0,1,\dots, n-1$.
Now define the bounded, Borel measurable function
$$g_n(a)=\sum_{i=0}^{n-1}{\bf 1}_{A_i}(a)+{\bf 1}_{\{f(1)\}}(a),$$
where $A_i=\{f(x), x\in I_i\}$.
We have $g_n(a)\uparrow g(a)$ as $n\to\infty$, which shows that $g$ is measurable.

Cardinality function is measurable


Search by primary key and then sort

Question: I'm using MySQL and I have a database that I'm trying to use as the canonical version of data that I will be storing in different indexes. That means that I have to be able to retrieve a set of data quickly from it by primary key, but I also need to sort it on the way out. I can't figure out how to let MySQL efficiently do that.
My table looks like the following:
CREATE TABLE demo.widgets (
    id INT AUTO_INCREMENT,
    -- lots more information I need
    awesomeness INT,
    PRIMARY KEY (id),
    INDEX IDX_AWESOMENESS (awesomeness),
    INDEX IDX_ID_AWESOMENESS (id, awesomeness)
);

And I want to do something along the lines of:
SELECT *
FROM demo.widgets
WHERE id IN (
    1,
    2,
    3,
    5,
    8,
    13 -- you get the idea
)
ORDER BY awesomeness
LIMIT 50;

But unfortunately I can't seem to get good performance out of this. It always has to resort to a filesort. Is there a way to get better performance from this setup, or do I need to consider a different database?
Answer: This is explained in the documentation ORDER BY Optimization. In particular, if the index used to select rows in the WHERE clause is different from the one used in ORDER BY, it won't be able to use an index for ORDER BY.
Comment: I understand why it doesn't work. I want to know if there is an index that can satisfy both the `WHERE` and `ORDER BY` in this query.
Answer: In order to get an optimized query to fetch and retrieve like that, you need to have a key that orders by sort and then primary like so:
create table if not exists test.fetch_sort (
    id int primary key,
    val int,
    key val_id (val, id)
);

insert into test.fetch_sort
values (1, 10), (2, 5), (3, 30);

explain
select *
from test.fetch_sort
where id in (1, 2, 3)
order by val;

This will give a query that only uses the index for searching/sorting.

Search by primary key and then sort


integral closure is intersection of discrete valuation rings?

Question: In the book Introduction to Commutative algebra (Atiyah and Macdonald), Corollary 5.22 reads:
Let $A\subset K$ be a subring of a field $K$, then the integral closure of $A$ is intersection of all valuation rings of $K$ containing $A$.
Is it still true if we replace "valuation rings" above by "discrete valuation rings"?
Comment: If $A$ is noetherian, then yes, we can.
Answer: Without some other major assumptions on $A$, this is false.  An important class of domains for which it is does hold are the Krull domains, which includes UFDs.  As pointed out in the comments it is also true for Noetherian domains, which can be argued directly or taken for granted from e.g. the Mori-Nagata theorem and the statement for Krull domains.
The easiest counterexample comes from valuation domains, because a valuation domain is integrally closed and it is the intersection of discrete valuation rings precisely when it is a DVR itself. (An easy way to see this is to note that overrings of a valuation domain are just localizations at prime ideals, and that a DVR is 1-dimensional.)
If you are familiar with the concept of complete integral closure, then note also that your hypothesis would imply that the complete integral closure of $A$ coincides with the integral closure of $A$, which is usually not the case, even with significant chain conditions like having ACCP (or even stronger being Mori).


Are there any resources to self-learn the bass guitar for those who already know theory?

Question: I am a Music teacher. I hold a Ph.D. in Music Composition, studied piano for several years, and now I want to play the bass.
My concern is that every resource I find to become self-taught ends up covering very basic aspects of music theory (notes, scales, chords, functional harmony, rhythmic notation etc.) and it seems to overweight the importance of the very specifics of the instrument. I feel stuck into things I already have grasped for years, and just don't know what to skip, for fear of missing something technically important in such process. The outcome is very little advance into technical aspects and limited expression through the instrument.
Do you know any resources or strategies that could help me through this?
Comment: There was this guy. He once met a bass teacher, who convinced him to give it a try. So he did. First lesson, they played the E a bit. Dum dum dum dum... Week later, _now let's try that on the A string_. Dam dam dam... Next week. _Tell you what, we can switch between those notes!_ Dam dum dam dam dum... Next week, student didn't appear. Months later they met again by chance on the street. Teacher asked, where have you been? Didn't you want to learn the bass? _Ah sorry, no time for that. Got too many gigs..._
Comment: When I started bass, I just dived in - I was in a band before I'd even taken delivery of the instrument! What are you hoping to do with it?
Comment: @topomorto I am relaxed into this; I just want to learn for the sake of playing and having fun. I have an academic career that provides my living, but I started to feel less like having fun with music in latest years. I always loved the sound of bass and now I want to explore it. I just feel I can do it now.
Comment: Do you see yourself playing in a band, or solo pieces?
Comment: I see myself gigging and grooving with my friends.
Comment: These books are what you need: [**_Serious Electric Bass: The Bass Player's Complete Guide to Scales and Chords_**](https://www.amazon.com/Serious-Electric-Bass-Complete-Contemporary/dp/1576238830) ;  [**_Steven Mooney - Electric Bass Method_**](https://www.amazon.com/Steven-Mooney/e/B001KC9PRQ/ref=dp_byline_cont_book_1)
Comment: This seems like a very bizarre question the way it's worded.  You claim that there is too much emphasis on the instrument, what should there be?  A self taught instrument book should NOT go too deep into theory, it should in fact focus on technique.  That is the point of mastering an instrument, technique.  I hope you find what you're looking for.
Answer: If you are taking the theory knowledge as a given, off the top of my head, you're left with

Instrument choice
Fretless? 4-, 5-, or 6- string (or more?) Short scale? Active or passive? In some ways, bass is like a family of instruments. Do you want to focus on one, or spread yourself around a bit?
Posture and holding the instrument
Just standing and hanging the instrument on a strap in a way that the neck doesn't 'dive' is important. Unforunately many basses 'dive' naturally, meaning that half of what your left hand does is just hold up the instrument. It's the equivalent of trying to play a piano with a lid that you have to hold open. Don't let this happen to you!
Left hand stuff : fingering and hand position
You can find plenty of basic information about this online, I'm sure. It can be a bit personal : people's hand sizes very a lot, so often there's no one correct way to finger.
The basic right hand techniques : fingerstyle playing, pick playing, and slap/pop
You may not be interested in all of these - the easiest starting point is probably playing with a pick, depending on the styles you are going for of course.
Muting
Muting is more important on bass than on most other instruments. You'll be using both your right and left hand to do this.
Instrument setup how to select, modify and adjust your instrument for the sound you want to get
Amplification and signal processing/effects
The practical musicianship of locking in with a drummer and being part of the rhythm section

Bass is no easier than any other instrument to play really well, but a lot of songs have simple bass parts that are really not that tough to play well enough, even for a novice. I would suggest that if you want to play with a band, then that's your starting point; Just by being aware of the areas mentioned above, you'll be able to address the specific issues you face as they come along.
Answer: Do you also have the basics of the instrument's hand positioning for chords, etc. down? No one can teach feel...it must come from your soul. That said however technical ability can be taught - you say you are all set there. Excellent!! Now, find your voice and play! I suggest that you choose a few amazing Bass Players in the genre of music you prefer, find videos of live performances and study, practice, study. practice.  I know many technically correct instrument players and vocalists who lack 'feel'.... You will get there...this is the same for any instrument.
Comment: "find your voice" is very true. The bass can be played (and set up to play) in a bunch of different ways - a lot of the process is about working out how to achieve what *you* want to achieve.
Comment: Nice to see this. The fact is that I am a total noob to bass, but a fairly experienced musician overall. My point is that I really need to get the very rudimentary aspects of bass playing (although I can find notes in the fretboard, I lack everything related to fingering, posture, tone etc.), but these are generally so attached to rudimentary aspects of theory that they end up getting more attention than the bass playing itself.
Answer: There are numerous online resources available.  See Scott's Bass Lessons on YouTube to start with. He as an excellent video on postures, fingering, etc. for electric bass guitar.  I'm sure with a simpe search you could find the same info for stand-up / acoustic bass as well.
Answer: It's often been said, and I certainly agree, that teaching something makes you learn it really well. You're already a teacher, why not get the bassics (sic) and start some pupils. You will always be a few steps ahead, if not more! Finding your way round a bass is not difficult, and techniques can be your own. Nothing wrong with that.
For the more advanced stuff, which may be a little while away, I found that videos were the best choice, so I could emulate what I saw and heard, but I taught myself ( I play guitar, which helps a little) way before I resorted to other teaching aids. Playing with others, as topo morto says, also concentrates the mind. As does playing along with the radio, C.D. etc. Just go for it!
Answer: Some basic things to learn.
Patterns

Root Fifth
Root Fifth Octave
Root Fifth Flat Seventh
Root Fifth Sixth
Boogie Woogie Bass

Chromatic Approach Notes
Straight & Shuffle Rhythms


How many subsets does the set $\{1, 2, \dots , n\}$ have that contain no two consecutive integers if $1$ and $n$ also count as consecutive?

Question:
How many subsets does the set $\{1, 2, \dots , n\}$ have that contain no two
consecutive integers if 1 and n also count as consecutive?

It looks that the number of such subsets obeys the (Fibonacci-style) formula
$$ F(n) = F(n-1)+F(n-2) $$
with $F(0)=1$ and $F(1)=2$, but I wasn't able to prove this conjecture.
Comment: Well, it's the number of subsets that don't contain two consecutive integers, minus the number of subsets that don't contain two consecutive integers but do contain both $1$ and $n$.
Comment: http://math.stackexchange.com/questions/154763/combinatorics-selecting-objects-arranged-in-a-circle
Answer: For first, let we solve a sub-problem.

Claim: if $S_n$ is the set of the strings of $n$ characters over the alphabet $\Sigma=\{0,1\}$ such that no two consecutive "1"s occur and $l_n=|S_n|$, then
$$ l_n = F_{n+2} $$
where $F_0=0,F_1=1$ and $F_{m+2}=F_{m+1}+F_m$ define the usual Fibonacci numbers.
Lemma: the prefix of an element $s\in S_n$ can be only "0" or "10". This gives $l_{n+2}=l_{n+1}+l_{n}$ while $l_0=1=F_2$ and $l_1=2=F_3$.

See also Fibonacci coding and Zeckendorf's theorem.

Back to the original problem: let $T_n$ ($n\geq 3$) be the set of strings of $n$ characters over the alphabet $\Sigma=\{0,1\}$, where the last character is considered to be adjacent to the first one and no two consecutive "1"s occur.
If the first character of $s\in T_n$ is a "0", then its removal just leaves an element of $S_{n-1}$. Otherwise, if the first character of $s$ is a "1", then both the second character and the last one are zeros, and by removing these three characters we get an element of $S_{n-3}$. By the previous lemma, we have that the number of "neighbours-free" subsets of $\{1,\ldots,n\}$ is given by:
$$F_{n+1}+F_{n-1}=L_n = \left(\frac{1+\sqrt{5}}{2}\right)^n+\left(\frac{1-\sqrt{5}}{2}\right)^n\tag{1}$$
for any $n\geq 3$. See also Lucas' numbers.


Intonation problem with guitar

Question: I have a Fender Model CD-60 NAT, which is having some intonation problems. I fully intend to take it to a professional, but would like to understand the problem and the most likely fix beforehand.

The action is pretty high. This is not the main problem.
The problem is with the thin E string. When I tune the guitar wrt the open string, it plays just fine for the first three frets. See the harmonic minor scale shape I'll be referring to:

The fret which has the first note of the scale, on the thick E string, will be called N. In the figure, N=8.
When I start with N=1, i.e. F harmonic minor, it's fine. But the frets start getting progressively flatter and flatter (i.e, out of tune), so for eg. N=11, Eb harmonic minor, instead of the two frets on the thin E string being 10 and 11,  I have to play frets 11 and 12 to complete the scale. So by the time I reach N=11, the frets have started sounding one WHOLE SEMITONE flat. However, the first three frets are still sounding fine!

The natural harmonic on the thin E string, which should occur on the 12th fret, actually occurs on my guitar in the 13th fret, with the note sounding like an E.
Comment: This is a really confusing way of describing it. Just test harmonic & octave, or even harmonic & 7th fret.
Comment: @Tetsujin Uh..what's the difference between harmonic and octave?
Comment: The harmonic is lightly touching and plucking the string at the 12th fret. The octave is actually fingering the 12th fret then comparing the two. You said the octave harmonic is occurring at the 13th fret, not the 12th but ONLY on the high E string?
Comment: Yes. You're correct @JohnBelzaguy I've played and compared multiple times and it is only on the thin E string.
Comment: Have you confirmed this with an electronic tuner? This is highly irregular. I would start by replacing that one string. The action being high also raises concerns although that could just be a neck relief/truss rod issue. Does the neck joint look sound/solid? Aside from a severely defective string I can only think of either structural damage or a manufacturing defect being the problem. A repair person should be able to diagnose this for you free of charge.
Comment: I had a thought, was this guitar converted from right to left handed or vice versa? It is an acoustic with a fixed bridge and if someone just flipped the strings around the intonation would be completely off. The bridge saddle should angle away from the neck going from high to low strings…
Comment: @JohnBelzaguy for first answer: yes, I've checked with electronic tuner.  Yes, neck joint looks fine, though any flaws could in theory have been hidden by the varnish. For second answer: Yes, the bridge is (slightly) towards the round hole for the thin E string and angles away as we mive to the thicker strings. No, I bought it new. Any changes of handedness is not known.
Comment: In that case start with a new E string then take it to a repair shop or the store where you bought it if there is no difference. Fender has warranties on  their products.
Comment: Sorry, but the guitar was bought 4 years ago! And please don't ask me what I've been doing ignoring this problem for this long ;). I haven't played above the fourth fret for more than 2-2.5 years I think, so I never even knew the problem existed.
Answer: What you describe is pretty standard for a bridge saddle that is placed too far from the nut (i.e. intonated too flat.)  The intonation adjustment at the bridge has more effect on higher frets than lower frets.  So, if your intonation is flat, the notes will get flatter and flatter as you go up the fretboard.
HOWEVER, having your intonation be off by an entire semitone is unusual.  So, please check intonation on the E, B, and G strings with a tuner.  If only the E string goes flat, then the bridge should look pretty strange- the bridge saddle contact point with the E string would have to be a full centimeter further than the B and G to cause this.
Answer: There are multiple sources for intonation problems on a guitar.

Misaligned frets (or frets with a bad profile). Of course, if your frets are off, you will have a hard time with intonation. This is not really fixable, but should not happen on good instrument.
Wrong bridge position. Almost all electric guitars have adjustable bridge riders which allows for taking this position back or forth to compensate this. Characteristic for this is that the further up you go the flatter you get (if the position is to low) or the sharper you get (if the position is too high).
Wrong nut position. If the nut is in the wrong position the first fret is wrong, resulting in bad intonation especially around the lowest frets. Theoretically adjustable, but usually requires more effort that simply adjusting the bridge riders, as most nuts are not adjustable.
Bad technique. Pressing the strings too hard or accidently bending the strings can make the strings go sharp.
Overall limitations of the design. With straight frets you cannot get each not in tune, so you need to live with not ever note being exactly in tune (there are compensated frets, but that is pretty much a niche thing).

In you case (the higher you go the flatter you get) this is a clear sign of number two, with the bridge rider of the e string being too low. Of course, each guitar has combination of these issues, so you cannot get your guitar exactly in tune. Common practise is to intonate the guitar in such a way that the intonation is correct on the twelfth fret. A good way to check this quickly is to compare the harmonic with the actual pitch on the twelfth fret (although this is not exact, since the harmonic at the twelfth fret is not an exact octave of the open string).
The intonation of the string is affected by other factors like tension, thickness and action (pressing the string raises the tension, increasing the pitch). So this intonation must be adjusted quite frequently, even if you simply choose to use a slightly different set of strings.
Adjusting the action will thus require an adjustment of intonation, so this is something that should be done after you've setup everything else.
Answer: All of the 12th fret harmonics should sound when the strings are touched exactly over the 12th fretwire. And should produce the same pitch as when the strings are pressed down on that 12th fret. That's called the intonation. When it's inaccurate, it's usually the bridge at fault, and with you producing that harmonic at the 13th fret, yes it's way out.
It's just possible that the string is at fault - the bridge does compensate for thicker strings by being placed further back for thicker strings - but top E is generally the shortest string of the lot. Change the string, maybe for a thinner gauge, oterwise it's major surgery, especially if the other 5 strings are intonated well. In fact, it's probably more than major surgery...
Comment: I mean, yeah. If you press the 13th fret after standard tuning for open strings, then you'll get an E. If you just touch above the 13th fret you'll also get an E.  By the way, do you concur with the opinion that "Made in Indonesia" guitars are generally good? Cuz it's written inside the body and I have a hard time believing that it could be this bad.
Comment: The older 'MII' guitars were good, I have a couple. Not sure about lately.

Intonation problem with guitar


Otimização para código que testa se um número é primo

Question:
Olá! Minha pergunta é sobre um código que eu montei, onde o usuário insere um certo número de sua escolha, e o programa irá testar se o mesmo é primo ou não, porém, ele está testando todos os números entre dois (2) e o número inserido, o que pode ser bem lento para números de grande porte (os mais indicados para a função do código). Uma solução que tive em mente foi para construir uma espécie de "Crivo de Eratóstenes", onde o programa iria eliminar todos os múltiplos dos números que já foram testados (como 2, 3, 5, 7 e 9), para assim, acelerar o processo de verificação do numero.

Entretanto, todas as minhas tentativas para chegar nesse objetivo não vingaram.** Por isso, estou questionando aqui se algum usuário tem algum algoritmo ou método que eu possa adaptar e (consequentemente) aprender com ele.
Abaixo está meu código caso seja nescessário (o que provavelmente é):
import sys

def programa():
    completo = None
    while True:
        if completo == True:
            break
        print()
        print("=" * 55)
        num = int(input("Digite um número para fazer o teste se o mesmo é primo: "))
        einteiro = isinstance(num, int)
        if num == 1:
            print()
            print("1 é primo.")
            print()
            completo = True
            break

        if num == 2:
            print()
            print("2 é primo.")
            print()
            completo = True
            break

        if einteiro == True:
            print()
            print("O número escolhido foi %d" % num)
            print()
            divisor = 2
            while divisor < num:

                teste = num % divisor
                divi = num / divisor

                if teste == 0:
                    print("Este número não é primo! Ele conseguiu dividir pelo número %d, o resultado foi %d!" % (divisor, divi))
                    print()
                    completo = True
                    break

                if teste != 0:
                    print()
                    print("Ele não divide por %d..." % divisor)
                    print()

            if divisor == num:
                print("Ele é primo!")
                print()
                completo = True

        if einteiro == False:
            print("O número tem que ser inteiro!")

    while True:
        a = input("Deseja ir de novo? (y/n): ")
        if a in ('y', 'n'):
            if a == 'y':
                programa()

            else:
                print()
                print("Adeus :)")
                print("=" * 50)
                sys.exit()

        else:
            print()
            print("Digitação Inválida!")
            print()
            continue

programa()

Comment: Use o teorema de Rosser para encontrar o enésimo primo.
Comment: Creio que faltou incrementar a variável divisor em seu programa.
Comment: Pela definição de número natural primo:
- 1 não é primo;
- 2 é o unico natural par que é primo;
- se não existe nenhum número entre 2 e SQRT(n) que divida n então n é primo.
Com estas considerações você pode otimizar bastante seu código.
De qualquer maneira não será a maneira mais otimizada de se determinar se um número é primo.
Comment: `int(qualquer coisa)` já retorna um `int`, não precisa usar `isinstance` depois. Pra saber se `int()` falhou, vc captura o `ValueError` - tem exemplo [na documentação](https://docs.python.org/3/tutorial/errors.html#handling-exceptions). Valores booleanos podem ser testados diretamente: `if completo:` em vez de `if completo == True:`. Pra imprimir uma linha em branco, use `\n`, então no início poderia ser `print('\n{:=^55}'.format(''))` - o `\n` pula uma linha, e o formato `=^55` preenche com 55 caracteres `=` (veja exemplos em https://docs.python.org/3/library/string.html#format-examples)
Comment: De qq forma, algoritmo pra achar números primos é o que não falta na internet (inclusive [aqui no próprio site](https://pt.stackoverflow.com/search?q=python+n%C3%BAmero+primo)). Alguns exemplos: https://pt.stackoverflow.com/q/231555/112052 | https://stackoverflow.com/q/1801391 | https://stackoverflow.com/q/2068372 | https://stackoverflow.com/q/18833759
Comment: Isto responde à sua pergunta? [Função que retorna o menor número primo. Em PYTHON](https://pt.stackoverflow.com/questions/191130/fun%c3%a7%c3%a3o-que-retorna-o-menor-n%c3%bamero-primo-em-python)
Answer: Simplificação:
import sys

def programa():
    print("=" * 55)
    num = int(input("\nDigite um número para fazer o teste se o mesmo é primo: "))
    einteiro = isinstance(num, int)
    if num == 1:
        print("\n1 é primo.")
    elif num == 2:
        print("\n2 é primo.")
    else :
        einteiro == True ,print("\nO número escolhido foi %d" % num)

    def divisor(n):
        n=2
        teste = num % n
        divi = num / n
        if teste == 0:
            print("\nEste número não é primo! Ele conseguiu dividir pelo número %d, o resultado foi %d!" % (n, divi))
        elif teste != 0:
            print("\nEle não divide por %d..." % (n))
        elif n == num:
            print("\nEle é primo!")
        else:
            einteiro == False
            print("\nO número tem que ser inteiro!")

    a = input("Deseja ir de novo? (y/n): ")
    if a in ('y', 'n'):
        if a == 'y': programa()
        elif a=='n':
            print("\nAdeus")
            print('='*50)
        else:
            a!='n'or 'y'
            print("\nDigitação Inválida!")

programa()


How to Solve the nonlinear first ODE?

Question: How to Solve the nonlinear first ODE ?
$y' = (y-1)^2 (t^4 e^y +\sin(y^2))$ , with $y(0) =1$
What I know only is How to solve the linear first ODE , I don't know about the nonlinear at all .
Comment: Are you supposed to numerically approximate it?  Because that looks impossibly difficult unless there's a trick I'm not spotting.
Answer: Ah, this is a trick.  See, the problem looks impossibly hard, but if you plug in the initial condition, you get $y' = 0$, so $y$ never changes!
Comment: Wow, you saved me !
Comment: When a problem looks too bad to be true, it sometimes is!
Comment: $y=1$ is the only solution

How to Solve the nonlinear first ODE?


Explanation of .net code

Question: Can someone explain what is happening in the following code:
private IList<SomeModel> ImportSomething<T>(IEnumerable<ISomeInterface> someResponse, Func<ISomeInterface, Conversion<T>> converter) => someResponse
    .Select(converter)
    .Where(conversion => conversion.Status == ConversionStatus.Success)
    .Select(conversion => conversion.Object)
    .Cast<SomeModel>()
    .ToList();

The code above is called by:
ImportSomething(collectionOfThings, _thingConverter.FromXmlResponse)

Answer: Not what actually happens, but logic idea is same.
var result = new List<SomeModel>();

foreach (var response in someResponse)
{
    // Select(converter)
    var conversion = converter(response);

    // Where(conversion => conversion.Status == ConversionStatus.Success)
    if (conversion.Status == ConversionStatus.Success)
    {
        // Select(conversion => conversion.Object)
        var value = conversion.Object;

       // Cast<SomeModel>()
        var model = (SomeModel)value;

        result.Add(model);
    }
}

return result;

Answer: You have a generic method whose signature is the following:
private IList<SomeModel> ImportSomething<T>(
    IEnumerable<ISomeInterface> someResponse
    , Func<ISomeInterface, Conversion<T>> converter)

This method has two arguments. The first one is a sequence of ISomeInterface objects. Wherease the second one is a Func which takes as an input an object that implements the interface ISomeInterface and returns an object of type Conversion<T>. Essentially it is method that convert the input of an object that implements the interface ISomeInterface to an object of type Conversion<T>.
Then for a given input, which is denoted as someResponse some transformations applied.
First, for each item in the sequence someResponse the converter is applied:
someResponse.Select(converter)

This way all the ISomeInterface objects in this sequence would be converted to objects of type Conversion<T>.
Then the items that failed to be converted would be filtered out and a new sequence would be created with the objects that have been converted successfully:
Where(conversion => conversion.Status == ConversionStatus.Success)

After this a projection is made and from the Conversion<T> objects we have we get only the Object property:
Select(conversion => conversion.Object)

Last we cast each item in our sequence to a SomeModel object and we request the immediate execution of our query by calling the ToList method.
The reult of the executed query would be a List<SomeModel> objects.
The above steps can be more specific if you have a concrete example as the one you mentioned:
ImportSomething(collectionOfThings, _thingConverter.FromXmlResponse)

Now the sequence of objects on which all the above would be applied is the collectionOfThings object and the converter that would be used is the _thingConverter.FromXmlResponse. It is not needed you specify the T, because the compliler can infer it form the the type of _thingConverter.FromXmlResponse.

Explanation of .net code


How do github unique clones work with push --force?

Question: So I've been experimenting with a repository and editing commit timestamps, and using git push --force to get those changes into the remote repository, and I've noticed some odd behaviour with the traffic stats on the repo. What I'm doing is:

Make some new test file in the repo.
git commit -m "something".
GIT_COMMITTER_DATE=[new date] git commit --amend --no-edit --date [new date]
git push --force

It appears that every time I do this, I get 1 or 2 new unique clones on the repository, and I was wondering why this might be happening.
Answer: There isn't any intrinsic reason why a force push must imply a clone operation at all.  If you're using a CI tool or GitHub Actions, then that's probably the reason, since those will clone repositories.  Otherwise, there are feeds of activity on public repositories so it's possible for people to watch those and clone when changes occur.
Sometimes people do this to find credentials that are pushed to repositories and exploit them.  A force-push might imply that someone accidentally pushed something secret, so those might be more interesting than normal.
I wouldn't worry about it, personally; it's just an interesting behavior.
Comment: I'm not using a CI tool or GitHub Actions, but I appreciate the info!


Proof that Recall ≥ F1-score

Question: I need to prove mathematically that the value of Recall is always bigger or equal to the F1-score.
The equation would be: $2 \times Precision \times \frac{Recall}{(Precision + Recall)} \le Recall$
Does someone have an idea how I can prove this mathematically?
Comment: The F1-score is the harmonic mean of precision and recall and so falls between them when they are different.  So the statement you want to prove can only be true when recall is greater than or equal to precision.
Comment: @Henry thank you very much. This explanation makes it really clear,
Answer: It isn't in general. R code:
<code>> precision <- 0.9
> recall <- 0.5
> 2*precision*recall/(precision+recall)
[1] 0.6428571
</code>
A possible confusion matrix giving rise to these precision and recall values would be:
<code>          Predicted P   Predicted N
Actual P       9             9
Actual N       1             5
</code>
Note that recall and precision suffer from precisely the same problems as accuracy.
Comment: Could you please provide the corresponding confusion matrix?
Comment: Indeed it will fail iff $\text{precision }\gt\text{ recall}$
Answer: $$
\begin{array}{rl}\begin{array}{c}\\\\
\rlap{\vphantom{\frac{\frac{1}{1}}{\frac{1}{1}}}\require{HTML}\style{display: inline-block; transform: rotate(270deg)}{\text{truth}}}\end{array}&&
\begin{array}{c|cc}
& \rlap{\text{predictions}}
 \\ & P & N\\ \hline
P & TP & FN \\
N  & FP & TP\\
\end{array}\end{array}$$
You have
$$\begin{array}{rcl}
\text{precision} &=& \frac{TP}{TP+FP} \\
\text{recall} &=& \frac{TP}{TP+FN}
\end{array}$$
Recall and precision are related with both having $TP$ in the numerator.
In terms of $TP$, $FP$ and $FN$ you get for the $F$ score.
$$\begin{array}{}F& =& 2\frac{\frac{TP}{TP+FP} \cdot \frac{TP}{TP+FN}}{ \frac{TP}{TP+FP} +  \frac{TP}{TP+FN} } \\
& =& \frac{ TP}{TP+FN} \cdot \underbrace{\frac{2(TP+FN)}{2(TP+FN)+FP-FN}}_{\text{$< 1$ if $FP>FN$} }
\end{array}$$
So it is only true if $FP>FN$ or when recall is larger than precision. This makes sense since the F score is the averag of recall and precision. If precision is smaller than recall then the average will be smaller than recall.
Answer: You can prove this mathematically by using the definition of precision and recall and the equation for the F1-score. Here is a proof:
First, let's define precision and recall:
Precision is the number of true positives divided by the total number of predicted positives.
Recall is the number of true positives divided by the total number of actual positives.
Now let's write the equation for the F1-score:
F1 = 2 * Precision * Recall / (Precision + Recall)
To prove that the recall value is always greater than or equal to the F1-score, we need to show that the numerator of the F1-score equation is always less than or equal to the denominator. In other words, we need to show that:
2 * Precision * Recall <= Precision + Recall
To do this, we can first multiply both sides of the equation by Precision + Recall, giving us:
2 * Precision * Recall * (Precision + Recall) <= (Precision + Recall)^2
Next, we can expand the right-hand side of the equation using the formula for the square of a sum:
(Precision + Recall)^2 = Precision^2 + 2 * Precision * Recall + Recall^2
Substituting this into the previous equation, we get:
2 * Precision * Recall * (Precision + Recall) <= Precision^2 + 2 * Precision * Recall + Recall^2
Now, we can move all the terms with Precision and Recall to the left-hand side of the equation, and all the constant terms to the right-hand side, giving us:
2 * Precision * Recall * (Precision + Recall) - Precision^2 - 2 * Precision * Recall - Recall^2 <= 0
Next, we can simplify the left-hand side of the equation by combining like terms and factoring out Precision and Recall:
(2 * Precision * Recall - Precision^2 - Recall^2) * (Precision + Recall) <= 0
Finally, we can apply the difference of squares factorization to the left-hand side of the equation:
(Precision + Recall) * (Precision - Recall) * (Precision + Recall) <= 0
Since the product of three numbers is always less than or equal to zero if one of the numbers is less than or equal to zero, we can see that the left-hand side of the equation is always less than or equal to zero. Therefore, the original equation is always true, which means that the recall value is always greater than or equal to the F1-score.
This completes the proof.
Comment: If you prove that the numerator of a fraction is always less than or equal to the denominator, then you have shown that the fraction is no larger than one, not that it is less than some specific number (like recall in this case).

Proof that Recall ≥ F1-score


iOS UI Custom button images

Question: I'm developing a iOS app that is using custom UIButtons with round shape. I wanted to add Image to these buttons and would like to know if I use IB to select an image from my project, do I have to also worry about 2x retina images for retina display?. What should be the image size for both non-retina and retina devices (all iPhones (including iphone 5) and iPad including mini) when I embedded them from IB?
Is there a best resource available on the Internet to get these pngs files for buttons?
Answer: It is easy. Goto interface builder and on the right hand panel you will see this -

All you need to do is first configure your button as custom then include a image file in your project through xcode and then you can select that image in the dropdown in background or image property.
Note that all this is possible to do through code also, its just that IB makes it interactive. Hope this helps.
Answer: Yes you should use all the images. you should just add the images with proper names to the resources folder. And just select the non-retina image rest the compiler will take care of.
http://www.idev101.com/code/User_Interface/sizes.html
The above link will help you with the images sizes

iOS UI Custom button images


Do not cache custom block

Question: I have a custom block created in code. I do not want to cache the block. I know I need to use BLOCK_NO_CACHE but I am not sure where to use it.
<code>function mymod_block($op = 'list', $delta = 0)
{
    // set up an empty array which will contain the block contents
    $block = array();
    if ($op == "list") {
        // Generate listing of blocks from this module, for the admin/block page
        $block[0]["info"] = t('mymod');
    }
    else if ($op == 'view') {
        $block['content'] = "hello world";
    }
    // return the built content
    return $block;
}
</code>
Answer: In your list $op, add:
<code>$block[0]['cache'] = BLOCK_NO_CACHE;
</code>
However, note that Drupal 6 will not automatically update your block information, you will have to do that yourself, see privatemsg_update_6002() for an example.
Comment: to note: "If page cache is enabled then blocks *will* be cached, regardless of block cache settings in hook_block()." -- http://www.drupaler.co.uk/blog/page-and-block-caching/114

Do not cache custom block


If statement keeps returning true

Question: So I am new to coding (starting with python) and I am trying to make a super simple/basic calculator. I've run in to this problem before on another set of code that I can't figure out why. Even though it's false the line of code returns true.  So say I did 100 divided by 5, it returns true for "*" and "Multiply" which gives the outcome of 500 instead of the correct answer which should be 20. If someone could explain/show why it's returning true instead of false?
def calculator():
    Number_input_one = int(raw_input("Enter your first number: "))
    Math_symbol = raw_input("What do you want to do? ")
    Number_input_two = int(raw_input("Enter your second number: "))

    if Math_symbol == "*" or "Multiply":
        print Number_input_one * Number_input_two
    elif Math_symbol == "/" or "Divide":
        print Number_input_one / Number_input_two
    elif Math_symbol == "+" or "Add":
         print Number_input_one + Number_input_two
    elif Math_symbol == "-" or "subtract":
        print Number_input_one - Number_input_two
    else:
        print "it doesn't match anything!"

Comment: Note that `lowercase_names` are often used for Python variables, while `UpperCamelCase` is usually used for classes.
Comment: Please also remember to properly indent your code. I assume your code was working without indentation errors.
Answer: You are making a classic mistake:
if Math_symbol == "*" or "Multiply":

doesn't do what you think it does. The correct version is:
if Math_symbol in ("*", "Multiply"):

What your version of the code is doing is checking if Math_symbol == "*" or if "Multiply" exists (i.e. it is not an empty string). This will always evaluate to True since the string "Multiply" does exist.
Similar corrections are needed for the other if statements:
if Math_symbol in ("*", "Multiply"):
    print Number_input_one * Number_input_two
elif Math_symbol in ("/", "Divide"):
    print Number_input_one / Number_input_two
elif Math_symbol in ("+", "Add"):
     print Number_input_one + Number_input_two
elif Math_symbol in ("-", "subtract"):
    print Number_input_one - Number_input_two
else:
    print "it doesn't match anything!"

Answer: You can also try this:
if (Math_symbol == "*") or (Math_symbol=="Multiply"):

elif (Math_symbol == "/") or (Math_symbol == "Divide"):

and so on!
Answer: You want math_symbol == "-" or math_symbol == "subtract"
the statement "string" always evaluates true

If statement keeps returning true


Algebraically closed field, polynomials decompose?

Question: If I work over an algebraically closed field $K$, and $f(x)\in K[x]$, then $f(x)$ always factorises into a product of linear polynomials, being the roots, is that correct?
I.e. $f(x)=(x-a_1)(x-a_2)\cdots(x-a_n)$?
Is that the right way to phrase it aswell? Linear polynomials, that are the roots?
Comment: When a polynomial factors completely into a product of linear polynomial over a field, we often say it "splits" over that field.  But don't confuse the linear polynomials $x-a_i$ and the roots $a_i$.  They have different names.
Answer: It's true up to a constant that over an algebraically closed field all polynomials factor in the way you describe. The correct statement is that every polynomial factors as
$$f(x) = b(x-a_1)\dots(x-a_n)$$ for $a_i,b \in K$. The point is you can't guarantee the leading coefficient is $1$ (consider the polynomial $2x-1$ for instance). Note also, that  we could have $a_i = a_j$ for some $i \neq j$.
The best way to phrase this is probably to say that every polynomial factors as a product of linear polynomials or splits into linear factors.
The roots refer to the elements $a_i \in K$ such that $f(a_i)=0$. While it's true that these (counted with multiplicities) determine the factorization of $f$ up to a constant, these do not refer to the linear factors themselves.
Comment: Thanks I really appreciate this answer.  Clears up a few of my worries


Microsoft-graph-api, SSO and ADAL mobile sdk

Question: I have developed few iOS/Android app using Azure Ad SDK 'ADAL'.
The app works properly for SSO feature and other login mechanisms. However now I want to add 'new contact' using Azure ad access token. But I came to know that Azure ad graph is no longer supported hence latest Microsoft Graph is suggested sdk for the same.
My issue is: The most important feature according to me is the Single Sign-On feature with respect to mobile apps SDK  Azure ad SDK offers API for most convenient login user experience. Thus you are free to pick account from Authenticator app (if present) or any other app in the device which is already logged in.
But Microsoft Graph SDK does not support Authenticator app available on the mobile phone. And prompts user a Login screen though he has already logged in to other app having outlook/Microsoft login
Please help me with some more information on this use case so that I can migrate to Microsoft graph from Azure Ad app.
I have a huge tradeoff as follow
1. Azure ad supports SSO but does not support Latest Graph features like: Adding new contact in 'My Contacts'
2. Microsoft Graph being Latest library/SDK has all features EXCEPT SSO.
Please provide me answers for these question of any suggestion if I am missing anything.
Comment: I am in need of help for the following question. Can you please check it out?  https://stackoverflow.com/questions/52815169/adal-sdk-for-webview-android-for-sso
Answer: The Graph SDKs do not contain any helpers for authentication/authorization.  For that you need to use either ADAL or MSAL to acquire tokens to use with Microsoft Graph (to instantiate a GraphClient object).  Please take a look at some of our Microsoft Graph samples. [NOTE the Azure AD Graph SDK also relied on ADAL or other mechanisms to acquire tokens and does not do this for you].  Here are the iOS samples:  https://github.com/search?q=ios+sample+user:microsoftgraph&type=Repositories
Also Azure AD Graph does not support personal contacts - this is ONLY supported by Microsoft Graph.
If you want to see an integrated client library, where token acquisition is implicitly taken care of as part of GraphClient instantiation then please post a request on UserVoice for this feature.
Hope this helps,
Comment: I'm not sure I understand the question.
Comment: Is there any way to have this explicitly. What I mean, is it possible to have some mixed or hybrid way to initiate GraphClient object, Instead of waiting for Microsoft to include this use case in future
Comment: @DanKershaw-MSFT, I am expecting a help from you for integrating ADAL SDK in my application. Can you please check the question in the following link?https://stackoverflow.com/questions/52815169/adal-sdk-for-webview-android-for-sso


Type of time series to use

Question: Consider the following time series plot:

I am trying to fit a time series to this data. I am using it for the purposes of prediction. What type of time series would work here?
I would like to fit a time series to only the part of the data that doesn't spike immediately upward.
Comment: Suspect you are trying to do the impossible....
Comment: Is this time series financial data, such as stock prices?
Answer: Is the issue something like this: "I want to use a model before the big uptick, and then forecast forward through the uptick -- to see whether the uptick would be predictable from what came before, or was unusual (for some probability level of "unusual")."
If that is the case, I would follow the lead of Makridakis and Hibron (International Journal of Forecasting, 2000, page 459, in the M3 forecasting competition) and run single exponential smoothing, Holt and dampen -- plus their average.  Each of these has a calculation for likely forecast error.  This will tell you how extreme this spike is on the basis of 3 forecasting methods in very common use.
If this works, thank a sailor -- all these methods have a strong historical connection with the U.S.Navy.
Answer: An exponential smoothing model might work.  I'd say the primary question is: do you expect the massive uptrend to continue or do you expect the series to revert to the mean?  Has anything like this happened in the past or for similar time series?
Comment: @proton So you want to fit a model BEFORE the uptrend, and then you want the model to predict the uptrend? That's going to be very hard to do with a univariate time series model.  Do you have any other covariates you could pull in?
Comment: I expect the massive uptrend to continue. The thing is, I want fit a time series using only data that doesn't trend up and then predict data during that interval.

Type of time series to use


$A^n\cong A^m$ implies $n=m$ without using tensor products.

Question: Let $A$ be a nonzero commutative ring with 1. Then we can show that $A^m\cong A^n$ implies $m=n$ by picking a maximal ideal $I\subset A$ and tensoring both sides of
$$
A^m \cong A^m
$$
with $k=A/I$. Is it possible to prove the statement without using tensor products?
Comment: Well, you could just show by hand that $A^m = A^n$ induces $(A/I)^m = (A/I)^n$.
Comment: But this MO answer is definitely, what you are looking for and it even shows more: https://mathoverflow.net/a/47846/93853
Answer: A ring $R$ (not necessarily commutative) is called stably finite if for each $n \in \Bbb N$, the matrix ring $M_n(R)$ has the property that $AB=1$ implies $BA=1$ for $A,B \in M_n(R)$.

Claim Any commutative ring $R$ is stably finite.

Proof: Suppose $AB=1$ for $A,B \in M_n(R)$, then $\det(A)\det(B)=\det(B)\det(A)=1$, so $\det(A) \in R^\times$, this implies that $A$ is invertible by Cramer's rule. Thus we get $AB=1=A A^{-1}$, so $B=A^{-1}$ after multiplying with $A^{-1}$ from the left.

Claim If $R$ is a non-zero stably finite ring, then $R^n\cong R^m$ implies $n=m$

Proof: Assume $n \leq m$ and let $k=m-n$, then we have by assumption $R^n \cong R^m = R^n \oplus R^k$. Take this isomorphism and compose it with the projection $R^n \oplus R^k \twoheadrightarrow R^n$ onto the first summand, to get a surjective homomorphism $f:R^n \to R^n$. Because $R^n$ is projective, the sequence $$0 \to \operatorname{ker}(f) \to R^n \xrightarrow{f} R^n \to 0$$
splits, so we get a homomorphism $g: R^n \to R^n$ such that $f \circ g = \operatorname{id}$. If we regard $f$ and $g$ as matrices, then we get $g \circ f=\operatorname{id}$ since we assume that $R$ is stably finite. This shows that $f$ is injective. But since $f$ is the composition of an isomorphism with the projection $p:R^n \oplus R^k \twoheadrightarrow R^n$, $p$ must also be injective. But $\operatorname{ker}(p)=R^k$, so $R^k=0$, thus $k=0$ and $n=m$.
All of the above and more on rings that satisfy "$R^n\cong R^m \Rightarrow n=m$" can be found in the first section of the book "Lectures on Modules and Rings" by T.Y. Lam (though some of the details I worked out are left to the reader).


Custom Button Text on JavaScript Confirm

Question: Mega has an interesting function running on it which appears to customize the title and button text of a JavaScript confirm() box:

How is this achieved, when every resource I'm finding here and elsewhere is telling me it's impossible?
Thanks!
Comment: `window.onbeforeunload:function (){if (downloading || ul_uploading) return l[377];} `. Probably this?
Comment: I suspect that is not a javascript window, checking..How do you get the confirm to show up?
Comment: I reload the page during a file transfer. I'm pretty sure it is a pure JS window, not a polyfill like jQueryUI's dialog, because it has the operating system's (Ubuntu 10.04) window chrome and button style.
Comment: You can tell, because a standard dialog window will allow you to move it outside the browser window, CSS/HTML dialogs you can not move outside the window.
Comment: is that just the browser?
Comment: I'm not sure I follow the question. Are you suggesting the browser itself is creating the dialogue of its own accord, or are you asking if the dialogue matches the browser style? For what it's worth, the browser is Chromium 25.0 on Ubuntu 10.04.
Comment: @Passerby, that does look like it's it, so I thank you! Now to Figure out what that's actually triggering.
Answer: Per Passerby's suggestion in the question comments, I did some tests, and it turns out that Chromium's onbeforeunload text is customized for a reload as opposed to a navigation or page close. As such, reloading the page caused the event to fire and return the reload confirmation.
Fiddle: http://jsfiddle.net/eXFnR/
Thanks for the insight!