(Yii2) submitButton =>Converting onclick function to siteControllers?

Question: index.php
<?php  use yii\helpers\Html; ?>

<?= Html::submitButton('tew',

['class' => 'btn btn-primary',

'onClick'=>'buttonClicked']) ?>

siteController.php
public function actionIndex()
    {
        if($buttonClicked)
           {

        echo "Button Clicked";

}
        return $this->render('index');

So how to call button click function in siteContoller
Answer: If you need  check a specific submit button you must name it  and assign a value
You can obtain the submit this way
 'value'=>'create_add', 'name'=>'submit'
    <?= Html::submitButton('tew',['class' => 'btn btn-primary',
            'value'=>'my_value', 'name'=>'submit',
          'onClick'=>'buttonClicked']) ?>

then in your controller you can check the if specific button is clicked
public function actionIndex()
{
   if (Yii::$app->request->post('submit')==='my_value') {
      echo "Button my_value Clicked";
   }
   return $this->render('index');
}

In your case you must add  the value
<?php

use yii\helpers\Html;

?>

<?= Html::submitButton('tew',['class' => 'btn btn-primary',
                'value' => 'my_value', // you must add  a proper value to check in action
                'onClick'=>'buttonClicked']) ?>

Comment: The action in controller is executed  server side when you form is submitted ...not locally in the browser .. in your code you invoce a function buttonClicked when clik event happen ..  then try remove the 'onClick'=>'buttonClicked'  form your button code .. (could be you don't have a proper buttonClicked  function and the code fails ) ... check in your browser  console what happen after the click  ..
Comment: In browser console after click "uncaught referenceerror buttonClicked is not defined"
Comment: as expected .. you have a call for a function that not exist .. then you have two choice  .. or you remove the code  'onClick'=>'buttonClicked' from you buttom and so the php code is called  and executed .. or you add  a proper javascript function named buttonClicked() and do what do you want inside this function ..  hope this is clear ..
Comment: siteController.php => public function actionAdd(){
        echo "asdasdasdasd";
    }

index.php =>  'q1',
    'class' => 'btn btn-primary',
    ]) ?>

   ajax.js=> 'q1',
    'class' => 'btn btn-primary',
    ]) ?>
Comment: sorry that was mistake
Comment: I tried to call function from siteController:=>public function actionHello(){echo "Hello"; return $this->render('index');} As you said I use javascript function js2.js=>$(document).ready(function(){

    $("#q1").click(function(){
        $.ajax({
            type: "POST",
            url  : 'hello'

        });
    });

}); index.php => 'q1', 'class' => 'btn btn-primary', ]) ?> but it also not working....maybe wrong url in js2.js
Comment: public function actionIndex()
{
   if (Yii::$app->request->post('submit')==='my_value') {
      echo "Button my_value Clicked";
   }
   return $this->render('index');
} this was your code . But "if" not working here
Comment: you must add  the proper  value to your submit button  .. answer udpated
Comment: It works but after updating page it shows "The page that you're looking for....". And shows the message  even I did not click.
Comment: i suggest you of post a new properly documented   question with your actual code and the problem you have now  . .. if the code provided  work  then  mean that your original question  is solved ..


Let $R$ be $R=\Bbb{Z}[x]/(f)$, where $f∈\Bbb{Z}[x]$. For fixed rational prime $p$, Why $R/pR=\Bbb{Z}[x]/(p,f)$?

Question: Let $R$ be $R=\Bbb{Z}[x]/(f)$, where $f∈\Bbb{Z}[x]$.
For fixed rational prime $p$, Why $R/pR=\Bbb{Z}[x]/(p,f)$ ?
I may use certain isomorphism theorems, but I couldn't do it exactly.
Thank you for your help.
Comment: Have you tried defining maps between these rings? I believe the third isomorphism theorem is relevant here, but you should also know how to do this explicitly.
Answer: One way to think about this is in terms of basis.
First some definitions to understand the structure we are working in.
Let $\bar{p}(x), \bar{q}(x) \in \mathbb{Z}[x]/\langle f \rangle$, then $\bar{p}(x) \sim \bar{q}(x) \iff p - q \in \langle f \rangle$.
Likewise take any element $\bar{a}(x), \bar{b}(x) \in R$, then $\bar{a}(x) \sim \bar{b}(x) \iff a - b \in pR$.
Elements of $\mathbb{Z}[x]\langle f \rangle$ will be of the form $s(x) + \langle f \rangle$, and for $R / pR$, they will be $\bar{g}(x) + pR = (s(x) + \langle f \rangle) + pR$.
Lets define our isomorphism
$$\phi : R / pR \rightarrow \mathbb{Z}[x] / \langle p, f \rangle$$
$$\phi((a + \langle f \rangle) + pR) = a + \langle p, f \rangle$$
Proving injectivity, $\phi(a + \langle f \rangle + pR) = \phi(b + \langle f \rangle + pR) \implies a - b \in \langle p, f \rangle$. Which we can see means that $a, b$ represent the same coset in $R/pR$. Likewise the surjective map back is obvious.

Let $R$ be $R＝\Bbb{Z}[x]/(f)$, where $f∈\Bbb{Z}[x]$. For fixed rational prime $p$, Why $R/pR＝\Bbb{Z}[x]/(p,f)$?


How do I determine the value of $d$ from the tangent graph of the form $y = a\times \tan (bx + c) + d$?

Question:
I understand that $d$ is the vertical shift, and I have already worked out the values of $a$, $b$ and $c$ to be the following (please tell me if I am wrong):
$\pmb{a}\quad$ Given point is $(-1, -7)$ so I substituted it in as the values of  $x$ and $y$ ; $-7= a\times \tan\left(\dfrac{\pi}{4}\left(-1\right)+5\right)$ which I solved for $a$ and that gave me$\space$ -3.8040.
$\pmb{b}\quad$ Period so $\dfrac{\pi}{4}$
$\pmb{c}\quad$ $y$-intercept so $5$
But how do I find $d$ for this type of graph with only vertical asymptotes?
Comment: From the graph, the $y$-intercept is $-5$.
Comment: @Alyna-KuteaeyvaXX Please do not make edits to the question which invalidate the posted comments and answers. Rolled back.
Answer: You are correct in that $b = \frac{\pi}{4}$, but your reasoning isn't so clear. The function's period is $4$, and since $f(x) = \tan (\alpha x)$ has period $\pi / \alpha$, $b$ is $\frac{\pi}{4}$ by simple arithmetic.
So far we have $f(x) = a\tan(\frac{\pi}{4}x + c) + d$.
The function $g(x) = \tan(\frac{\pi}{4}x)$ has asymptotes at $x = 4n + 2$ e.g $x = 2$ where $n$ is an integer, while $f(x)$ has asymptotes at $x = 4n +1$. This means in the simplest case that $f(x)$ is $\tan(\frac{\pi}{4}x)$ translated $1$ unit to the left.
Hence $$ f(x) = a\tan\left(\frac{\pi}{4}(x+1)\right) + d \tag{1}\label{eq1}$$
Substitute the value $f(-1) = -7$ into \eqref{eq1} to obtain that $d = -7$, and substitute $f(0) = -5$ to obtain $a = 2$.
Finally we arrive at
$$f(x) = 2 \tan \left(\frac{\pi}{4}x + \frac{\pi}{4}\right) -7$$
I hope this answer was clear.
This is my first time giving an answer on this website, if you are a more experienced user and have any constructive criticisms feel free to share them with me.
Comment: Welcome! Your answer is fine.
Answer: The graph of a transformed $\tan$ function is
$ f(x) = A \tan( B (x - C) ) + D $
The first thing is that $ B = \dfrac{\pi}{T} $ where $T $ is the period.
Here the period is $ 4 $ , so $B = \dfrac{\pi}{4} $
$C $ is the horizontal shift to the right.  Here the graph is shifted to the left by $1$, therefore, C = -1 $
Now we have two points on the graph: $ (-1, -7)$ and $(0, -5) $. Hence
$ -7 = 0 + D $ from which $D = -7 $
and
$ -5 = A \tan( \dfrac{\pi}{4} ( 0 + 1 ) )  - 7 $
From which $ A = 2 $
Therefore, the function is
$ f(x) = 2 \tan( \dfrac{\pi}{4} x + \dfrac{\pi}{4} ) - 7 $


Por quê minha requisição AJAX não retorna o nome do meu arquivo de imagem?

Question: Não sei como obter o retorno esperado do AJAX com a instrução event.preventDefault() habilitada. Sem esta função a requisição é executada e o navegador vai direto para a página do arquivo PHP onde obtenho os dados das variáveis corretamente, mas com ela habilitada parece que o arquivo PHP é percorrido sem que os dados do arquivo de imagem sejam atribuídos à global $_FILES (os dados do input_texto são retornados normalmente).
Html
<form id='myForm' name = 'myForm' method='POST' enctype='multipart/form-data' action='myFile.php'>"
<input name='input_texto' type='text'>
<input name='image_input' type='file' id='file' accept='image/*'>
<input form='myForm' type='submit' value='Enviar'>

Script
 $("#myForm").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var actionUrl = form.attr('action');

    $.ajax({
       url: actionUrl,
       data: form.serialize(),
       type: "POST",
       success: function(data) {
          alert(data);
       }
    });
 });

PHP
echo $_FILES['image_input']['name'];
echo $_POST['input_texto'];

Comment: "*sem que os dados do arquivo de imagem sejam atribuídos à global*", de fato isso acontece. Veja aqui dezenas de perguntas que tratam como fazer upload utilizando AJAX: https://pt.stackoverflow.com/search?q=%5Bajax%5D+upload
Comment: se precisa fazer uma chamada *ajax*, que é assíncrona por natureza, não deveria fazer no evento *submit*, faça a ação num botão comum que não faça submit, e após o retorno assíncrono do *ajax*, lá no `success`, ai faz o submit
Comment: @RicardoPontual mas a ideia do AJAX é justamente substituir a ação do submit. Qual seria a diferença em fazer em um botão "comum"?
Comment: A solução foi o uso de um objeto formData ao invés do form.serialize(). Obrigado a todos pelo auxílio.
Answer: O problema pode estar relacionado ao uso do serialize() na chamada AJAX. A função serialize() serializa os dados do formulário em uma string de consulta que é enviada ao servidor.
Isso significa que apenas os dados dos campos de formulário que possuem o atributo name são enviados, mas não os dados do arquivo selecionado.
Para enviar dados de arquivo usando AJAX, você precisa usar um objeto FormData que permite a você enviar dados de arquivo e outros dados do formulário em uma única solicitação AJAX.
Para usar FormData, você precisa criar um novo objeto do tipo FormData e adicionar os dados do formulário a ele usando o método append().
Em seguida, você pode enviar o objeto FormData usando o método $.ajax().
Aqui está um exemplo de como usar FormData para enviar dados de arquivo usando AJAX:
$("#myForm").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var actionUrl = form.attr('action');

    var formData = new FormData(form[0]); // cria o objeto FormData a partir do formulário

    $.ajax({
       url: actionUrl,
       data: formData,
       type: "POST",
       contentType: false, // não definir o tipo de conteúdo
       processData: false, // não processar os dados
       success: function(data) {
          alert(data);
       }
    });
 });

Observe que os parâmetros contentType e processData são definidos como false. Isso é necessário para evitar que o jQuery tente processar o objeto FormData. Se esses parâmetros forem definidos como true, o jQuery tentará processar o objeto FormData como uma string, o que resultará em um erro.
Além disso, lembre-se de que o arquivo enviado deve ser tratado corretamente no servidor para que possa ser salvo ou processado corretamente. Você deve verificar se o arquivo foi enviado corretamente e se ele atende aos requisitos necessários antes de processá-lo.
Comment: Obrigado! O uso do formData funcionou perfeitamente.


How to I get the list of week days for a specific date in android

Question: I'm implementing the material calendar view in android app,the user can select a particular date in the calendar.how do i get the complete list of week days for that particular selected date
for example: if user selects 22 as the date,how do i get the week days in that row from calendar in which 22 is present
Comment: I think you need to customize the calendar as per the requirement.
Comment: i'm using https://github.com/prolificinteractive/material-calendarview as the library,any help or ideas?
Comment: try caldroid library instead. you can easily customise it.
Comment: any code samples,for my requirements,pls help
Comment: You can choose `android-week-view` also. this might help https://android.libhunt.com/project/caldroid/vs/android-week-view
Comment: thanks,for the help[
Answer: Your requirement is unclear. If you want to get the week day for that day, you can use
Calendar.getInstance().set(year, month, day);
int dayOfWeek = Calendar.getInstance().DAY_OF_WEEK;
Ref : https://developer.android.com/reference/java/util/Calendar.html
Comment: not a day of week,i need to get the list of days from the calender row corresponding to the selected dates...for example:suppose that user selects  22 of october,i need to retreive all the remaining week days of thar row in which 22 falls
Comment: you mean for 22 oct 2016, you wanna get {16, 17, ..., 22} like this?
Comment: sure,exactly thats what i need
Comment: you can add and subtract 7 days using calendar function add() and check accordingly to get the desired result
Answer: try this
public String[] getWeekDaySelected(String selectedDateStr) {

        Calendar cal = Calendar.getInstance();

        try {
            Date startDate = sdf.parse(sdf.format(cal.getTime()));
            Date endDate = sdf.parse(selectedDateStr);
            weekDaysCount = Functions.getWeeksBetween(startDate, endDate);

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

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String[] days = new String[7];
        // set the011, 10 - 1, 12);
        String[] arr = selectedDateStr.split("-");
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(arr[2]));
        cal.set(Calendar.MONTH, (Integer.parseInt(arr[1]) - 1));
        cal.set(Calendar.YEAR, Integer.parseInt(arr[0]));
        Calendar first = (Calendar) cal.clone();
        first.add(Calendar.DAY_OF_WEEK, first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
        first.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        // and add six days to the end date
        Calendar last = (Calendar) first.clone();
        last.add(Calendar.DAY_OF_YEAR, 6);

        // print the result
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(df.format(first.getTime()) + " -> " +
                df.format(last.getTime()));

        for (int i = 0; i < 7; i++) {
            days[i] = format.format(first.getTime());
            first.add(Calendar.DAY_OF_MONTH, 1);
        }
        return days;

    }

Comment: i'll try and let u know
Comment: what does this line mean..?what exactly is Functions in the following line ?weekDaysCount = Functions.getWeeksBetween(startDate, endDate);


Infinite perfect field of characteristic p

Question: Given a perfect field of prime characteristic $p$, is it necessarily finite? I believe there must be some counterexample. However, the only infinite field of characteristic $p$ that I know of is $\mathbb{Z}_p(t),$ which is not perfect. Any hints?
Comment: [Algebraic closure.](https://www.encyclopediaofmath.org/index.php/Perfect_field)
Comment: See [this question](https://math.stackexchange.com/questions/2450648/can-we-have-a-perfect-field-of-characteristic-p-with-a-non-archimedean-valuati).
Answer: You can take, for instance, the field $\mathbb F_p(x,x^{1/p},x^{1/p^2},\ldots)$.


Can this function have a minimum or maximum value? If yes, is my function correct?

Question: The problem is the following (Ron Larson's Calculus for AP - 2nd Edition):

My solution to part a). was found by proving that the triangles are similar by the AA property (by comparing Alternate Interior Angles) and that they have a side ratio of "k". My answer to part a). is:
$$
A(x)=\frac{1}{2}dx (1-k)+\frac{1}{2}kdb.
$$
Part b) and c) however seem to indicate that there is a maximum and minimum function, but since the function is a line, there shouldn't be one. Now I am beginning to doubt the correctness of my solution for part a).
If a). is correct, then how do I proceed? If a). is incorrect, what mistake have I made?
Answer: Your answer to part a) is not correct.
The function $A(x)$ should be equal to
$$\frac{dx}{2}+\frac{D(b-x)}{2}$$
where $D$ can be obtained by the similarity of the two triangles
$$k(x)=\frac{D}{d}=\frac{b-x}{x}.$$
Hence, for $x\in (0,b]$, we have
$$A(x)=\frac{dx}{2}+\frac{d(b-x)^2}{2x}$$
which is not linear.
Taking the derivative we find
$$A'(x)=\frac{d}{2}\left(1+\frac{-2(b-x)x-(b-x)^2}{x^2}\right)=\frac{d(2x^2-b^2)}{2x^2}.$$
Hence, in $(0,b]$, $A$ has no the maximum value because $A(x)$ tends to $+\infty$ as $x\to 0^+$, and it attains the minimum value for $x=\frac{b}{\sqrt{2}}$, that is when $|QS|=d(\sqrt{2}-1)$.
Comment: So is my solution to a). wrong, or is it just that the question is based on this form of $A(x)$?
Comment: @rayank97 The ratio $k$ depends on $x$, it is not constant!
Comment: I just realized and was about to edit my comment! Thank you so much!
Comment: @rayank97 Which book is this problem taken from?
Comment: Ron Larson's Calculus for AP - 2nd Edition.


Clone a SelectQuery instance : what am I doing wrong?

Question: I've got a SelectQuery which I've created using db_select(). Then, after I've executed the query, I'm trying to clone it as I need to generate a few more queries based on the original one.
However, for some reason the clones I get from the original query doesn't seem to be clones. This is what I do.
// Create query
$q0 = db_select('track', 't');
$q0->fields('t', array('id','number','title');
[...]
$tracks = $q0->execute()->fetchAll();

// Clear fields on original query.
$fields = &$q0->getFields();
$fields = array();

// Clone original query. The below queries should not have
// any fields set as they just got cleared above.
$q1 = clone $q0;
$q2 = clone $q0;

// This gets weird. The queries $q1 and $q2 should be separate
// clones, independent of each other. So should their fields.
// However, setting fields on $q1 also sets fields on $q2.
$q1->fields('t', array('id'));

// Output : Array ( [id] => Array ( [field] => id [table] => t [alias] => id ) )
print_r($q2);

The fields() function on SelectQuery simply sets an array (see below). I thought that cloning an instance of a class containing an array would copy those arrays by value...and not by reference? Is this a special cloning "feature"?
protected $fields = array();

public function &getFields() {
  return $this->fields;
}

Answer: As you have seen in bug report #1671848 the special getters of these special drupal objects breaks the clone behavior. The problem is that by reference getter are used and this imply hazardous behaviors in PHP internals of returned values.
I think it will be quite very long until this bug get fixed. So one of the solution is to avoid such writings:
$fields = &$q0->getFields();
$fields = array();

This is not the way to empty something in an object. here the & is the fault. after such a write the internal array stored in the object is broken and the object record it as a reference, you've been breaking object encapsulation and bad things happen (sse the bug report). Use a setter, And if there is not setter to do that clone the queries before havinf any field added to the query (so it's empty).
Comment: Thanks for your reply, and for your advise! As a side note : I'm tempted to say that it is more bad design than it is bad usage. After all, it should be the responsibility of the SelectQuery to manage it's internals, and not my responsibility (it is a black box - I don't know what's going on inside it). The documentation even says that the method returns an array as reference for hooks to modify it, and clearing the array would strictly be a modification too. Anyway;  it's how it is and I've got to find another way :-) Have a good day!
Comment: You're right on that.


Views Block Doesn't Show on Views Page

Question: I have a Views Page that displays content from articles matching a particular criteria.  That views page works as expected.
I also have a views block that is supposed to pull related content from the article (think taxonomy, but I am using content types instead).  I have placed this block on all pages (no exclusions) on the right sidebar (Garland).
My content URL paths are set up as such:
example.com/section/page-name

My views page is set up as:
example.com/section

When I access the article directly via .com/section/page-name, the block shows up properly with all of the correct relevant links.  This means I have configured my relationships and context filters correctly.
When I hit my views page and render the content there, the content gets rendered, but the block never shows up. (Just for grins and giggles, I put a test block with some garbage and it shows up every time; views page and article)
I am assuming it is due to passing a filter or something in the URL, but I am just assuming and even if I was right, I have no idea how to pass that info to the block so that it gets rendered.
A point in the right direction here would be greatly appreciated!
Comment: What is the contextual filter you are passing to the block? You need to explain more. getting context into blocks is difficult and you probably will need to look at page manager and panels or a bit of custom coding, like a views hook wherein you pass the context manually.
Comment: Actually, I was able to get it working basing it off what limecake answered..it turned out to be a combination of how my view was configured (path) and how I was rewriting output of the view to generate the links that pass arguments to the view.
Answer: This sounds a little like it's due to your contextual settings. Not sure if you set these based on some info you found on the net, but the settings given online can lead to your view block not rendering content because you are currently looking at that exact content to begin with.
The thought behind this is for example if you load a bunch of articles of the same content-type, that it will not list the same article in that list etc.
What you CAN try is to go into your views block (which is causing trouble) and under "advanced" set a simple "Global Text" under NO VIEW RESULTS BEHAVIOUR saying something like "Cannot load" or similar, to look if the block loads now with that message. If that is the case then the issue is more than likely in your contextual filters or in the field filter settings.
Comment: I was able to get it working by experimenting with this and found that it was a combination of my view and how I was rewriting output generating the link to pass arguments to the view.  Thanks for the point.  However, I still have no idea why this doesn't work with aliases, but works with just node numbers.

Views Block Doesn't Show on Views Page


SVN - how do I commit previous version back into svn?

Question: I am in version 100
svn co -r92 http://www.projectname.svn/trunk projectname
seems to work but how do I get this v92 version committed?
If I do an svn up I get conflicts
If I do svn commit it won't work
Any idea's I'm lost here
Answer: <code>svn up -rHEAD           # be sure you're updated with the latest HEAD
svn merge -rHEAD:92 .   # reverse-merge back to revision 92
svn commit              # commit
</code>
Comment: @Hi-Angel It keeps the full history - you would have all the revisions up to 100, and revision 101 would be the one that brings it back to the same state as revision 92
Comment: Does it keep the last commit *(i.e. the one we want to revert)*? Descriptions are confusing — one says it completely undoing changes, the other ones doesn't mention it.
Answer: you need to reverse merge the revisions on an up to date working copy, then commit. i d recommended against doing that withthe command line client, use a graphical client.
Comment: OK I got it done - weird way. I did an svn del on all files in my working dir. Then did a svn co -r92 http://www.projectname.svn/trunk projectname-v92 made an export from projectname-v92 and added it to my project svn add and svn commit and it works %) I'm happy again
Answer: You need to merge back your changes
 svn merge -r100:92 file.txt
Comment: can I do svn merge with a whole directory? svn merge -r100:92 webroot/ It's not working? nor is the -rHead solution mentioned earlier


Instance of Mean Value Theorem

Question: What's an elementary proof that there exists $c\in (a, b)$ with
$$e^b-e^a=(b-a)e^c$$
without calculus, just using the standard properties of the exponential function?
*By calculus I mean derivatives and integrals. The intermediate value theorem is fine, the mean value theorem is not.
**Either elementary definition of the exponential function is fine, but I suspect that continuity, monotonicity and $e^{a+b}=e^a e^b$, $(e^{a})^b=e^{ab}$ should be more than enough to do this.
Comment: How do you define the exponential function?
Comment: $exp(x)=\lim_n (1+\frac{x}{n})^n=\sum_k\frac{x^k}{k!}$, whatever you like.
Comment: If you let $b \to a$, then you get $De^x =e^x$. I doubt that you can prove the MVT for the exponential without any use of derivatives.
Comment: So the above result would indeed imply that $De^x=e^x$, but why is that a reason to believe that derivatives are needed to prove it?
Answer: Just take $$c=\ln\left(\frac{e^b-e^a}{b-a}\right).$$
Edit: $a<c\iff e^a<\frac{e^b-e^a}{b-a}\iff b-a+1<e^{b-a}$. Now $x:=b-a$ is positive. Hence it is obvious that $x+1<e^x=1+x+x^2/2+\cdots$.
Edit$^2$: To show that $c<b$ yields to show $1<e^{b-a}(b-a+1)$. Now clearly $1<xe^x+e^x$ since $e^x>1$ for positive $x$.
Comment: Why does that lie between $a$ and $b$?
Comment: Because surely $x^2/2!+x^3/3!+x^4/4!+\cdots$ is positive if $x$ is positive.
Comment: How can you have taylor series without mean value theorem and derivative?
Comment: By definition? I don't know, but it is proposed by Mathgemini.
Comment: Convinced, if we know that $e^x>1+x$ for all $x>0$ - but how do you deduce this from the series definition of $exp$?
Comment: Silly of me^^ Accepted.
Comment: But you also have to show c<b...
Comment: I think you need $1<e^{b-a}(1-(b-a))$, to show c<b. See my submitted answer (written before I noticed you elaborate on your original answer).
Comment: Can I accept two answers? It's only fair.
Answer: To use the intermediate value theorem, let $f(x)=e^x-\frac{e^b-e^a}{b-a}$. It is sufficient to check that $f(a)<0$ and $f(b)>0$.
Simple rearrangement shows $f(a)=\frac{e^a}{b-a}((b-a+1)-e^{b-a})$. Since $b>a$, this is negative if $e^{b-a}>(b-a)+1$. This is clear from both the series of $e^x$, as b-a>0, and all terms are positive so truncating to 2 terms only reduces the value.
Similarly, we have $f(b)=\frac{e^a}{b-a}((b-a-1)e^{b-a}+1)$. This is positive if  $e^{b-a}>\frac{1}{1-(b-a)}$. Setting $y=b-a$, this is clear from the series for $e^y$ and the series for $\frac{1}{1-y}=1+y+y^2+...$ (sum of a geometric series).
Answer: Something close to what you want.
Let $a, b \in \mathbb{R}$ and let $a < b$. If $f: x \mapsto e^{x} - \frac{e^{b}-e^{a}}{b-a}: \mathbb{R} \to \mathbb{R}$, then $f$ is continuous. But $f(x) > 0$ for $x \to \infty$ and $f(x) < 0$ for $x \to -\infty$, so by Bolzano's theorem (a specialized version of the intermediate value theorem for continuous functions) there is some $c \in \mathbb{R}$ such that
$$
e^{c} = \frac{e^{b} - e^{a}}{b-a}.
$$
But I suspect there is little chance to locate such a point within $]a,b[$ without calculus...
Answer: $e^{x}$ is a convex increasing function and $\frac{d}{dx}e^x=e^x$, hence if $a<b$
$$ e^{a}<\frac{e^b-e^a}{b-a}<e^b \tag{1}$$
holds, then $\frac{e^b-e^a}{b-a}=e^{\xi}$ for some $\xi\in(a,b)$ by continuity and monotonicity.

Instance of Mean Value Theorem


Load set through properties file

Question: Is it possible to load a set, which is initialised in my Spring context, with entries configured in a properties file? If so, how?
The loading of the properties file should as well happen in the Spring context.
Answer: With a PropertyOverrideConfigurer you can initialise an array, a list or a map. That's sufficient for me.
<code>myBean.myList[0]=Michael
myBean.myList[1]=J
myBean.myList[2]=Fox
</code>

Load set through properties file


Criar coluna categórica a partir de outra coluna usando listas

Question: Olá, estou tentando criar uma nova coluna no pandas a partir de uma coluna existente. Essa coluna contém nome de partidos políticos. Na nova coluna eu quero classificar a ideologia do partido. Para isso criei 3 listas contendo a orientação. Mas não estou conseguindo aplicar isso no pandas. Minha nova coluna deve retornar uma string com a orientação do partido: 'esquerda', ' centro', 'direita'.
esquerda = ['PSOL', 'PT', 'REDE', 'PCdoB', 'PSB', 'PV', 'PDT']
centro = ['SOLIDARIEDADE', 'CIDADANIA', 'AVANTE', 'PSD', 'PROS', 'MDB', 'PSDB', 'PODE']
direita = ['REPUBLICANOS', 'PP', 'PTB', 'UNIÃO', 'PATRIOTA', 'PSC', 'PL', 'NOVO']

# dentre algumas formas eu tentei esse método, mas
# retorna erro
df_3['ideologia'] = np.where(df_3['partido'] in esquerda, 'esquerda', \
                         df_3['partido'] in centro, 'centro', \
                        df_3['partido'] in direita, 'direita')

Me retorna esse erro: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Meu dataframe tem essa cara aqui: (não sei bem como representar ele na postagem)
    nome              estado        partido
0   abou anni         São Paulo     UNIÃO
1   acacio favacho    Amapá         MDB
2   adolfo viana      Bahia         PSDB
3   adriana ventura   São Paulo     NOVO
4   adriano do baldy  Goiás         PP

Answer: Veja uma forma de fazer isto utilizando a estrutura que você definiu anteriormente, porém ao invés de arrays de cada partido eu defino um dicionário que contém todos:
partidos = {
  "esquerda": ['PSOL', 'PT', 'REDE', 'PCdoB', 'PSB', 'PV', 'PDT'],
  "centro": ['SOLIDARIEDADE', 'CIDADANIA', 'AVANTE', 'PSD', 'PROS', 'MDB', 'PSDB', 'PODE'],
  "direita": ['REPUBLICANOS', 'PP', 'PTB', 'UNIÃO', 'PATRIOTA', 'PSC', 'PL', 'NOVO']
}

def defineIdeologia(partido):
  for k in partidos:
    if partido in partidos[k]:
      return k

df_3["ideologia"] = df_3["partido"].apply(defineIdeologia)

Answer: consegui resolver o problema criando listas e iterando.
b = list(df_3['partido'])
ideologia = []
for x in b:
    if x in esquerda:
        #print('esquerda')
        ideologia.append('esquerda')
    elif x in direita:
        #print('direita')
        ideologia.append('direita')
    else:
        ideologia.append('centro')

df_3['ideologia'] = ideologia

Mas gostaria de saber se tem algum modo mais simples para fazer isso. Obrigado


How to force rvm to use older versions of llvm to install rubinius on arch?

Question: I have been having trouble installing rubinius on arch through rvm. Rubinius requires llvm version of 3.0-3.5 however Arch provides 3.6 by default under the package name llvm and I can install llvm35 to provide llvm 3.5. How do I force rvm to use llvm35 instead of using llvm?
Answer: ./configure --llvm-config=/path/to/llvm-config

I don't have Arch installed, so I don't know where the llvm35 package puts llvm-config. Hopefully, this gives you enough of a hint to continue; if not, please let me know and I'll see what I can do.


How to make Linux VNC server listen on local IP instead of just loopback?

Question: I know how to specify a listening port of VNC server under Linux, but what puzzles me is that I can not find a way to specify a VNC listening IP.
When started VNC server under CentOS 5.6, I found its process "Xvnc" is listening on 127.0.0.1:5901. Maybe this is why I always failed to get in when I use any XNC client. I do not know why it listened on "lo" network interface but not on "eth0".
Answer: It sounds like your vncserver is started with localhost parameter:
# vncserver -h

usage: vncserver [:<number>] [-nohttpd] [-name <desktop-name>] [-depth <depth>]
                 [-geometry <width>x<height>]
                 [-pixelformat rgbNNN|bgrNNN]
                 <Xvnc-options>...

# Xvnc -h
Unrecognized option: -h
...
Global Parameters:
  localhost      - Only allow connections from localhost (default=0)

You should probably check the /etc/sysconfig/vncservers and the init script /etc/init.d/vncserver.
If you want to bind to specific IP, do it with iptables or take a look at this.
Comment: Thanks.That is the "-localhost" configuration in /etc/sysconfig/vncservers:                                     VNCSERVERARGS[3]="-geometry 1280x768 -nolisten tcp -localhost
Comment: The link is broken.
Answer: For TigerVNC, as quanta already mentioned, try to utilize Xvnc-option -interface like so: vncserver <your options here> -interface <ip address>. Also -localhost option might be the cause as well.
Xvnc -help:

  interface      - listen on the specified network address (default=all)
  localhost      - Only allow connections from localhost (default=0)

vncserver -help:

    [-localhost [yes|no]]
      if enabled, VNC will only accept connections from localhost.

Useful links:
https://tigervnc.org/doc/Xvnc.html
https://linux.die.net/man/1/xvnc
Answer: There are different flavors of VNC, but I will proceed with describing setup of TightVNC.
First, verify you are using Xfce4.  I use XUbuntu 21.10, in this case, which defaults to XFCE. Check for it with this command:
sudo apt list --installed | grep xfce4

NOTE: I had trouble getting this config to work without xfce4 on the standard Ubuntu.
Next install TightVNC like so:
sudo apt upgrade & sudo apt update
sudo apt install xfce4-goodies
sudo apt install tightvncserver ssh openssl

Then run:
vncpassword
echo -e '#!/bin/bash \nxrdb $HOME/.Xresources \nstartxfce4 & \n'

At this point you could run the vncserver command to start it up, but instead we want to run as a service.  So, create this service file, but fix the 4 instances of sammy username in this file to match your system user/group:
#/etc/systemd/system/vncserver@.service
[Unit]
Description=Start TightVNC server at startup
After=syslog.target network.target

[Service]
Type=forking
User=sammy
Group=sammy
WorkingDirectory=/home/sammy

PIDFile=/home/sammy/.vnc/%H:%i.pid
ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :%i
ExecStop=/usr/bin/vncserver -kill :%i

[Install]
WantedBy=multi-user.target

In that config, I suppressed the use of the -localhost argument so that the VNC service will listen , and allow, on port 5901 from all remote hosts.
Then run these commands once:
sudo systemctl daemon-reload
sudo systemctl enable email@example.com
sudo vncserver -kill :1
sudo systemctl start vncserver@1
sudo systemctl status vncserver@1

Now, from a remote computer, connect to this service on port 5901 from a VNC client on another computer.


Erro ao chamar método no code behind

Question: using System;
using Treinamento.DTO.Global;
using Treinamento.BLL;
namespace Treinamento.WEB.Tabelas.cidade
{
public partial class Listar : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = CidadeBLL.Instance.Listar();
        GridView1.DataBind();

        if (GridView1.Rows.Count == 0)
            LabelMensagem.Visible = true;
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs
    e)
    {

    }
  }
}

Severity  Code    Description Project File    Line    Suppression State
  Error   CS1061  'object' does not contain a definition for 'Listar' and no extension method 'Listar' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)   Treinamento.WEB C:\Users\danilo.costa\Desktop\TreinamentoNET\source\Treinamento.WEB\Tabelas\cidade\Listar.aspx.cs   10  Active
Answer: CidadeBLL.Instancenão possui o método Listar() ou não foi inicializado da forma correta.

Erro ao chamar método no code behind


How to inherit the output of toString() and to append additional text?

Question: So... I have a parent class which overrides default toString() method and another class which inherits (extends) the first class.
Is there a way to override toString() method of the second class so it just to append text next to the output of toString() method of its parental class?
 This is the code of the parental class:@Override
    public String toString(){
    return String.format("First Name: %s%nLast Name: %s", getFirstName(), getLastName());
    }

I would like just to append Facility number: %s at the end of the string.
Comment: Something like `public String toString(){return super.toString() + "additonal part";}`?
Comment: Yes. Post your code.
Comment: Thank you. It works :) I guessed that it will be something similar to the constructor invocation with "super" but I didn't know how to write it.
Answer: You can get use super before toString() method. It let you use method from base class. The word this give you method from class which is extended by base class.


jquery how to remove a column from a table

Question: I need to click in a Close img, and remove all the column where the img is located.
I'm trying to do something like this:
            var colnum = $(this).closest("td").prevAll("td").html();

    $(this).closest("table").find("tr td:eq(" + colnum + ")").remove();

but, its not working.
EDIT: GUYS, SORRY FOR THE FIRST POST, I WAS KIND A HURRY TO OPEN THE QUESTION.
I EDIT EVERYTHING. TAKE A LOOK IN THE DEMO
the html demo: New Demo
if you guys see the red stuffs in the table, that I need to remove when click que "CLOSE".
Remove the column where I'm clicking.
ps.: guys, the red class was just to you guys see where need to be the close event.
Comment: There are a lot of errors in the code, the handler `)}` should end in `});`.  Also HTML attributes should be wrapped in double quotes `"` instead of single quotes.  Also, the colnum variable you are assigning isn't getting the column number.  Use `$(this).index();` instead.  Using tables isn't a bad thing if you are displaying tabular data but I'm not sure nested tables are appropriate and removing columns completely is kind of a code smell as well... I don't have any truly helpful advice rather than start fixing all your errors first before moving forward on this one.
Comment: Nested Tables? Ouch. This would be a lot easier if you weren't removing columns of nested columns.
Comment: John Strickler: sry , i "paste" the code in jsfiddle missing somthing's . in my source its ok.
Comment: The html its ok now, i edit all the stuffs in the demo, please, take a look.
Answer: In your example demo, what should actually close?...  I modified it slightly and the close column disappears, but I am unsure what else you are expecting to be removed.
See here:  http://jsfiddle.net/gfosco/TdCYy/24/
The issue is being inside a nested table... You want to remove the column from the cell parent tables parent table.
Updated example here:
http://jsfiddle.net/gfosco/TdCYy/37/
Comment: The html its ok now, i edit all the stuffs in the demo, please, take a look
Comment: @ric_bfa Updated example to working order... The issue is being 2 tables deep.  Let me know if you have any issues.
Comment: @Fosco: yes, its work, but the numbers of columms is dinamic, i have a input, in the input i put how many columms will appear, and each columm i add a close buttom, to remove the columm that just has beem add, exp: http://jsfiddle.net/5AFJn/19/ i can have alost of columms.
Comment: @ric_bfa you switched to ID's and you can't have 2 elements with the same ID..   It works fine with multiple columns using a class selector:  http://jsfiddle.net/gfosco/5AFJn/20/
Comment: @Fosco: edit, was ID , change to class. take a look http://jsfiddle.net/5AFJn/22/
Comment: @Fosco: yes, just got that. will check.
Comment: @ric_bfa why did you update the `var idx` to +2?  It should stay +1 always.. it's to switch from a 0 based index to a 1 based index.
Comment: @Fosco: i was just testing, beacause in the my official code, one of the columms its not beeing removed. dont know why
Comment: @ric_bfa well if you can post relevant code I can look, but you can see that I've provided a valid solution to your request.
Comment: @Fosco: yes, check this out, i was just organazing all the stuffs http://jsfiddle.net/QpuT5/17/
Comment: @ric_bfa it's due to all of the crazy colspan action you have going on... I really don't know if I'm up for digging through all of it to find a perfect solution.  There's a better way to manage these column headers, maybe I'll work on that instead...
Comment: @ric_bfa check it out: http://jsfiddle.net/gfosco/QpuT5/21/  Since the rows AFTER the header row had multiple columns, I first remove the right column from all rows after row #1, then do the previous remove.
Comment: @Fosco: perfect man, congratulation! will try to clean this html crazy stuffs. thnks again!
Answer: You should be able to use the nth-child selector to get the cells in nth column, something like this:
$(this).closest("table").find("tr td:nth-child(" + colnum + ")").remove();

Answer: Check out this link, I have edited your demo http://jsfiddle.net/TdCYy/39/
This is the HTML unchanged, except for the class first-row added to the first red row:

        Somthing 1
        Somthing 2
        Somthing 3

                        Something
                        Close

                    Another
                    Another 1

        Result
        Result
        Result
        Result

        Result
        Result
        Result
        Result

        Result
        Result
        Result
        Result

        Result
        Result
        Result
        Result

CSS is untouched.
Javascript should be (this works):
$(".img_romove_columm").click(function(){
    // Hide the first row that has the close button, and also hide the row right after it (another, another1)
    $('tr.first-row, tr.first-row + tr').hide();
    // Hide everything that has the red class (result, result, result, result, )
    $('td.red').hide();
});

Is this what you're looking for?
Comment: forget the class "red", was just to see where the event click will rappend, my problem is, i need to close all the columm without any class or id especification
Answer: Here is an example I came up with. simply apply the same class (red) to all of the elements to want to disappear, including the nested table. Then you can call
    $('.red').hide();

FIDDLE http://jsfiddle.net/Jaybles/TdCYy/42/
Comment: the red class that i put in the demo was just to see where the click event will apperar :)
Comment: Yes, I know. It can be any class. It can even be a class that's not in your CSS. It's just to identify a group of objects that you want to appear. `red` can just as easily be `closable` or anything else. On a side note, don't expect to get a lot of help if you go around down-voting every answer that's not exactly what you want. Two of us on this page gave you two working examples, and because they have the word `red` in them, they were downvoted. Nowhere in your question did you specify that this had to be done without classes. I am down-voting your question, since it was not properly asked.


Is there a loss function when estimating a model using MCMC?

Question: I am trying to understand how fitting a model using MCMC works. Is there a loss function that is optimized?
Or is it simply a case of more draws from the distribution amount to a more complete description of the posterior and therefore more accurate parameters?
In particular I am referring to how a BSTS time series model is fitted using MCMC draws as described in Scott and Varian "Predicting the Present with Bayesian Structural Time Series", 2013.
In that paper a state space model of a time series is described:
$y_t = Z_t^T \alpha_t + \epsilon_t $.
$\alpha_{t+1} = T_t \alpha_t + R_t\eta_t$
Let
$\theta = (Z, T, R, \epsilon, \eta)$
and
$\textbf{y} = y_1,....y_n$ their time series data.
They then use MCMC to simulate the posterior distribution of the parameters of the model given their data $p(\theta|\textbf{y})$ - and presumably (they don't actually states this, I am assuming) they select $\theta$ that maximizes $p(\theta|\textbf{y})$.
In R the BSTS model takes a number of MCMC draws as an input parameter - and I am trying to figure how to choose that number.
If it is the second case (more draws = better simulation of the distribution), how do we decided the number of iterations and how do we avoid overfitting?
Comment: You are confusing inference (estimation) and simulation (MCMC), precision in the estimation and precision of the Monte Carlo approximation.
Comment: @Alex Bayesian estimation has notable links to loss functions. You should learn *how* $\hat{\theta}$ is taken from $p(\theta|y)$. In minimax theory, different estimators optimize different losses: the median with L1 loss, the mean with L2 loss and the mode with Linf loss: all of these are used in practice. The use of MCMC is just to numerically calculate the shape of $p(\theta|y)$: we can assume it has no bearing on the actual "loss" function that is minimized by the estimator $\hat{\theta} = f(p(\theta|y))$.
Comment: Your question has reopened. @Xi'an's comment still stands. 'Train the model' is estimation (it certainly will be in this instance).
Comment: Sorry, I don't see how that changes the point being made about confusing precision in the estimation and precision of the Monte Carlo approximation.
Comment: This is clearer but there is no such thing as overfitting associated with an MCMC chain. The more the better.
Comment: @AdamO - Ok - but the MCMC must be converging towards something? Otherwise why do specify a number of iterations?
Comment: @Alex No MCMC is not converging to anything. It is sampling from $p(\theta|y)$. Our estimate of $\widehat{p(\theta|y)}$ gets better with more samples, so there is a functional convergence. This forms the shape of the posterior. That shape in fact tells us very little. To report something useful, we reduce this shape into a statistic. What I am saying is only that that statistic has some link with a loss function. In this way, the relation between MCMC and loss-functions is just incidental. We could still do the same thing when $p(\theta|y)$ has a closed form solution.
Comment: Your question is too broad; MCMC may be used in various ways (for example, it encompasses optimization via simulated annealing). Are you talking about fitting a Bayesian model? Please give more context.
Comment: @Glen_b I've added details.
Comment: @Xi'an I'm not talking about inference - the paper I'm reading specifically states that they are using MCMC simulation to train their model.
Comment: @Glen_b "The model is fit using an MCMC algorithm" are the original authors words not mine.
Answer: For Bayesian estimation, the point of MCMC is only to simulate data from--and thereby obtain an estimate of--the posterior. In general, MCMC (Markov Chain Monte Carlo) only refers to generating realizations or simulating data from a probability model. This is necessary for Bayesian analyses where the posterior if often not solvable in a closed form. Gibbs Sampling is perhaps the most popular technique for obtaining a posterior and it happens to be MCMC, but there are other approaches.
These simulation methods are imprecise, but we do not call this loss (in the same way that a blurry image could be called "lossy"). We call this precision. Increasing the number of iterations of Gibbs sampling will generally increase the precision with which the density of the posterior can be estimated. The lack of precision is called MCMC error.
Rather, loss is a general concept of Bayesian estimation. In practice, we make no distinction between posteriors which are estimated from MCMC or posteriors which are known in exact form when we discuss the loss of estimators. The risk (expected loss) is calculated the same way. Optimal Bayes estimators minimize risk.


Simple homework question about normally distributed variables

Question: The question states:

Consider a set of random variables $X_i$, where $i=1,...n$. Each $X_i$ is
  normally distributed with mean $0$ and variance $1$, i.e. $X_i$ are $\mathcal N(0,1)$.
  What is the mean and the variance of the random variable $Y$, where
  $Y=X_1+...+X_n$.

How do I do this?
Comment: https://www.google.be/#output=search&sclient=psy-ab&q=sum+of+normal+distributions&oq=sum+of+n&gs_l=hp.3.0.0l4.1131.4145.0.622.214.171.124.220.127.116.11.739.3j2j1.6.0...0.0...1c.1.12.psy-ab.IgJqdx9M6MI&pbx=1&bav=on.2,or.r_qf.&bvm=bv.45960087,d.d2k&fp=e3c46b2e87b6b124&biw=1366&bih=640
Comment: So Y is my sum of normally distributed RVs and I should find the mean and variance of that, correct?
Comment: If you can't think of an analytic solution, you could try simulating it. That may spur you to find the analytic solution.
Answer: Regarded as a question in probability theory, the answer to this question is that $$E[Y]=E[X_1+X_2+\cdots +X_n] = E[X_1] + E[X_2]+\cdots + E[X_n]$$
via a result known as the linearity of expectation, and since the random variables
all have zero mean in this particular instance, $E[Y]=0$.  On the other hand,

the
  information given is insufficient to determine the variance of $Y$.

The variance of $Y$ is
$$\operatorname{var}(Y) = \sum_{i=1}^n \operatorname{var}(X_i)
+ 2 \sum_{i=1}^{n-1}\sum_{j=i+1}^n\operatorname{cov}(X_i,X_j)$$
and so unless one knows (or makes assumptions about) the covariances, the variance
of $Y$ cannot be determined. One common assumption is that the $X_i$ are
independent random variables in which case the variance of $Y$ is just the
sum of the variances. The weaker condition that the $X_i$ are uncorrelated
random variables also leads to the same result, which in this instance is
that $\operatorname{var}(Y)=n$.
The answers are different if one is talking about the sample mean and
the sample variance of $n$ samples from a standard normal distribution.
Comment: Are you sure the variance cannot be found? I was just looking on the wiki page for 'Sum of normally distributed random variables' and it said "This means that the sum of two independent normally distributed random variables is normal, with its mean being the sum of the two means, and its variance being the sum of the two variances". So can we not just add the variances together in my example?
Comment: Yes, I am sure that the variance cannot be found _from the information in the_ **current** _version of your question_. Note that the Wikipedia page that you refer to _specifically_ says that the two random variables are **independent** which word is nowhere to be found in your question. In my answer, I _did_ point out that if one assumes that the random variables are _independent_, then the variances can be added up. Your $Y \sim N(0,n)$, but normality is irrelevant to the issue of the variances adding. Variances add if the variables are uncorrelated, including as a special case, independent.
Comment: Ah, I see your point. I think I'll write above that I'm assuming the RVs are independent otherwise this cannot be done. I don't think the professor would be trying to throw us for a loop like this. Thank you!
Answer: Working off Peter Flom's suggestion, look at this R code:
x <- as.data.frame(matrix(rnorm(50000,0,1), nr = 5000, nc = 10))
x$y <- x$V1 + x$V2 + x$V3 + x$V4 + x$V5 + x$V6 + x$V7 + x$V8 + x$V9 + x$V10

We generate 10 variables (V1 through V10), each with a mean of 0 and a standard deviation of 1.  Y is constructed to be the sum of the ten variables for each observation.  You can then run:
colMeans(x)
diag(var(x))

And those results should give you some insight about what to expect.
Then, look at this Wikipedia entry (the formula for Z specifically) and see if your insights match theirs!


É possível prevenir injeção de recursos e requisições externas em uma página web?

Question: Supondo que exista alguma biblioteca da qual injete elementos de fontes externas como  ou  e javascript: em eventos (por exemplo )

'unsafe-eval'
Permite o uso da função eval()

Permitir blob e acesso ao arquivos de sistema
Muitos sistemas necessitam do uso de upload e criação de urls dinamicas, mas o default-src 'self' pode impedir isto, então use:
Content-Security-Policy: default-src 'self'; img-src 'self' data: blob: filesystem:; media-src mediastream:

Fonte: https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
PHP
Para usar isto com PHP é necessário usar o header:
<?php

header('Content-Security-Policy: default-src \'self\'');

Apache e .htaccess
Para usar o com Apache, você pode usar o httpd.conf ou o .htaccess e o mod_headers:
<IfModule mod_headers.c>
    Header set Content-Security-Policy "default-src 'self'"
</IfModule>

IIS
Em servidores IIS
<set name="CONTENT_SECURITY_POLICY" value="default-src 'self'">

CSharp (System.Web)
Com c# você pode acessar o HttpContext e setar em um variável chamada context:
HttpResponse HS = context.Response;

HS.AddHeader("Content-Security-Policy", "default-src 'self'");

Python
Com django:
def main(request):
    response = HttpResponse()
    reponse["Content-Security-Policy"] = "default-src 'self'"

Com flask (neste caso define na rota /):
@app.route("/")
def home():
    resp = flask.Response("foo")
    resp.headers['Content-Security-Policy'] = 'default-src \'self\''
    return resp

Comment: +1 Não conhecia esse CSP, mas já vejo que promete bastante. Eu sempre quis que os *browsers* implementassem algo como o [`hash-source`](http://www.w3.org/TR/CSP/#source-list-valid-hashes) no CSP nível 2, tomara que isso se popularize logo (no momento, [só o Chrome suporta](http://caniuse.com/#feat=contentsecuritypolicy2)). Sempre fiquei com um pé atrás com os CDNs justamente por isso (vai que um CDN qualquer é hackeado e substituem o jQuery por um arquivo malicioso, quantos sites no mundo seriam afetados?). Mas se for possível estabelecer um hash, então já não há mais problema.


Função para resumir string no php

Question: Bom montei a seguinte função para resumir uma string no php.
function resumo($string,$chars) {
if (strlen($string) > $chars) {
    while (substr($string, $chars, 1) <> ' ' && ($chars < strlen($string))) {
        $chars++;
    }
}
return substr($string, 0, $chars);
}

echo resumo("bla bla bla bla bla", 4);

Bom o problema que estou tendo é o seguinte. Eu informa a quantidade de no máximo 4 letras e a função esta me retornando mais letras.
E sempre que a sting for resumida que quero adicionar (...) três pontos.
Se eu informar uma string que não for preciso resumir não é necessário adicionar os três pontos.
Comment: Não entendi pq precisa daquele `while`, não seria só retornar o `substr()` ?
Comment: Isso facilita muito as coisas https://pt.stackoverflow.com/a/169912/3635
Answer: function resumo($string, $chars) {
    if (strlen($string) > $chars)
        return substr($string, 0, $chars).'...';
    else
        return $string;
}

echo resumo("abcde", 4);

Saída

abcd...

Você também pode utilizar a função mb_strimwidth, você pode usa-lá desta forma:
function resumo($string, $chars) {
    return mb_strimwidth($string, 0, $chars + 3, "...");
}

Conforme a resposta do @Wallace
Comment: Curioso que a saída resumida ficou maior que a entrada xD kkk
Comment: @HugoBorges isto não vai funcionar bem com unicode, ainda recomendo que teste `mb_strimwidth`, como na resposta do Wallace: https://pt.stackoverflow.com/a/169912/3635
Comment: @HugoBorges exatamente isso que a função faz, se passar do limite ela adiciona os tres pontos, caso contrário não. Não é necessário postar uma resposta nova e nem é mais possivel, pois a pergunta já é marcada como dup e a resposta do Wallace lhe resolve o problema, se quiser vote up na resposta do Wallace para agradecer-lhe sobre a colaboração com a dica. ;)
Comment: @RobertoFagundes editado, recomendo ainda que ajuste o código de limitação fazendo a conta de caracteres, mas ae é opcional.
Comment: kkkk bem isso, para evitar isso poderia somar a variável `char` com 2. Evitaria esse problema
Comment: Aliás, sua resposta foi sinalizada como qualidade baixa em relação a tamanho/conteúdo. Eu recomendo que além do código você coloque alguma explicação sobre o mesmo.
Comment: @RobertoFagundes era isso mesmo, obrigado.
Comment: @GuilhermeNascimento o problema é, como vou fazer para aparecer os pontos apenas se tiver que abreviar? Tem como você posta um resposta ai eu ja marco ele como solucionada.
Comment: Alterei a resposta adicionando um exemplo
Comment: Obrigado, foi corrigido
Comment: Não entendi o que você quis dizer
Comment: @RobertoFagundes não entendeu o que eu disse sobre "editado" ou sobre como usar a função?
Comment: Não entendi este comentário: `recomendo ainda que ajuste o código de limitação fazendo a conta de caracteres, mas ae é opcional.`.
Comment: @GuilhermeNascimento ficou assim a função. `function resumo($string, $chars) {

 // Calcula os pontos
 $chars += 3;

 // Retorno
 return mb_strimwidth($string, 0, $chars, "...");
}`
Comment: @HugoBorges não precisa, o teu código esta correto, é que eu não tinha entendido direito, mas pelo que testei esta ok ;)
Answer: Pode simplificar sua função apenas com substr() ou mb_substr() como retorno e mudar a assinatura da função para adicionar os ... caso nenhum argumento seja passado:
function resumo($string, $chars=0) {
    if(!mb_strlen($string)) return '';
    return  $chars == 0 ? $string : substr($string, 0, $chars)  .'...';
}

echo resumo("bla bla bla bla bla", 4); //Output = "bla ..."
echo resumo("bla bla bla bla bla");    //Output = "bla bla bla bla bla"
echo resumo("bl", 5);                  //Output = "bl..."

Veja funcionando no repl.it.
Comment: era isso mesmo, obrigado.
Comment: Só tem um detalhe, os (...) só pode aparecer se a sting for resumida.

Função para resumir string no php


Minimum degree of $T_n(x)$ in knowing that $\mid f(\pi) - T_n(\pi) \mid \leq \frac{1}{100}$

Question: I got the taylor expansion of $f(x) = \
\int_{\frac{\pi}{2}}^{x} \frac{\cos(t)}{t - \frac{\pi}{2}}dt$  around $a=\frac{\pi}{2}$ which is
$$T(x) = \sum_{n=0}^\infty(-1)^{n+1} \frac{1}{(2n+1)!(2n+1)}(x-\frac{\pi}{2})^{2n+1}.$$
Let $T_n(x)$ the Taylor polynomial of degree $n$ of $f$ around $a=\frac{\pi}{2}$. What is the minimum $n$ of $T_n(x)$ so that $$\mid f(\pi) - T_n(\pi) \mid \leq \frac{1}{100}?$$ In fact, the answer is $n=1$ and $T_1(x) = -(x-\frac{\pi}{2})$, but I can't explain why rigorously.
Please let me know if the question is unclear.
Answer: You have that
$$
f(\pi) = \sum_{n=0}^\infty (-1)^{n+1} a_n,
\qquad
a_n := \frac{1}{(2n+1)! (2n+1)}\, \left(\frac{\pi}{2}\right)^{2n+1}\,.
$$
You have that the series is alternating, and $(a_n)$ is a sequence of positive numbers converging motononically to $0$.
If we denote by $s_n := \sum_{k=0}^n (-1)^{n+1} a_n$ the $n$-th partial sum of the series, you have the following error estimate:
$$
|f(\pi) - s_n| \leq a_{n+1}
$$
(see the proof of the Leibniz criterion of convergence).
You can now check in a moment that, for $n=1$, the error is bounded by
$$
a_2 = \frac{1}{7! 7} \left(\frac{\pi}{2}\right)^{7} \simeq 0.67 \cdot 10^{-3} < \frac{1}{100}\,.
$$


Is c lib a static in c++ program?

Question: I have a c lib, algo.lib, which I need to call in my c++ program. I realise that the variables in algo.lib is static, which creates problem for my c++ program, when I call algo.lib multiple times, or use threads to call algo.lib concurrently.
For example, in algo.lib, there is a int a which is initiall set to 0. When I call algo.lib the first time, a will be set to 1000. But when I call algo.lib another time, I want the variables in algo.lib to be in the initial state, that is, a = 0 and not a = 1000.
Is it possible to make algo.lib to become object-oriented, so that when I call its function, it is created as an object and is set to its initial state? And after finish running algo.lib, this object is destroyed?
Answer: Yes, it is possible. If you rewrite it. If you only have the binary - then you cannot change this behavior. You can solve it by creating a separate executable that will do what you want with it and then exit, and pass the results back to the main program through some IPC. Basically - wrap it with your own implementation that will effectively initialize the library for each separate call.
Comment: rewriting will be very tedious and time-consuming, as this algo.lib belongs to someone else. Thanks for your suggestion, I think I will then compile algo.lib as an excutable instead, and call it in my c++ program, maybe using popen()
Comment: No need. Just write your own API which will initialise the existing library correctly, and/or wrap its functions in your own. Call the new API instead of the old one. `popen()` is overkill for this.
Comment: @spraff, i'm not sure you're right. The OP has a global variable in the library, that gets changed on each call, and apparently it cannot be reset once loaded, and is inaccessible from outside. If that's the case - just wrapping the API's won't help.

Is c lib a static in c++ program?


cutting $2$ rods to $2$ pieces probability that $3$ chosen pieces form a triangle

Question: We have two rods of length $a$ and $b$ ($b> a$) we randomly cut each rod to $2$ pieces. Then we choose $3$ pieces of $4$ pieces. What is the probability that these pieces form a triangle?
I think if we consider first piece if a as $x$ then $x$ has uniform distribution $(0,a)$ and the other piece has length of $a-x$. For the other rod we consider one piece as y and the other as $b-y$. We have $4$ different combinations for choosing pieces . I think I have to consider each combination, then find the probability of making triangle using triangle inequality but I don't know how to apply it. Also I think I don't have to calculate for each of $4$ states (because of symmetry).
Comment: Graphing is the way.
Comment: I think that the only way in which you cannot form a triangle is that all three selected pieces are of the same length
Comment: Related: https://math.stackexchange.com/q/676
Answer: WLOG, assume $a=1$.
There are two cases: the left out piece corresponds to the long rod (length $b$), or it corresponds to the short rod (length $1$). Both cases are equiprobable.
Denote by $x \in [0,1]$ the cutting position for the short rod, $y \in [0,b]$ the cutting position for the long rod.
Lets compute the probability of success (a triangle can be formed) assuming first case.
The lengths of the pieces are then $a=x$, $b=1-x$, $c=y$. The triangle inequalities ($a<b+c$, $b<a+c$, $c<a+b$) give the conditions
$$[y<1], [y>2x-1], [y>1-2x] $$
Graphing this on the $x,y$ plane we get a triangle of area $1/2$, over the total zone (of uniform probability) of size $b$. Hence the probability is $$p=\frac{1}{2b}$$
As similiar calculation for the other case gives the same result.
In conclusion, in general:
$$p=\frac{\min(a,b)}{2 \max(a,b)}$$
Comment: The scale should be irrelevant $(a=3,b=5)$ should give the same result that  $(a=30,b=50)$ . Hence we can assume $a=1$
Comment: I didn't understand the last part. How did you conclude that p= 1/(2b)?  when I draw graph for " a "(not 1) the area is a^2/2 for the first case and b^2/2 for the next. How did you assume a= 1?
Comment: so I think the answer should be a/(2b) for the first case. But b/(2a) for second case


Maximal-Orthogonal Convex Hull (or Maximal-Rectilinear Convex Hull)

Question: In my research, I have come across a this paper from the Computational Geometry field and I am not able to understand the concept of Maximal-Rectilinear Convex Hull of a given point set in plane.
In the attached image, I have tried to explain my problem.
Edit 1 :
In sketch 4 of attached image, note that the set contains the inside of the rectangle as well and not just the periphery.
Appreciate any help in clearing my confusion.
Comment: The link on the paper is broken.
Comment: its working now. Thanks for pointing out.
Answer: The maximal orthogonal convex hull is what is left of the plane when you take away all set-free quadrants, that is basically the intersection of the sets 1,2,3 below plus cutting off the rest outside the rectangle (I have shown only three the most important quadrants on the pictures as the others cannot penetrate in the rectangle, so they make the obvious cut - the same as half-planes). The intersection then is precisely the set drawn on the figure 3 above. In your answer it looks like you are taking away half-planes (less freedom) instead of the quadrants, that's why you get it different. By the way, the inside part of your rectangle seems to be empty. If so, how did you cut it off?
Comment: Few questions

1) Maximal orthogonal convex hull is not defined on the Wiki page. It is defined in the paper (linked in question) on page 160, Def 2.4. Are Orthogonal Convex Hull and Maximal-Orthogonal Convex Hull the same?

2) I still don't understand your answer completely. Example, in your image (1), any quadrant that is below and left of the one shown is also set free (i.e none of the three points in quadrant). Do I take a union of all such quads?

3) Why is one of the quadrant case missing?

Appreciate your help. Don't know why this question was downvoted on Mathoverflow.
Comment: I have updated the paper link. Now its on my google drive in public setting.
Comment: @Abhinav 1) This is the maximal orthogonal convex hull as it defined in your paper. The rectilinear half-plane is the plane without a quadrant. Wiki definition is basically the same (due to Proposition 2.4 in the paper). 2)+3) Yes, you are right, those quadrants are needed too, but I draw only the most important quadrants with non-trivial cut. I have added this explanation to the answer.
Comment: Thanks. One thing is odd in the paper. In def 2.4 it reads, "In Figure 4 the four possible rectilinear half planes are illustrated," But aren't these rectilinear quadrants and not rectilinear half planes?
Comment: @Abhinav They are rectilinear half planes, which are the *complements* of the rectilinear quadrants. The quadrants are white in colour and not in the set.
Comment: I had put the above comment as another question on math.stackexchange [here](http://math.stackexchange.com/questions/1446700/rectilinear-half-plane-is-my-understanding-correct-image-attached). If you give the above answer there Ill accept it.
Answer: After understanding the logic of creating mr-convex hull of a set of points in a plane from A.G's answer, I tried making a sketch that explains the idea clearly (hopefully). You can access the sketch here.


Roundcube Autologon

Question: i have Roundcube and i need to change the Login ...
i found only :

<roundcube:form name="form" method="post">
<roundcube:object name="loginform" form="form" size="40" submit=true />

And i have login Script :

                            <form  action="?????.php" method="post">

Webmail Login

                                     Email
                                    <input id="username" name="username" required="required" type="text" placeholder="firstname.lastname@example.com"/>

                                     Passwort
                                    <input id="password" name="password" required="required" type="password" placeholder="eg. X8df!90EO" />

         <input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />
         Keep me logged in

                                    <input type="submit" value="Login" />

         Noch kein Mitglied ?
         Registrieren

                            </form>

I have Activate the "autologon" Plugin.
What i need now?
Answer: Note: Working on RoundCube 1.4.11 Version.
Step 1: Update config.inc.php
Update Plugin
$config['plugins'] = array('autologon');
Realpath: ROUNDCUBE/config/config.inc.php

Step 2: Update autologon.php
Realpath: ROUNDCUBE/plugins/autologon/autologon.php
function authenticate($args)
  {
    if (!empty($_POST['_autologin']) && $this->is_localhost()) {
      $args['user'] = $_POST['_user'];
      $args['pass'] = $_POST['_pass'];
      $args['host'] = 'ssl://mail.YOUR DOMAIN NAME.com';
      $args['cookiecheck'] = false;
      $args['valid'] = true;
    }
    return $args;
  }

Step 3: Update index.php
Update this code before this line
Realpath: ROUNDCUBE/index.php
if ($auth['valid'] && !$auth['abort'] && $RCMAIL->login($auth['user'], $auth['pass'], $auth['host'], $auth['cookiecheck'])) {

Code here
This process makes the Authentication Validation to true if the Username and Password is to post
Try More Custom Condition for more if you want
        // Custom Code
        {

            // if login detail post and check post server detail
            if( $RCMAIL->login($auth['user'], $auth['pass']) && $_POST['_user'] && !empty($_POST['_user']) && $_POST['_pass'] && !empty($_POST['_pass']) ){
                $auth['valid'] = true;
                $auth['abort'] = false;
            }

        }

Step 4: Create form for POST data to index.php
<form name="form" action="//YOUR DOMAIN NAME.com/index.php" method="post">
    <input type="hidden" name="_action" value="login" />
    <input type="hidden" name="_task" value="login" />
    <input type="hidden" name="_autologin" value="1" />

            Utente
            <input name="_user" id="rcmloginuser" value="" type="text" />

            Password
            <input name="_pass" id="rcmloginpwd" type="password" />

            <input type="submit" value="Login" />

</form>

Answer: I use RoundcubeAutoLogin class to auto login: https://github.com/alexjeen/Roundcube-AutoLogin
And I call it like this:
require_once 'RoundcubeAutoLogin.php';

$rc = new RoundcubeAutoLogin('http://your_domain/roundcube/'); // set your roundcube domain path

$cookies = $rc->login('firstname.lastname@example.com', 'email_password');

// now you can set the cookies with setcookie php function, or using any other function of a framework you are using

foreach($cookies as $cookie_name => $cookie_value)
{
    setcookie($cookie_name, $cookie_value, 0, '/', '');
}
// and redirect to roundcube with the set cookies
$rc->redirect();

I hope that this will help you

Roundcube Autologon


Datalist.Visible always false?

Question: I've done this a million times without a problem, and I'm stumped at this one.
I have a DataGrid:
<asp:DataGrid ID="gridDeptEmployees" runat="server" AutoGenerateColumns="False"
                 ItemStyle-CssClass="hovertable" ViewStateMode="Enabled">
                    <ItemStyle Font-Size="Smaller" />
                    <Columns>
                        <asp:TemplateColumn HeaderStyle-CssClass="hidden">
                            <ItemTemplate>
                                <asp:CheckBox ID="cbSelect" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateColumn>
                        <asp:BoundColumn DataField="firstname" HeaderStyle-CssClass="hidden" />
                        <asp:BoundColumn DataField="lastname" HeaderStyle-CssClass="hidden" />
                        <asp:BoundColumn DataField="employeeNumber" HeaderStyle-CssClass="hidden" />
                    </Columns>
                </asp:DataGrid>

This datagrid is bound to a list of objects:
Dim userList as New List(Of User)
userList = getList()
gridDeptEmployees.DataSource = ulst
            gridDeptEmployees.DataBind()

I can see users in the list when I set a breakpoint and step through it, but the grid is never visible. The visible property is always false!
I've tried explicitly setting the visible property, but it doesn't honor my changes. I even tried adding my DataKeyNames, but that didn't work.
What am I missing here? Should I switch to a different control?
Comment: maybe is inside some other control that is non-visible, like a PlaceHolder, or a Panel, or a custom control
Comment: Aristos - want to make this an answer so I can give you the credit?
Answer: When you can not see a control (not rendered on page), and debug it and see that the visible is false, then is probably because is inside some other hidden control, like a PlaceHolder, or a Panel, or a UserControl.
Check to see if a parent control is hidden to find your reason.

Datalist.Visible always false?


Tweet Scheduler based on Flask Megatutorial: Issues with getting fields of flask-sqlalchemy databse

Question: I'm in the process of modifying the Flask app created in following along Miguel Grinberg's Flask Mega Tutorial such that it is possible to post tweets. I have imported tweepy for accessing the twitter api and modified the databases to hold the scheduled time of a tweet.
I wish to iterate over the current_user's posts and the corresponding times from the SQLAlchemy database and post when the current time matches the scheduled time.
The database model modifications in model.py are as follows:
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
socialnetwork = db.Column(db.String(40))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#This is the stuff for scheduling, just date
hour = db.Column(db.Integer)
minute = db.Column(db.Integer)
day = db.Column(db.Integer)
month = db.Column(db.Integer)
year = db.Column(db.Integer)
ampm = db.Column(db.String(2))

Just as a test, I wanted to iterate over the current user's posts and tweet them using tweepy:
@app.before_first_request
def activate_job():
    def run_job():
        posts = current_user.followed_posts().filter_by(socialnetwork ='Twitter')
        for post in posts:
            tweepy_api.update_status(message)

            time.sleep(30)
    thread = threading.Thread(target=run_job)
    thread.start()

However, this returned the error:
AttributeError: 'NoneType' object has no attribute 'followed_posts'

on the terminal. This is perplexing me as I have used current_user multiple times in the same file to filter the posts by social network.
As in the following case in routes.py
@app.route('/<username>')
@login_required
def user(username):
    user = User.query.filter_by(username = username).first_or_404()
    socialnetwork = request.args.get("socialnetwork")

    if socialnetwork == 'Facebook':

    posts = current_user.followed_posts().filter_by(socialnetwork = 'Facebook')

    elif socialnetwork == 'Twitter':
        posts = current_user.followed_posts().filter_by(socialnetwork = 'Twitter')
    else:
        posts = current_user.followed_posts()

    return render_template('user.html', user = user, posts = posts, form = socialnetwork)

The above yields no error and works perfectly.
If anyone could shed some light on what I am doing wrong, I'd be truly grateful.
Answer: You're likely running into issues because you're trying to get current_user on a different thread (see the Flask docs for more details).  You're calling run_job() in a different context that doesn't have any current user (because there's no active request).
I'd rework it so that you get the current user's posts on the main thread (i.e. in activate_job(), then pass the list of posts to the background process to work on.
Something like:
def activate_job():
    posts = current_user.followed_posts().filter_by(socialnetwork ='Twitter')
    def run_job(posts):
        for post in posts:
            tweepy_api.update_status(message)

            time.sleep(30)
    thread = threading.Thread(target=run_job, args=[posts])
    thread.start()

It's also worth noting that you may want to rethink your overall approach. Rather than checking with each request if there are any scheduled tweets to send, you should use some sort of background task queue that an operate independently of the web process. That way, you're not checking redundantly on each request, and you're not dependant on the user making requests around the scheduled time.
See The Flask Mega-Tutorial Part XXII: Background Jobs for more details, and look into Celery.
Comment: Thank you, I am still unclear as to how I should go about getting the current user's posts on the main thread. Perhaps I misunderstood, but shouldn't the thread created in my 'hacked-up' function be an auxiliary thread and the other thread(the one in which I execute the other functions, views etc.), the main thread?
Comment: Thank you so much, will try, tinker a little and let you know
Comment: It seems to work except for the face that, the following error is spawned: SQLite objects created in a thread can only be used in that same thread. As a remedial measure, I discovered that the following line should be added to the config.py:
  SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db?
 check_same_thread=False'. However, I have connected the databse as follows:
  SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:///'+os.path.join(basedir, 'app.db'). I'd really appreciate it if you could offer any guidance to change the last statement to reflect the former.
Comment: I apologize about the clutter, I don't know how to include code in comments.
Comment: Thank you, I just needed something quick for a demonstration. I'm definitely going to use Celery/RQ as you suggested.
Comment: I've added a quick example of how to change your code. It may still require some changes to actually work, but should get you started.
Comment: I'd suggest you rethink your approach, so you can avoid needing to access the database on the background thread. Ideally, look into the task queue approach I suggested. Additionally, if you need to post code blocks, updating the question is probably the best place for additional info.


Three points are collinear if and only if the matrix has a non trivial solution

Question: I have to prove three points are collinear iff$$\begin{pmatrix}x_1&y_1&1&0\\x_2&y_2&1&0\\x_3&y_3&1&0\end{pmatrix}$$has a non-trivial solution. I'm having problems on the $\Leftarrow$ side. I assumed that if$$\begin{pmatrix}x_1&y_1&1&0\\x_2&y_2&1&0\\x_3&y_3&1&0\end{pmatrix}$$has a non-trivial solution, then it has infinite solutions. Therefore, I can find a solution in which the points are collinear. But my thought process seems very fishy to me. I'm sure I made a mistake somewhere.
Comment: To be precise: an *equation* can have a nontrivial solution. A matrix cannot; it does not make sense for a matrix to have a solution. What you mean is that the equation $$\begin{pmatrix}x_1 & y_1 & 1 \\ x_2 & y_2 & 1 \\ x_3 & y_3 & 1\end{pmatrix} \begin{pmatrix}a \\ b \\ c\end{pmatrix} = \begin{pmatrix}0 \\ 0 \\ 0\end{pmatrix}$$ has a nontrivial solution $(a,b,c)$.
Answer: Suppose that the equation $$\begin{pmatrix}x_1 & y_1 & 1 \\ x_2 & y_2 & 1 \\ x_3 & y_3 & 1\end{pmatrix} \begin{pmatrix}a \\ b \\ c\end{pmatrix} = \begin{pmatrix}0 \\ 0 \\ 0\end{pmatrix}$$ has a nontrivial solution $(a,b,c)$. Then all three points $(x_1,y_1)$, $(x_2, y_2)$, and $(x_3, y_3)$ lie on the line $ax + by + c =0$.
Comment: This is, by far, the simplest and most direct of the answers given.
Answer: The points $A(x_1, y_1), B(x_2, y_2), C(x_3, y_3)$ are collinear if the determinant of the matrix is equal to zero.
$$\begin{vmatrix}x_1 & y_1 & 1 \\ x_2 & y_2 & 1 \\ x_3 & y_3 & 1\end{vmatrix} = 0$$
Note that this is because we can calculate the area of a triangle by
$$A=\frac{1}{2}\cdot \begin{vmatrix}x_1 & y_1 & 1 \\ x_2 & y_2 & 1 \\ x_3 & y_3 & 1\end{vmatrix}$$
As the points represent the vertices of the triangles, if the area exists, the determinant must be different from zero, otherwise, the vertices are aligned, and therefore, collinear.
You may also take this example using vectors. Once two vectors $\vec v$ and $\vec u$ are collinear if $\exists k \in \mathbb{R}: \vec v=k\vec u$, two vectors are collinear if they are parallel.
Given the points $P(3, 2, 1)$, $Q(-2, 5, 2)$ and $S(8, -1, 0)$,
$\overrightarrow {PQ} = Q - P = (-2, 5, 2)-(3, 2, 1)=(-5, 3, 1)$
$\overrightarrow {QS} = S -Q = (8, -1, 0)-(-2, 5, 2)=(10, -6, -2)$
Once $-2 \overrightarrow {PQ}=\overrightarrow {QS}$, we have  $\overrightarrow {QS}\parallel\overrightarrow {PQ}$ and hence $P, Q$ and $S$ are collinear.
Comment: My favorite way of proving the determinant area formula is to *start* from the fact that the points are collinear when the determinant is $0$. Then, we can check that both (signed) area and the determinant vary linearly as we move one of the points along a line. Then, we figure out that the constant of proportionality, $\frac12$, by checking a special case.
Answer: Geometriclly seen, the area enclosed between three points in 3-space vanishes when the determinant
$$\begin{pmatrix}x_1 & y_1 & 1 \\ x_2 & y_2 & 1 \\ x_3 & y_3 & 1\end{pmatrix} = 0 $$
It is same as saying that these three points and vectors connecting them are collinear.


Binding errors coming from under hood

Question: Trying to use grouping in DataGrid and for no reasons getting those binding errors (they are not belong to my code, nor I see a way to deal with them):

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=AreRowDetailsFrozen; DataItem=null; target element is 'DataGridDetailsPresenter' (Name=''); target property is 'SelectiveScrollingOrientation' (type 'SelectiveScrollingOrientation')

and

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=HeadersVisibility; DataItem=null; target element is 'DataGridRowHeader' (Name=''); target property is 'Visibility' (type 'Visibility')

They appears for each row in DataGrid. This bugs me alot!
To reproduce the problem I made a small project
public class MyItem
{
    public string A { get; set; }
}

public class ViewModel
{
    public List<MyItem> List { get; set; }

    public ViewModel()
    {
        List = new List<MyItem>(new[] { new MyItem() });
    }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

xaml
<DataGrid ItemsSource="{Binding List}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding A}" Header="A"/>
    </DataGrid.Columns>
    <DataGrid.GroupStyle>
        <GroupStyle>
            <GroupStyle.ContainerStyle>

            </GroupStyle.ContainerStyle>
        </GroupStyle>
    </DataGrid.GroupStyle>
</DataGrid>

Some observations:

without DataGrid.GroupStyle there are no errors;
with AutoGenerateColumns = true there are no errors;
without binding (setting DataGrid.ItemsSource directly) there are no errors.

Only combination of opposite to those 3 conditions will start spamming Output window with above messages.
What should I do? I can't ignore errors, nor I see a way to fix them.
Googling around wasn't really helpful, to example, this case was called a bug, I tried to apply its workarounds, but none works for me.
P.S.: discovering such bugs at first attempt to use DataGrid is very demotivating.

Trying to deal with second error.
<DataGrid.RowHeaderStyle>

</DataGrid.RowHeaderStyle>

But error still

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=HeadersVisibility; DataItem=null; target element is 'DataGridRowHeader' (Name=''); target property is 'Visibility' (type 'Visibility')
Answer: Was playing with control templates and after changing one for DataGridRow errors are gone!
<DataGrid.RowStyle>

</DataGrid.RowStyle>

I removed DataGridDetailsPresenter and DataGridRowHeader from default template, because I will not use them.

I got one more error

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=NewItemMargin; DataItem=null; target element is 'DataGridRow' (Name=''); target property is 'Margin' (type 'Thickness')

which I fix by adding Margin setter into DataGrid.RowStyle
<Setter Property="Margin" Value="0"/>

It seems all of such errors can be fixed by re-factoring default templates.
Comment: thanks, guy! after searched lots of 'workaround' through googling, only your way works!
Comment: Worked for me too.  Thanks!
Comment: It seems to suppress part of the problem, but doesn't really solve it. I have a GroupStyle and an ICollectionView.Filter... since I got this error they don't work anymore! Unfortunately, after implementing your solution, they still don't work
Answer: Firs of all thanks Sinatr for the problem analysis and the solution, which almost worked for me.
I did have the same problem with the DataGrid Control. Apart from the binding errors in the output there was a slight displacement of the new item row (in my case the DataRowMargin was off by two DIPs).
DataGridRow invalid margin
The whole issue is caused by a style trigger activated when the IsNewItemProperty equals true, the DataGridRow is not getting the proper margin values. The answer from Sinatr did fix the binding issue but the wrong margin was still used. This is the styling that removed the binding errors and set the correct margin.

</Style>

Binding errors coming from under hood


Inheritance with possible template failure

Question: An error in a method that relies on template expansion only gives a compiler error when the method is explicitly called. Though when that method is marked as virtual, it produces a compiler error whether or not it is actually called. Is there anything in the C++ standard that explains why marking these methods as virtual causes a compiler error?
#include <memory>
#include <iostream>

template <class T_>
class Foo
{
protected:
    T_ data;
public:
    Foo(const T_& x) : data(x) { }

    Foo(T_&& x) : data(std::move(x)) { }

    // comment these two lines out and it works fine.
    virtual void test(T_& x) = 0;
    virtual void test(T_&& x) = 0;
};

template <class T_>
class Bar : public Foo<T_>
{
public:
    using Foo<T_>::Foo;

    void test(T_& x)
    {
        std::cout << "test(&)" << std::endl;
        x = this->data;
    }

    void test(T_&& x)
    {
        std::cout << "test(&&)" << std::endl;
        x = std::move(this->data);
    }
};

int main()
{
    Bar<std::unique_ptr<int>> x(std::unique_ptr<int>(new int(42)));
}

Answer: The overriders of virtual functions are always odr-used - that is, their definition must be present, whether they are explicitly used in a translation unit or not. Overriders of virtual functions are themselves virtual ([class.virtual]/2) and all virtual functions must be defined ([basic.def.odr]/3 and 4).
Now the question is whether the test overloads in the derived class are actually instantiated.
For templates, the standard mandates that

Unless a member of a class template […] has been
  explicitly instantiated or explicitly specialized, the specialization
  of the member is implicitly instantiated when the specialization is
  referenced in a context that requires the member definition to exist;

For virtual functions one might argue that their presence is enough to require a definition. However, the standard doesn't tie itself down and leaves the decision to the implementation, [temp.inst]/11:

It is unspecified whether or not an implementation implicitly
  instantiates a virtual member function of a class template if the
  virtual member function would not otherwise be instantiated.
Comment: Also relevant is [temp.inst]/p11 - "An implementation shall not implicitly instantiate [...] a non-virtual member function [...] of a class template that does not require instantiation. It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated."
Comment: The declarations *are* instantiated when the class template is instantiated. The definitions *aren't*, by default ([temp.inst]/p1). The general rule is that "the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist" ([temp.inst]/p2). Whether being *odr-used* counts as such a context is unclear. Regardless, [temp.inst]/p11 gives the compiler leeway to instantiate a virtual member function that would not otherwise be instantiated.
Comment: @T.C. Yeah, I just found the same quote. I was unclear about when a requirement exists, but that seems to be a vagueness of the standard itself.
Answer: Making it virtual is forcing instantiation. I get the same error with the following test code after commenting out the virtual function in the base class:
int main()
{
    Bar<std::unique_ptr<int>> x(std::unique_ptr<int>(new int(42)));
    x.test(std::unique_ptr<int>(new int(99)));
    std::unique_ptr<int> pi;
    x.test(pi);
    std::cout << "test returned " << *pi << std::endl;
}

The version taking an reference can't be instantiated as std::unique_ptr is not assignable.


Modal II-V Patterns

Question: So II-V7 patterns occur when a minor seventh and a dominant seventh are a fourth apart or when a minor seventh moves to a dominant seventh with root motion that moves down by half step. This all being in Ionian of course. So does the same apply to the different modes?
Let's take C Phrygian fot example, would DbMaj7 to G°7 (or Gm7 (b5)) work as a II-V7 pattern? The II in this mode is not minor and the V is diminished but it also functions as a member of the dominant family. And they're also a fourth apart in the scale. Would you use modal interchange to change the chord types to bII-7 and V7? Or would Dbm7 to G°7 work because the Diminished chord has the same function as a dominant chord? Any clarity would help, thank you
Answer: All of the normal modes are derived from the Major scale, where the tonic is a different degree from that scale. Your example concerns C Phrygian. Phrygian has the tonic derived from the third scale degree of Major, and C natural can only be the third degree of Ab Major, also known as Ab Ionian.
Think of the Ionian scale as its scale degrees:
1-2-3/4-5-6-7/1, or
Ab-Bb-C/Db-Eb-F-G/Ab
Phyrgian has 3 as the tonic, so the scale would be shifted:
3/4-5-6-7/1-2-3, or
1/2-3-4-5/6-7-1, or
C/Db-Eb-F-G/Ab-Bb-C

Here I wrote the chords out so you can see the difference compared to major. As you can see both Db and F are common between the Dbmaj7 and Ghalfdim7, with the Ab moving down a half step to G, C down a whole step to Bb, and the bass Db moving up an augmented 4th to G. The A4 is very important in a dominant chord in major, since the interval is rather dissonant and the notes are only a half step away from the tonic chord, as can be seen on the major side between F and B. B is pulled up to the tonic while F is pulled down to the third of the tonic chord. This interval is also only present between 4 and 7, which in Phrygian is now 2 and 5.
Next the bass moves up a perfect 4th to the tonic, C, making a nice cadence, while the soprano moves down a half step taking advantage of that flatted second degree half step which wants to resolve to the tonic. F moves down a whole step to Eb instead of a half step, so it's not quite as nice, and Bb and G stay the same.
When writing in modes it's best to take advantage of it's unique properties compared to its relative Major or Minor scale. Half steps tend to want to resolve the most and sound great doing so compared to whole steps. There are also many ways to voice the chords and lead the voices depending on what intervals you wish to focus on. In my example, if you added a Db to the V chord an octave lower than the soprano the augmented 4th between G and Db adds extra tension. Db is the unique tone in Phyrgian, and both the II and v chords have it, making them great chords to works with.
Comment: Tonic, dominant, and sub-dominant are functional based on their intervals, which I pointed out in my answer. Tritones tend to want to resolve back into stable perfect 5ths. Half steps and minor thirds tend to want to resolve to major thirds, a more stable interval. In minor keys the point is to be unresolved. Basic rules like these are why functional harmony work. You just have to apply these to the intervals present in any given mode.
Comment: Thank you, that was an incredible answer and gave me a great understanding of using modes. By any chance have you encountered any pages or charts on the modal chord families? I can't find any and it would save me a lot of time for the other modes.
Comment: @MusicMan I don't have any charts with this because I don't think it's entirely necessary. Since modes are all derived from the Major scale if you learn the relationships between all the chords of the Major scale it will all transfer over. Any chord progression works not only on the chord's quality but also the intervals between them and the rhythm which accents certain chords or pitches above others. So I'm not sure what such a chart would entail.
Comment: I guess to specify, the dominant chords in Ionian are the V and Vii. In Phrygian or Aeolian, the dominant chords or the chords with the most resolution to the tonic would change. Obviously the V and Vii of Ionian wouldn't be the dominant chords of the other modes.
Comment: Thank you very much, I appreciate it. I've always been confused on the matter. I'm a bassist and just got into chord theory etc
Answer: For analytical purposes, the same roman numeral analysis can be used for modal music; however the function of the chords is not necessarily the same (depending on the mode). In phrygian, for example, the V chord is built on the fifth scale degree, but it does not function as a dominant chord. It has a different quality and does not have the same pull (or resolution) to the tonic. Generally speaking, even in modal music (at least in western, tonal music) chord progressions tend to have a "function." Tonic, dominant, sub-dominant are the three basic "categories" of chord function. Use your ears to determine what sounds unresolved and what has the strongest tendencies to move to the tonic chord. Again, using phrygian as an example, composers tend to choose either the II chord or VII chord as "dominant" to resolve to tonic. (So in C Phrygian, either Db major or Bbm).
Comment: I don't agree that the Phrygian bII or bvii have dominant functions. I generally hear bvii-i to sound more like a deceptive cadence and bII-i to sound more like the minor key's bVI-V.
Comment: Why exactly are the II and VII chords of Phrygian dominant sounding? Is there a more detailed page of details on this information?
Comment: I can't find a single book or page on the internet on this topic. It would be really helpful for future musicians or composers if we all could figure out a chart for the modes and their chord families.
Comment: Phrygian tends to not be used as much as, say, mixolydian.  I know Respighi utilized it in Trittico Botticelliano. It often gets "modified," similar to the way we modify aeolian-natural minor to accommodate functional harmony. A I-II-III-II-I motif (progression) is often heard in TV or film scores to accompany bull fights or conquistador scenes. Em  F G F   Em  which sometime  becomes major phrygian.  E   F G F   E. The bii of the mode is like a tritone sub for a dominant chord.
Comment: M-Squared, that's incredibly interesting. I appreciate the insight, is it the cadential motion of the notes within the chord then that'll tell you if a modal chord has a certain function? I love to stray away from Ionian but can't find much anywhere on modal chord families
Comment: The E F G F E chord progression looks more like heavy borrowing from the Phrygian Dominant scale to me. I strongly suspect this chord progression is not strictly modal, as it uses both G and G#.

Modal II-V Patterns


VMWare - Jumbo Frames over iSCSI to a NAS4Free array

Question: I am having problems getting Jumbo Frames working over my iSCSI connection.
Here is what I try.

4 1GbE connections on 4 different subnets on my NAS4Free array for iSCSI, MTU set at 9000
2 redunant switches with the MTU set at their maximum 12288(or something like that)
1 vSwitch MTU 9000
4 vNICs MTU 9000

If I turn the vNICs MTU from 1500 to 9000 everything stops working, I can't even turn on or off a VM on the associated datastore.
Comment: @ewwhite They generally make sense on something like ISCSI  - the overhead and packet reduction can seriously take load of the network in this particular case.
Comment: Do you *need* Jumbo frames?
Comment: From what I had researched if I can turn it on it is beneficial to do so. And I have a SAN unti from Dell that appears to support Jumbo Frames and only Jumbo Frames.
Answer: I have punted for this array, the problem I am having seems to be pointing back at the NAS4Free array, since I can use 9000 MTU for VMotion just fine (over the same NICs and switches, just different vNICs). I am going to create two iSCSI storage networks, one that operates as 1500 MTU and one that operates at 9000 MTU. When I transition my other SAN units to the cluster I will attempt to get them working on the Jumbo Frame network.


Holder continuity for $\alpha$ but not $\alpha+\varepsilon$?

Question: Is it possible to find a function which is, say, α− Holder continuous, for 0<α≤1, but not α+ε- Holder continuous for arbitrary ε>0? I was thinking that perhaps $|x|^\alpha$ could work? It's easy to prove that function is α−Holder continuous but I'm not sure how to prove it isn't when you make α slightly larger.
Answer: You are right, $f(x) = |x|^{\alpha}$ works. You can show that it is not Holder continuous with exponent $\alpha + \epsilon$ by taking $x = s$ and $y = 0$ in the definition of Holder continuity:
$$\frac{|f(x) - f(y)|}{|x -y|^{\alpha + \epsilon}} = s^{-\epsilon},$$
which tends to $\infty$ as $s \to 0$.
Notice, however, that $f(x)$ is Holder continuous for exponents less than $\alpha$ only if you look at a bounded interval. On $\mathbb R$, it is not, because
$$\frac{|f(s) - f(0)|}{|s -0|^{\alpha - \epsilon}} = s^{\epsilon},$$
which tends to $\infty$ as $x \to \infty$.
Comment: Ah, of course. Thank you!
Comment: You're welcome!


How can I pivot result of SQL query

Question: I Have this result in for my SQL query

and I want to convert it like this
Comment: Try to see: https://stackoverflow.com/questions/7674786/mysql-pivot-table   (this is first result using Google search with words: pivot mysql)
Answer: You could use (a fake) aggregation function and group by
<code>select type_revenue
  , max(case when location_name ='30juin' then amount else 0 end) 30Jui
  , max(case when location_name ='Bandal' then amount else 0 end) Bandal
from my_tbale
group by type_revenue
</code>

How can I pivot result of SQL query