Prime number $p=4k+1,\;k\in\mathbb{Z}$

Question: Let $p=4k+1,$$p$ is a prime numbe,and $ k\in\mathbb{Z}$. Prove the existence of positive integer $a_1,a_2,\ldots,a_k$ and $b_1,b_2,\ldots,b_k$.
$$
p=\frac{(a^{2}_{1}+1)(a^{2}_{2}+1)\cdots(a^{2}_{k}+1)}{(b_{1}^{2}+1)(b_{2}^{2}+1)\cdots(b_{k}^{2}+1)}.
$$
My friend trying to prove the following for a long time,and I cann't solve it,I hope you can help me.
I would be extremely happy if somebody could help me with this!
Comment: *Let $n \in {\mathbb N}$, and $n > 3$. Prove the non-existence of positive integer $x, y, z$. $$x^n + y^n = z^n$$  My friend trying to prove the following for a long time,and I cann't solve it,I hope you can help me. I would be extremely happy if somebody could help me with this!* It is definitely not the question for stackexchange.
Comment: @penartur (1) This site is for all math questions, simple or difficult. (2) Even if difficult questions were disallowed, generally there is no way to know in advance how difficult a solution will be. Teachers sometimes pose difficult (even unsolved) problems as exercises without any warning to students. Occasionally they are solved. Incorrect preconceptions about the difficulty of problems often times prevent one from discovering simple, beautiful solutions.
Comment: Where did the problem come from? Is there any reason to believe it holds? Are there any restrictions on $a_i$ and $b_i$? Context?
Comment: @penartur Why is this question *definitely not a question for stackexchange*? Where else would you go?
Comment: @penartur:Thank you for your concern, I am a Chinese student, my English is terrible.I think I will try to overcome language difficulties.It will be a pleasant thing ,exchange Mathematics with you.thank you!
Comment: http://en.wikipedia.org/wiki/Fermat%27s_theorem_on_sums_of_two_squares
Comment: @pedja The question is not about the sum of two squares but about the complex fraction. Getting one from the other is not obvious, if the two things related at all.
Comment: @penartur: my first thought was to use results of sums of squares, and repeated application of the Brahmagupta-Fibonacci identity. What is (or isn't) obviously to you might not be obvious to others!
Comment: @draks Making it more obvious, would you consider a question "I want to write my Ph.D. diploma, i tried writing it for a long time but didn't succeed, please help me" as appropriate for stackexchange? Both this and OP questions are more like requests to do some heavy (and well-paid outside of the stackexchange) work/research for free. If one wants to prove some not-well-known theorem, they should do it by themselves or discuss it on some thematic boards / etc, stating the discussants as co-authors.
Comment: @draks Or here is another analogy: asking people to say how can you fix your broken ipad is the question; asking people to invent a new ipad for you (so that your company may became #1 on the tablets' market) is not the question, and asking it on a resource like stackexchange where the people help others for free is a bit inappropriate and impertinent.
Comment: @Arturo Magidin:This problem comes from one of my friend,and I think it's right.I figured that the smaller the case.Thank you all the same.
Comment: @BillDubuque Still there is a difference between a difficult question and the work task.
Answer: Maybe something like this works. There's an integer $a_1$ such that $a_1^2+1=pm_1$ with $m_1\lt p$. There's an integer $b_1$ such that $b_1^2+1=m_1n_2$ with $n_2\lt m_1$. There's an integer $a_2$ with $a_2^2+1=n_2m_2$ with $m_2\lt n_2$. Etc. The sequence $p\gt m_1\gt n_2\gt m_2\dots$ must terminate after at most $k$ steps (since each $m_i$ and $n_i$ is 1 mod 4).

Prime number $p=4k+1,\;k\in\mathbb{Z}$


Allow user to change the web page font sizes - ASP.Net

Question: I want to provide a feature on my website to let users increase and decrease the font size by clicking on some stuff (like + and - image etc). However I also want:

make sure that when the font size is increased, my website layout doesn't get messed up
test the scenario out on my machine to make sure about the point above

I think what I want is a solution that is independent of the browsers font size and machines font size otherwise i would have no way of testing and controlling the results
in my web application, i haven't hard coded font sizes but in some place i have specified text boxes length like width = 50px which i think needs to be changed..so what unit should i use?
i am thinking of using themes and defining the font sizes of labels and text boxes as small, smaller, bigger etc ..not sure if that will work?

Update: I asked the question on another forum as well: http://forums.asp.net/t/1453926.aspx
Basically, from all the answers, I gathered that there are two approaches:

Use em and body font size:
body
{
font-size: 62.5%;
}
p
{
font-size: 1.2em;
}

and when you have to increase/decrease font size, simply increase/decrease the body font size percentage

Use absolute font sizes:
css defines a range (7) of font sizes from xx-small to xx-large so you can define font-size: small in css..

i found a good article on these font sizes at:
http://meyerweb.com/eric/articles/webrev/199908a.html
however none of these two options is what i was looking for. I was looking for setting absolute sizes in the real sense so if i set font-size:large, and then i increase the browser size, font sizes should remain same..right now even with these"absolute font sizes" its dependent on current browsers font size. Any help????
Answer: I would use jQuery to do this.  This question wasn't exactly the same, but the highlighted answer is very close to what you want to achieve:
Allow users to change font size in a webpage
This one is also quite good: http://webrocket.ulmb.com/ability, although the demo is a little pants
Comment: thanks..but the answer for that question suggest :

body
{
    font-size: 62.5%;
}

does that mean make it 62% of the size configured in the browser or at the OS level..in that case, the problem is that i cant control and test it..i mean one users default font size could be 20 and for someone else it can be 12..so...
Comment: But without defining actual font sizes in the css, the only thing you can use is percentages.  If you were to set all of the fonts at "normal" level to be a particular pixel size, then you could get away with defining classes such as smaller, small, normal, big as actual pixel sizes.  Otherwise, percentages (or maybe em's) are the only way of achieving this.
Answer: You might want to look into some surveys to see if this is a desired feature. Most people I know will use their web browser's built in functionality to manipulate font size. Throughout my own testing and development on various sites, most clients ignore font-size controls on websites. Might save you some time in the long run :)
If you find you actually implement this, the biggest concern is to make sure that your font-sizes are increased in a balanced matter, and that your layout and css design patters are "fluid" and "expandable". This is actually sort of hard, because if the site design is a fixed-width layout, then you may run into problems with the content not being able to fit anymore, which can be pretty disheartening with what you're trying to accomplish.
If it's not though, then again just make sure to maintain a balance between elements and their font-sizes. Personally though, I would leave the font-changes up to the web browser. Most browsers are pretty good about manipulating your layouts on their own.
Comment: thanks..that's exactly my concern .. i want to make sure if the user increase the font sizes through the browser, the web application (consisting of bunch of forms) doesnt get messed up...how do i do that and i do i know my website is fluid and expandable..i havent hard coded any sizes or font sizes in my web application
Answer: You are very close to the solution, I know its too late to reply on this thread now, However guessing it might useful to the users who come across on this question
In simple with Jquery selectors change font size using css.
<code>function font_resize(act)
{
    if(act=='small')
    {
        $("body").css("font-size","10px");
        $("#footer").css("font-size","9px");

    }
    else if(act=='mid')
    {
        $("body").css("font-size","12px");
        $("#footer").css("font-size","11px");

    }
    else if(act=='large')
    {
        $("body").css("font-size","15px");
        $("#footer").css("font-size","14px");

    }
}
</code>
Answer: jQuery, see Easy text resizer with jQuery
Comment: Link is broken.


Duvida sistemas de perguntas e resposta com método $_GET

Question: Tenho um sistema que mostra uma pergunta e a pessoa responde,só que estou com uma falha,seguinte:
 Quando a pessoal responde passo uso o método $_GET para pegar a resposta dele e inserir as informações no banco,mais a falha e que se a pessoa atualizar a pagina ou coisa assim a informação é inserida 2x no banco,como poderia fazer para fazer somente uma inclusão no banco ?
Formulário:
<form class="form-horizontal" action="comportamento.php?nro_pergunta=<?php  echo $nro_pergunta; ?>" method="GET">
  <fieldset>
      <legend>Pergunta <?php echo"$ordem";?> de <?php echo"$totalpergunta";?></legend>
    <?php
     $timestamp            = @mktime(date("H")-4, date("i"),date("s"),date("m"),date("d"),date("Y"),0);
     $data_cad              = gmdate("Y-m-d", $timestamp);
     echo"<input type='hidden' name='loja'         id='loja'         value='$loja'>";
     echo"<input type='hidden' name='id_usuario'   id='id_usuario'   value='$id_usuario'>";
     echo"<input type='hidden' name='questionario' id='questionario' value='$questionario'>";
     echo"<input type='hidden' name='area'         id='area'         value='$area'>";
     echo"<input type='hidden' name='nro_pergunta' id='nro_pergunta' value='$nro_pergunta'>";
     echo"<input type='hidden' name='data_cad'     id='data_cad'     value='$data_cad'>";
     echo"<input type='hidden' name='pergunta'     id='pergunta'     value='$idpergunta'>";
    ?>
       <?php
        $sql_button = mysql_query("SELECT *  FROM respostas WHERE
           resp_loja='$loja'
       AND resp_usuario='$id_usuario'
       AND resp_area ='$area'
       AND resp_pergunta_id ='$idpergunta'
       AND resp_subgrupo='100'
       AND resp_questionario='$questionario'");

     if(mysql_num_rows ($sql_button) == 0 )
      {
     echo"
";
      echo"
 $descpergunta
";
      echo"
";
        echo"
<input type='radio' name='resp' id='optionsRadios1' value='5'>OTIMO
";
        echo"
<input type='radio' name='resp' id='optionsRadios2' value='3'>BOM
";
        echo"
<input type='radio' name='resp' id='optionsRadios3' value='2'>REGULAR
";
        echo"
<input type='radio' name='resp' id='optionsRadios3' value='1'>RUIM
";
        echo"
<input type='radio' name='resp' id='optionsRadios4' value='0'>NAO APLICADO
";
        echo"
";
      echo"
";
     echo"
";
      echo"
";
                echo"<button id='button' type='submit' name='submit' class='btn btn-danger'> Responder</button>
";

       echo"
";
    echo"
";
    } else  {
    echo"
";
      echo"
";
            echo"<button id='button' type='next' name='next' class='btn btn-danger'> Próxima</button>
";
            echo"
";
            echo"
";
            echo"<button type='button' class='close' data-dismiss='alert'></button>";
            echo"ATENÇÃO! Você já respondeu essa pergunta.";
            echo"
";
       echo"
";
    echo"
";
    }
   ?>

  </fieldset>
 </form>

Insert:
<?php
 include("conexao.php");
if(isset($_GET['submit'])){
    $loja         = $_GET ["loja"];
    $id_usuario   = $_GET ["id_usuario"];
    $questionario = $_GET ["questionario"];
    $area         = $_GET ["area"];
    $idpergunta   = $_GET ["pergunta"];
    $resp         = $_GET ["resp"];
    $datacad      = $_GET ["data_cad"];

  $sql_insert = mysql_query("INSERT INTO respostas
  (resp_id,resp_loja,resp_usuario,resp_questionario,resp_area,resp_subgrupo,resp_pergunta_id,resp_resposta,resp_data,resp_status)
  VALUES
  ('','$loja','$id_usuario','$questionario','$area','100','$idpergunta','$resp','$datacad','1')") or die (mysql_error());
    mysql_query($sql_insert,$conexao); }

if(isset($_GET['proxima'])){
$pergunta = (int)$_GET['proxima'];
header('location: comportamento.php?nro_pergunta='.$pergunta);
}

OBS: Postei somente a parte do código referente a pergunta,mais se precisarem de mais alguma informação por favor retornar.
E para concluir,não sei se pode colocar 2 perguntas juntas,mais se puderem responder,é o seguinte:
Na inclusão do banco esta inserindo somente a data,e não data hora como é no campo,seria a forma de inclusão que esta errada?
No mais um forte abraço e até mais.
Answer: Algo bem simples de resolver esse problema é fazer a mesma verificação que você fez no formulário dentro do insert.
   <?php
    include("conexao.php");
                $loja         = $_GET ["loja"];
                $id_usuario   = $_GET ["id_usuario"];
                $questionario = $_GET ["questionario"];
                $area         = $_GET ["area"];
                $idpergunta   = $_GET ["pergunta"];
                $resp         = $_GET ["resp"];
                $datacad      = $_GET ["data_cad"];

    $sql_button = mysql_query("SELECT *  FROM respostas WHERE
       resp_loja='$loja'
   AND resp_usuario='$id_usuario'
   AND resp_area ='$area'
   AND resp_pergunta_id ='$idpergunta'
   AND resp_subgrupo='100'
   AND resp_questionario='$questionario'");

 if(mysql_num_rows ($sql_button) == 0 )

   {

            if(isset($_GET['submit'])){

              $sql_insert = mysql_query("INSERT INTO respostas
              (resp_id,resp_loja,resp_usuario,resp_questionario,resp_area,resp_subgrupo,resp_pergunta_id,resp_resposta,resp_data,resp_status)
              VALUES
              ('','$loja','$id_usuario','$questionario','$area','100','$idpergunta','$resp','$datacad','1')") or die (mysql_error());
                mysql_query($sql_insert,$conexao); }

            if(isset($_GET['proxima'])){
            $pergunta = (int)$_GET['proxima'];
            header('location: comportamento.php?nro_pergunta='.$pergunta);
            }

 } else {

     header("Location: vaParaAlgumLugar.php");

 }

?>

Mas, sinceramente, essa não é a melhor forma e nem a mais segura para fazer inserção em DB. Para isso existe o method="post". Pois com ele você sabe realmente se o usuário clicou no <input type="submit">. Além disso abre uma porta imensa para hacker 'ligeirão' usar esse método para manipular sua query.
Sem contar que você pode resgatar alguns parâmetros via $_GET mesmo usando o metodo $_POST no formulário.
Formulários com metodo $_GET são bons para fazer uma busca no DB por exemplo. E mesmo assim, você tem que criar classes ou funções de segurança.
Uma dica: procure não usar mais mysql_*, mude para mysqli_* ou PDO, pois o mysql_* já está defasado.
Espero que eu tenha te ajudado.
Abraço!
Comment: Tinha postado que o erro continuava,mais na verdade estava passando o parâmetro da query errada,já acertei e deu certo,exatamente da forma que você me passou,Obrigado.
Comment: Tranquilo @otacio! Boa sorte!


C++ Compile-Time offsetof inside a template

Question: I have the need to use offsetof from a template with a member selector. I've come up with a way, if you'll excuse the awkward syntax:
template <typename T,
          typename R,
          R T::*M
         >
constexpr std::size_t offset_of()
{
    return reinterpret_cast<std::size_t>(&(((T*)0)->*M));
};

Usage isn't perfect (annoying at best):
struct S
{
    int x;
    int y;
};

static_assert(offset_of<S, int, &S::x>() == 0, "");
static_assert(offset_of<S, int, &S::y>() == sizeof(int), "");

The non-constexpr form is easier to use:
template <typename T, typename R>
std::size_t offset_of(R T::*M)
{
    return reinterpret_cast<std::size_t>(&(((T*)0)->*M));
};

at the obvious disadvantage that it isn't done at compile-time (but easier to use):
int main()
{
    std::cout << offset_of(&S::x) << std::endl;
    std::cout << offset_of(&S::y) << std::endl;
}

What I'm looking for is syntax like the non-constexpr variety, but still fully compile-time; however, I can't come up with the syntax for it. I would also be happy with an offset_of<&S::x>::value (like the rest of the type traits), but can't figure out the syntax magic for it.
Comment: Whats wrong with the standard [`offsetof`](http://en.cppreference.com/w/cpp/types/offsetof)?
Comment: @ChristianRau If the standard doesn't require implementations to document their support, the support isn't implementation-defined. In this case, if an implementation defines the behaviour (and I'm not saying VC does), it's simply a permitted extension. A valid consequence of undefined behaviour is doing exactly what you want.
Comment: @Joachim Pileborg: `offsetof` only works with member names, not with a `M T::*`.
Comment: I'm trying to figure out where in the standard that it says that this does what you expect it does. But I can't find it.
Comment: @NicolBolas I guess it doesn't. Shouldn't the dereference of a `nullptr` (and I think `->` counts as dereference) be UB already? But then again, VC's version of the `offsetof` macro isn't any different. So in practice it's probably rather implementation defined than undefined.
Comment: I thought a `constexpr` function isn't allowed to contain `reinterpret_cast`s or pointer derefs and address operators?
Comment: @hvd The *"implementation-defined"* from my comment was meant in a more informal sense (as introduced by the preceding *"in practice"*). Of course it is and will always be UB and not IB, nobody argues about that.
Comment: @ChristianRau Implementation-defined has a very specific meaning in C++; using it informally with a different meaning isn't wrong, but I did not get from your comment that you were knowingly doing so. It's actually still not clear to me what exactly you did mean: did you mean the VC compiler will not complain about null pointer dereferencing, or did you mean the VC compiler supports null pointer dereferencing? They differ in how safe it is to rely on the current behaviour.
Answer: The following should work (credits go to the answer to this question for the idea):
#include <cstddef>

template <typename T, typename M> M get_member_type(M T::*);
template <typename T, typename M> T get_class_type(M T::*);

template <typename T,
          typename R,
          R T::*M
         >
constexpr std::size_t offset_of()
{
    return reinterpret_cast<std::size_t>(&(((T*)0)->*M));
}

#define OFFSET_OF(m) offset_of<decltype(get_class_type(m)), \
                     decltype(get_member_type(m)), m>()

struct S
{
    int x;
    int y;
};

static_assert(OFFSET_OF(&S::x) == 0, "");

Note that in gcc, the offsetof macro expands to a builtin extension which can be used at compile time (see below). Also, your code invokes UB, it dereferences a null pointer, so even if it might work in practice, there are no guarantees.
#define offsetof(TYPE, MEMBER) __builtin_offsetof (TYPE, MEMBER)

As pointed out by Luc Danton, constant expressions cannot involve a reinterpret_cast according to the C++11 standard although currently gcc accepts the code (see the bug report here). Also, I found defect report 1384 which
talks about making the rules less strict, so this might change in the future.
Comment: A constant expression cannot involve a `reinterpret_cast` (unless not evaluated).
Comment: @LucDanton: Thanks for the info. I also found a [defect report 1384](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1384) that talks about loosening the restrictions about that.
Comment: I've been trying to modify this method to allow OFFSET_OF to accept a pointer to member without success (http://stackoverflow.com/questions/22359535/gcc-can-i-use-offsetof-with-templated-pointer-to-member) - does anyone know if it's possible?
Comment: The made it more strict but both [gcc and clang provide a work-around](http://stackoverflow.com/questions/24398102/constexpr-and-initialization-of-a-static-const-void-pointer-with-reinterpret-cas/24400015#24400015) to use `reinterpret_cast` in a constant expression.
Comment: So you believe your code does not invoke undefined behavior?
Comment: @ShafikYaghmour: Thank you for the information. I do believe my code invokes UB.


Scrapy: how to pass links

Question: I can not pass references. When starting a spider, I'm not getting data
Help with code.
I'm a beginner in Scrapy
import scrapy
from movie.items import AfishaCinema

class AfishaCinemaSpider(scrapy.Spider):
    name = 'afisha-cinema'
    allowed_domains = ['kinopoisk.ru']
    start_urls = ['https://www.kinopoisk.ru/premiere/ru/']

    def parse(self, response):
    links = response.css('div.textBlock>span.name_big>a').xpath(
        '@href').extract()
    for link in links:
        yield scrapy.Request(link, callback=self.parse_moov,
                             dont_filter=True)

def parse_moov(self, response):
    item = AfishaCinema()
    item['name'] = response.css('h1.moviename-big::text').extract()

Answer: The reason you are not getting the data is that you don't yield any from your parse_moov method. As per the documentation, parse method must return an iterable of Request and/or dicts or Item objects. So add
yield item

at the end of your parse_moov method.
Also, to be able to run your code, I had to modify
yield scrapy.Request(link, callback=self.parse_moov, dont_filter=True)

to
yield scrapy.Request(response.urljoin(link), callback=self.parse_moov, dont_filter=True)

in the parse method, otherwise I was getting errors:
ValueError: Missing scheme in request url: /film/monstry-na-kanikulakh-3-more-zovyot-2018-950968/

(That's because Request constructor needs absolute URL while the page contains relative URLs.)

Scrapy: how to pass links


Mark Levine the jazz theory versus the jazz piano book

Question: I currently own the jazz theory book by mark levine. It's very informative and I'm sure it's gonna take me a few years to get the best out of it, but I wonder is it still worth getting the jazz piano book or does it cover most of the same stuff? I'm personally not a very good pianist, but would love to get a better understanding of how to improvise on the piano itself. But I mainly wonder how much different this book is besides the jazz theory book.
Answer: If I'm not mistaken, both of the books have some stuff in common, but the theory is book is focusing solely on theory (duh), whereas the piano book focuses on the piano. The theory book has some stuff about the piano and vice versa, but both have stuff the other book doesn't. I would suggest that if you have the money (they cost around 30-40$ on Amazon), you should buy them both. If not, you could stick with the theory book.
If you want to improve on piano, you should buy it. It has many useful stuff about piano playing that the theory book doesn't.
This link has a brief summary of the book's scope.

Over 300 pages with complete chapters on Intervals and triads, The major modes and II-V-I, 3-note voicings, Sus. and phrygian Chords, Adding notes to 3-note voicings, Tritone substitution, Left-hand voicings, Altering notes in left-hand Stride and Bud Powell voicings, Block chords, Comping ...and much more!


Como colocar dentro de uma variável somente o texto que foi selecionado dentro de uma textarea?

Question: Com
var texto = document.getElementById('texto').value;

consigo tudo que está na tetxarea que tem esse id, mas e se eu quiser um texto parcial?
Por exemplo o texto todo é esse:
Alemanha comprou o jogo contra o Brasil
Se eu selecionar apenas "comprou o jogo", gostaria que minha var tivesse esse conteúdo.
Acrescentado (11/5/15):
Bem, com o "mouseup" o alert funciona, mas assim, se eu simplesmente precisar colocar o valor da seleção dentro de uma variável com
 var textoSelecionado = showSelection(this);

para depois tentar usar este valor?
Meu objetivo final é poder colocar tags HTML ao redor do texto selecionado.
No entanto se eu clicar no link/imagem/botão que realize esta função automaticamente o texto deixa de ser selecionado e pelo que testei a função "showSelection" passa a não ter mais efeito.
Eu imaginei uma forma de tornar funcional isso:
ativando e desativando os botões, então se estiverem ativos ao selecionar o texto no "mouseup" ele sofre as alterações. Se não tiverem ativos não mudam. Seria como controlar se uso ou não a função showSelection. Isso creio que consigo fazer, mas gostaria de reter o texto selecionado para usá-lo ao clicar em um botão ou link.
Comment: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement#Insert_HTML_tags_example
Comment: Acredito que funcione a partir do IE9 visto que são utilizadas as propriedades `selectionStart` e `selectionEnd` e o método `setSelectionRange`.
Comment: Sim, os outros navegadores (firefox, chrome, safari, opera) suportam estas funcionalidades (só não sei quanto as versões mobile).
Comment: Legal, mas é cross browser? pelo que vi na caixa não está marcado a maioria dos navegadores.A não ser que nãos e refira a isso.
Comment: Isso não chega a ser um problema, mas nos demais browsers funciona?
Comment: Já até adaptei o esquema que comentei na pergunta para ativar e desativar os botões, mas essa alternativa que você mostrou pode ser mais prática. Obrigado, vou testar.
Comment: @Oeslei funcionou em todos nabegadores, valeu, como o que estou construindo é para uso de adm, mesmo que não funcione em browsers mais antigos, é só pedir para o usuário atualizar todos os browsers para última versão.
Answer: Encontrei uma resposta no SOen que adaptei. Assim com esta função podes ir buscar o que está selecionado.
HTML
<textarea name="" id="texto" cols="30" rows="10">Texto de exemplo</textarea>

JS
function showSelection(textComponent) {
    var selectedText;
    // IE version
    if (document.selection != undefined) {
        textComponent.focus();
        var sel = document.selection.createRange();
        selectedText = sel.text;
    }
    // Mozilla version
    else if (textComponent.selectionStart != undefined) {
        var startPos = textComponent.selectionStart;
        var endPos = textComponent.selectionEnd;
        selectedText = textComponent.value.substring(startPos, endPos)
    }
    return selectedText;
}

var textarea = document.getElementById('texto');
textarea.addEventListener('mouseup', function () {
    var textoSelecionado = showSelection(this);
    if (textoSelecionado) alert(textoSelecionado);
});

jsFiddle: http://jsfiddle.net/a1tc9984/
Comment: @IWannaKnow mudei a resposta para só dar o texto selecionado.
Comment: Grato, vou estudá-la e já retorno.
Comment: @IWannaKnow é isto que pretendes? -> http://jsfiddle.net/tLbysg4p/
Comment: Isso eu conheço, mas não quero todo o texto, quero parcialmente.
Comment: Já tinha visto algumas dessas funções e lido sobre esse problema de que não há nada crossbrowser, mas li em páginas antigas do Google, imaginei que na atualidade já haveria algo que resolvesse isso. Acrescentei um texto a pergunta.
Comment: Isso eu já fiz. Depois que você mostrou as funções ficou fácil e até acho que seja uma solução viável, mas eu falava de selecionar um texto e modificá-lo ao clicar em um botão.
Comment: Eu usei o "replace" e também ativo ou desativo um botão para que esta função só funcione se o botão desta tag estiver ativado.
Comment: Você viu o link que o @Oeslei postou? https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement#Insert_HTML_tags_example
Comment: @IWannaKnow sim, vi. Isso é uma tecnologia que ainda não está implementada nos browsers. Pode ser que daqui a uns anos seja comum usar. Por enquanto só sei da maneira que coloquei.
Comment: Eu agradeço já foi de grande ajuda, mas testei aqui e funcionou a tecnologia do link.
Comment: @IWannaKnow testa também no IE versão 9, 10 e 11, e testa Safari (Mac) e Firefox. Acho que não vai funcionar na maioria desses.
Comment: Funciona em todos esses: Chrome, FF, IE 11, Safari e Opera. Não tenho como testar nas versões mais antigas, pois atualizo todos os browsers.


Mudando cor do site através de parâmetro GET

Question: Antes de tudo queria informar que eu sou iniciante em programação, estou aprendendo por conta.
Eu tenho uma dúvida, não quero códigos de mão beijada nem nada, apenas uma explicação para que eu possa colocar em prática.
Estava navegando na internet e entrei numa web-rádio, vi que no player deles é possível mudar a cor com um código na URL. Como isso é feito?
http://redeblast.com/player?color=FFCC00
Answer: Isso é feito utilizando a variável global $_GET. Com essa variável você pode identificar os parâmetros utilizados na URL. Ex:
Url: https://www.example.com/?foo=bar
var_dump( $_GET["foo"] ); //Output --> bar

Dessa forma você consegue passar qualquer valor, inclusive você pode utilizar o valor dessa variável em um código CSS
Url: https://www.example.com/?font-weight=bold&bg=F00&color=FFF
PHP 5.6 ou inferior

PHP 7.0 ou superior

Dica: Utilizando os operadores de comparação ou null coalescing operator você definir uma cor ou outra característica padrão, caso o site não receba esses parâmetros.

Porém tenha cuidado como e onde utiliza esses valores. Algumas pessoas utilizam técnicas de Cross-site scripting para ataques.
Answer: Isso é feito pegando o parâmetro da URL com $_GET['color'] e atribuindo a uma variável que será usada no PHP para definir a cor onde quiser. Exemplo:
$cor = $_GET['color'];

A variável $cor poderá ser aplicada no HTML da página onde quiser, por exemplo, como cor de fundo de uma div:
<div style="background-color: #<?=$cor?>">

Como toda cor em hexadecimal é prefixada com #, basta adicionar o valor capturado da URL e acrescentar o símbolo # antes do valor.
Answer: Apenas para complementar a resposta:
O PHP possui outras variáveis com usos semelhantes, o $_GET passa dados através da url, o $_POST passa esses dados "escondidos" (ambos são eliminados ao mudar de página, por exemplo, se você estiver em ex1.php e passar os dados via GET ou POST para ex2.php os dados estarão lá, mas ao ir para ex3.php esses dados não existiram mais, a não ser que vocẽ os reenvie novamente) e o $_SESSION que cria uma sessão com os dados que ficará salvos até ser excluídas (através de código) ou usuário sair do navegador
Essas variáveis são globais (pode ser acessado de qualquer parte do site) e do tipo array, assim para obter um GET, POST ou SESSION você deve passar um nome, por exemplo, $_GET["exemplo"] busca o valor do array get na posição que possui o nome exemplo
Para enviar dados do HTML para o PHP use a tag <form> especificando como você quer enviar os dados no method (POST ou GET), nos input use o atributo name para especificar o nome quando for pegar esse valor por exemplo:
<form action="pagina/de_destino.php" method="POST">
    <input type="text" name="exemplo">
</form>

No PHP use $_GET["exemplo"] para pegar o valor enviado pelo usuário
O SESSION precisa precisa ser criado direto no php, por exemplo:
$_SESSION["exemplo"] = "valor do exemplo";


Redirecionamento HTTP e HTTPS com exceção

Question: Tenho um site em http e adicionei um certificado SSL. Preciso de um script via htaccess que redirecione todo o site para https (redirecionamento 301), porém uma única página especifica do site precisará ser acessada via http:
Exemplo:
https://meusite.com Todas as páginas do site com https
http://meusite.com/pagina-especifica Apenas essa página sem o https
No caso, essa página poderá até ser acessada via https, mas também precisará necessariamente ser acessada via http sem redirecionamento.
Tentei esse código, porém dá erro de excesso de redirecionamento. A intensão seria permitir que a página meusite.com/api fosse acessível tanto via http quanto via https sem redirecionamento.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
RewriteCond %{REQUEST_URI} !^/(api) [NC] #permite tanto acesso via https quanto http
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Esse outro código abaixo funcionou perfeitamente para o redirecionamento 301 do site, entretanto não estou conseguindo incluir a exceção para que a página /api seja também acessível sem o https:
# BEGIN GD-SSL
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_USER_AGENT} ^(.+)$
RewriteCond %{SERVER_NAME} ^meusite\.com$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Header add Strict-Transport-Security "max-age=300"
</IfModule>
# END GD-SSL
# BEGIN WordPress

Comment: Olá @Bacco, obrigado por responder. Adicionei o que tenho pronto para ver se auxilia. Basicamente o que preciso é um código padrão de redirecionamento 301 via htaccess de http para https, porém preciso incluir uma regra para que apenas uma única página especifica do meu site seja acessível também via http, sem redirecionar para https.
Comment: Sua lógica tá indo bem, só que não pode redirecionar de novo se já for HTTP só. Talvez fosse melhor juntar os cond num rewriterule só. Só redirecione se for HTTP, **E** se não for **/api**
Comment: Então, seria justamente isse "E se não foi /api" que não estou conseguindo. Sou novato nisso.
Comment: Olha só realmente existe a necessidade de deixa a API sem HTTPS? Essa API vai dar acesso pra quem? Terceiros ou seu próprio sistema?
Answer: Provavelmente isso resolva. É parecido com a sua primeira versão, mas foi corrigido um != e o https no RewriteRule
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} !^/api.* [NC] #essa linha é a exceção
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Se o redirect não fosse 301, bastaria omitir da flag R:
RewriteRule ^.*$ http://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Veja só um exemplo se a exceção fosse um domínio específico, por exemplo:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC] #exceção pra domain.com
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Notar que foram tirados os parênteses de algumas situações, pois geralmente só se faz agrupamentos quando vai ser usado aquele pedaço no RewriteRule, com os grupos de captura %1, %2 etc.


window.__proto__ equivalent for IE10

Question: I am wondering how to enumerate window functions like setTimeout or alert in IE10. In all other "modern" browsers (inluding IE11) I can get them with:
Object.getOwnPropertyNames(window.__proto__)

But in IE10 window.__proto__ is not defined. As in all other browthers
Object.getOwnPropertyNames(window)

does contain many functions, but not all (including the two mentioned above).
How do I enumerate those in IE10?
Comment: Have you tried `Object.getPrototypeOf(window)`?
Comment: What's bad with good old `for (var i in window) if (typeof window[i] === 'function' && !window.hasOwnProperty(i)) console.log(i);`? You can drop the `hasOwnProperty` check, of course, if that's not what you need. )
Answer: You can get enumerable and non-enumerable properties of the Window object with:
var properties = Object.getOwnPropertyNames(Object.getPrototypeOf(window))

the getPrototypeOf method is available in IE9+.

window.__proto__ equivalent for IE10


Python save to .txt

Question: I have this program to generate random passwords. I'm trying to save it to the directory where the .py file is being executed. I.E if its in desktop i want the new .txt file to be saved in desktop.
This is the code i have tried:
base_dir = os.path.dirname(os.path.realpath(__file__))

text_file = open(r'base_dir + mypassword', 'w')
text_file.write(password)
text_file.close()

Everything seems to be working fine except the part where it actually saves the .txt file with the newly generated password.
Comment: `'base_dir + mypassword'` is a literal string. Get rid of the quotes around `base_dir +`
Comment: Even then, `base_dir + mypassword` is going to need a proper path separator maybe with `os.path.join()`
Answer: You can get the current working directory with os.getcwd(). So you could try something like:
base_dir = os.path.getcwd()
filename = "my_file"

with open(f"{base_dir}/{filename}", 'w') as text_file:
    text_file.write(password)

Note how you can avoid having to deal with .close() your open file using context managers (using with).
Answer: Pathlibs Path is another nice option that will work on all operating systems (the path separator is not the same in linux and windows for example):
from pathlib import Path

with open(Path(filename), 'w') as file:
    file.write(password)

If you create a new Path it will automatically be relative to the current working directory.
Answer: Can you try this:
base_dir = os.path.dirname(os.path.realpath(__file__))
text_file = open(base_dir+'/mypassword', 'w')
text_file.write('password')
text_file.close()

*** changed some code options to this:
base_dir = os.path.dirname(os.path.realpath(__file__))
text_file = open(base_dir + '/mypassword.txt', 'w')
text_file.write(password)
text_file.close()

It's working perfectly now.
Comment: I wrote 'password' as a representative but you are right
Comment: if i write ('password') isnt it just gonna write 'password' rather than the variable containing the actual password?
Comment: i tweeked it around a bit and it worked. im gonna edit your comment

Python save to .txt


blacken screen in iOS while app is running

Question: I want my iPad app to completely blacken the screen but retain all the standard functionality.
I'm doing this to test the non-visual aspects of the app (to test what the app would be like if you were a blind user).
Is this possible?
Comment: Have you considered closing your eyes?
Comment: There are very advanced tools for this kind of test too. For example this one: http://i44.tinypic.com/28auw4p.jpg
Answer: Have you seen Apple's testing guide for accessibly?
https://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/iPhoneAccessibility/Testing_Accessibility/Testing_Accessibility.html
Blind users make use of the phone through an accessibility mode which is quite different and takes care of blanking the screen for you.
Article by Matt Gemmell on accessibility.
Comment: yeah i'm definitely aware of the iOS built in voice over. i'm building my own accessibility settings into the app natively so i'd like a easy way to test it with sighted users who don't want to wear a blindfold
Answer: I found a solution:
http://vectorvector.tumblr.com/post/2130331861/ignore-touches-to-uiview-subclass-but-not-to-its
Basically I create a black view on top of my application and then have that view pass touches to subviews.


Security of storing User object to session

Question: I'm creating my own authentication system (using Java). When user is authenticated and user object is loaded from datastore, it is secure to store this user object to session and assume when user has user object in session, it is real and valid user object that has been obtained by legit login? Are there any possible security issues that I'm not seeing here?
Answer: Session hijacking? Possible SQL injection or XSS on your login page? A man in the middle attack?
Only a few things you should think about when designing a secure login system.
Answer: In principle yes.
You alone are in full control of the session variables (the client has neither read nor wright access to these variables). If the authentication mechanism is circumvented, it is not because the user has set his own session variable (as he could for instance set the content of cookies).
This being said, there are of course ways hack web pages (read up on OWASP top 10, including CSRF, XSS and so on).
Answer: I personally tend to do this on all my web apps but I remove or encrypt sensitive data in the user object before storing it in the session e.g. password
alternative is to populate and use a light version of the user object that will contain only the data you want in the session (i.e user id, first name. last name)
Answer: Adding to all other posts I think there is one more security issue. You are validating user against databaseonly at the time of user logs in and then you set user in session let say when user is logged-in andsession is active in between access is revoked in that case user will have access until his session life which is not acceptable.


Showing that there is a surjective map from $\Bbb Z \ast \Bbb Z$ to $C_2 \ast C_3$ just using universal property of coproduct

Question: I am solving Allufi chapter $0$ exercise $3.7$. There is a easy way to solve this if we know how the coproduct of $\Bbb Z \ast \Bbb Z$ and $C_2 \ast C_3$. I was wondering if there is an abstract approach to solving this without knowing information about the groups.
Comment: Well morally you should know _some_ information about the groups. Otherwise this would work for any such collection of groups. That would imply some rather bogus results.
Comment: I think I figured it out. I will post answer as soon as I finalize the solution. It is pretty neat.
Answer: First, let $T:\mathbf{C}\to\mathbf{D}$ be a left-adjoint covariant functor from a category $\mathbf{C}$ to a category $\mathbf{D}$, that is, there exists a covariant functor $S:\mathbf{D}\to\mathbf{C}$ such that $$\text{hom}_\mathbf{D}\big(T(x),y\big)\cong\text{hom}_\mathbf{C}\big(x,S(y)\big)\text{ for all }x\in\mathbf{C}\text{ and }y\in\mathbf{D}\,.$$
We claim that $T$ preserves epimorphisms.  Suppose that $f:x\to x'$ is an epimorphism of objects $x,x'\in\mathbf{C}$.  Then, $T(f):T(x)\to T(x')$ is an epimorphism if and only if
$$\text{hom}_\mathbf{D}\big(T(x'),y\big)\overset{F}{\longrightarrow }\text{hom}_\mathbf{D}\big(T(x),y\big)$$
is an injective function, where $F(\phi):=\phi\circ T(f)$ for all $\phi\in \text{hom}_\mathbf{D}\big(T(x'),y\big)$.  By left-adjointness of $T$, $F$ induces a map
$$\text{hom}_\mathbf{C}\big(x',S(y)\big)\overset{F'}{\longrightarrow}\text{hom}_\mathbf{C}(x,S(y)\big)\,,$$
where $F'=\psi\circ f$ for all $\psi\in \text{hom}_\mathbf{C}\big(x',S(y)\big)$.  As $f$ is an epimorphism, $F'$ is an injective function, and so is $F$.  Therefore, $T(f)$ is also an epimorphism.
Fix an index set $I$.  Let $\mathbf{D}$ be the category of groups (or any category that admits coproducts on the index set $I$), and $\mathbf{C}$ the product category $\prod\limits_{i\in I}\,\mathbf{D}$.  That is, the objects of $\mathbf{C}$ are families $(G_i)_{i\in I}$ of objects in $\mathbf{D}$ and morphisms from an object $(G_i)_{i\in I}$ of $\mathbf{C}$ to an object $(H_i)_{i\in I}$ of $\mathbf{C}$ are the families $(\phi_i)_{i\in I}$ of morphisms $\phi_i:G_i\to H_i$ in $\mathbf{D}$.  Note that $(\phi_i)_{i\in I}$ is an epimorphism in $\mathbf{C}$ if and only if each $\phi_i$ is an epimorphism.
Take $T:\mathbf{C}\to\mathbf{D}$ to be the $I$-coproduct functor:
$$T\Big(\left(G_i\right)_{i\in I}\Big):=\coprod_{i\in I}\,G_i\text{ for all }G_i\in \mathbf{D}\text{ where }i\in I\,.$$
Then, $T$ is a left-adjoint covariant functor, with the right adjoint being $S:\mathbf{D}\to\mathbf{C}$ defined by
$$S(G):=(G)_{i\in I}\text{ for each }G\in \textbf{D}\,.$$
Thus, $T$ preserves epimorphisms.
On the other hand, it is an unrelated happy coincidence that $T$ also preserves monomorphisms in the case $\mathbf{D}$ is the category of groups.  This is not true in the general setting.  For reference, see here.
Comment: Outstanding pretty neat thank you.
Answer: Do you mean something like this?  Let $\phi_1:G_1\to H_1$ and $\phi_2:G_2\to H_2$ be homomorphisms of groups $G_1$, $G_2$, $H_1$, and $H_2$.  Then, $\phi_1$ and $\phi_2$ induces a group homomorphism
$$\phi:=\phi_1*\phi_2:(G_1*G_2)\to (H_1*H_2)$$
defined by
$$\phi(g_1^1g_2^1g_1^2g_2^2\cdots g_1^kg_2^k):=\phi_1(g_1^1)\,\phi_2(g_2^1)\,\phi_1(g_1^2)\,\phi_2(g_2^2)\,\cdots \,\phi_1(g_1^k)\,\phi_2(g_2^k)$$
for all $g_1^1,g_1^2,\ldots,g_1^k\in G_1$ and $g_2^1,g_2^2,\ldots,g_2^k\in G_2$.  The map $\phi$ is injective if and only if both $\phi_1$ and $\phi_2$ are injective.  The map $\phi$ is surjective if and only if both $\phi_1$ and $\phi_2$ are surjective.

 Proof.  Let $\iota_1$ and $\iota_2$ denote the canonical injections $G_1\to (G_1*G_2)$ and $G_2\to (G_1*G_2)$, respectively.  Similarly, $i_1:H_1\to (H_1*H_2)$ and $i_2:H_2\to(H_1*H_2)$ are the canonical injections.  We note that there exist maps $\psi_1:=i_1\circ \phi_1:G_1\to (H_1*H_2)$ and $\psi_2:=i_2\circ\phi_2:G_2\to (H_1*H_2)$.  By universality of coproducts, there exists a unique map $\phi:(G_1*G_2)\to (H_1*H_2)$ such that $\phi\circ\iota_1=\psi_1$ and $\phi\circ\iota_2=\psi_2$.  Check that $\phi$ is the map given above.  The rest (regarding injectivity or surjectivity of $\phi$) is trivial.
Comment: I was wondering can we get surjectivity for free? What if we don't know how the free product looks like ?
Comment: @Newbie  Yes, see my additional answer.


jQuery check an hidden checkbox onclick

Question: I am on jQuery 1.3.2
I need a very simple code.
I have 4 checkboxes.
One of these checkboxes is hidden.
I want that when one of the 3 visible checkboxes is clicked the hidden one will be automatically checked.
So I have
<input type="checkbox" style="display:none" id="hiddenOne">
<input type="checkbox" style="display:block" id="visible2">
<input type="checkbox" style="display:block" id="visible3">
<input type="checkbox" style="display:block" id="visible4">

So if I click on any visible2 3 or 4 the hiddenOne will be automatically checked.
Is there a way to do that in jQuery?
Thank you!
Comment: Do you want to clear the hidden checkbox if all the visible ones are clear?
Comment: Yes that would be great too. So check the hidden one when one of those visible is checked. Uncheck the hidden one when no of those visible is checked. That would be fanstastic. If you can help me I will give you a point and an accepted answer =D. Thank you
Answer: this will check if any of the three visible's are checked, if any are then show the hidden one and check it.
http://jsfiddle.net/pxfunc/S6SFZ/
HTML:
<input type="checkbox" id="hiddenOne"> Hidden One
<input type="checkbox" id="visible2" class="visiChk"> Visible 2
<input type="checkbox" id="visible3" class="visiChk"> Visible 3
<input type="checkbox" id="visible4" class="visiChk"> Visible 4

jQuery:
// update if any of the three are checked/unchecked
$('.visiChk').change(function() {
    var hiddenOne = $('#hiddenLabel')[0];

    // Are any of them checked ?
    if ($('.visiChk:checked').length > 0) {
        hiddenOne.style.display = 'block';
        hiddenOne.checked = true;
    } else {
        hiddenOne.style.display = 'none';
        hiddenOne.checked = false;
    }
});

Comment: It does not seem to work. The hidden checkbox is not checked. This is also visible in your demo. It just shows, but it is not checked at all

jQuery check an hidden checkbox onclick


postinst script in hand-rolled .deb reported not found

Question: I had a quick dpkg/debian-izing question. I am trying to create a .deb(by hand - mostly for learning purposes) and I have rolled up an ar-chive with the control.tar.gz, data.tar.gz and the debian-binary files.
This hand-rolled .deb works fine for regular installs, purges et al. However when I specify an --instdir at install time, dpkg reports a 'file not found' error when trying to run the postinst script. This is not an issue with the prerm script, btw(which works fine).
Running dpkg with --debug=2000 and looking at /var/log/dpkg.log didn't help much.
Any thoughts on why this could be happening?
TIA.

To give some more context and pose another question: I am trying to get --instdir to work mostly because the top level directory to which my package contents get installed is also a mount point and on doing dpkg -P foo, dpkg attempts to remove this directory. If anyone can suggest a workaround for this, that would serve my purpose too(i.e. I wouldn't need --instdir to work). Also, this top-level directory is not empty, so not sure why dpkg is attempting to remove it. Putting a .placeholder file in there didn't help either.
Answer: As it is listed here (https://stackoverflow.com/questions/8921626/run-time-installation-directory-of-debian-package-contents) dynamic directory paths are not supported in deb packages with prepackaged binaries. But you can specify the directory path not at runtime but in your control file. And for easy making of packages you can use some graphical tools (ex., mentioned here: https://askubuntu.com/questions/8055/graphical-tool-for-creating-deb-packages).


How to send a newsletter to all email addresses attached to a content type?

Question: I have a content type (customers) having an email field (field_email). I need to create a newsletter using those emails that every certain period increase.
I try to use the module Newsletter but I must to re-enter all emails again and new email every time a new customer is registered.
Is there a way to import all emails from my content type, to list the newsletter module?
Answer: Unfortunately, it doesn't look like Newsletter supports that.
On the other hand, the Simplenews module has decent Rules support which may make managing your subscribers easier. As far as I know a user account isn't required to subscribe.
Off the top of my head, here is an example of a rule that might automatically add an email address to a subscription list when a new 'Customer' node is created:

IF
  (condition) 'After saving new content' (node is created)
AND
  (condition) 'Entity is of type' (node is 'Customer' type)
AND
  (condition) 'Entity has field' (node has 'email' field)
THEN
  (action)  'Set a data value' (get value of email field)
THEN
  (action)  'Subscribe an e-mail address to a newsletter'

(The full implementation is beyond the scope of this answer but there are plenty of other posts dealing with Rules.)
As for importing email addresses, in both of the 7.x branches there is a "mass subscribe" option at People > Subscriptions.


this.setState is not a function but should be within scope

Question: Given my component, when I try to change an input I get the error "this.setState() is not a function."  As far as I can tell, it's within scope, so I'm not sure why it cant find it.  I tried binding the function within the constructor, but it yielded the same results.
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

class UpdateTab extends Component {
    constructor(props) {
        super(props);
        const {settings} = this.props;

        this.state = {
            version_text: "",
            version_description: "",
            accepted: [],
            post_changes_to_comments: settings.post_changes_to_comments,
        };
    }

    componentDidMount(){
        const {settings} = this.props;
        this.setState = ({
            post_changes_to_comments: settings.post_changes_to_comments,
        });
    }

    handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        this.setState({
            [name]: value
        });
    }

    handleSubmit(e){
        console.log("working");
        e.preventDefault();
        const values = {
            version_number: this.state.version_text,
            version_description: this.state.version_description,
            file: this.state.accepted

        };
        this.props.saveUpdate(values)
    }

    render() {
        const placeholder = "This section is to highlight the changes in the updated \n" +
            "version of the document.\n" +
            "\n" +
            "This will appear in the comment section unless disabled within the "Edit" tab.";
        return (

                <form>

                                Version Number

                                    <input value={this.state.version_text}
                                           onChange={(e) => this.handleInputChange(e)}
                                           name="version_text"
                                           placeholder="eg. 1.0"/>

                                Description of Changes

                                    <textarea value={this.state.version_description}
                                              className="description-of-changes-textarea"
                                              onChange={(e) => this.handleInputChange(e)}
                                              name="version_description"
                                              placeholder={placeholder}/>

                                <input name="post_changes_to_comments"
                                       type="checkbox"
                                       checked={!this.state.post_changes_to_comments}
                                       onChange={(e) => this.handleInputChange(e)}/>
                                Do not display this description of changes in SRD comments

                    <button className="button-filled center" onClick={(e) => this.handleSubmit(e)}>Update</button>

                </form>

        );
    }
}

function mapStateToProps(state) {
    return {
        settings: state.settings,
    };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        saveUpdate: saveUpdate,
    }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(UpdateTab);

Any help as to why "this.setState" is not visible within my input change handler would be greatly appreciated.
Answer: Here
this.setState = ({
   post_changes_to_comments: settings.post_changes_to_comments,
});

You are overwriting setState. You know, move to
this.setState({
   post_changes_to_comments: settings.post_changes_to_comments,
});


the proof of the measurability of a sequence of monotone functions.

Question:

I understand that $E_{kn}$ is disjoint and the union of $E_{kn}$ is equal to $X$. But, I don't understand that the next sentence "If we define $\varphi_n$ to be equal to $k2^{-n}$ on $E_{kn}$, then $\varphi_n$ belongs to $M(X, \mathbf{X})$".
Could you elaborate on this?
Comment: $\phi_n$ is the sum of multiples ($k 2^{-n}$) of characteristic functions of measurable sets ($E_{kn}$). The characteristic functions are measurable, multiples of measurable functions are measurable and sums of measurable functions are measurable.
Answer: The whole construction of $\phi_n$ boils down to:$$\phi_n(x):=\min\left(2^{-n}\lfloor2^nf(x))\rfloor,n\right)$$
It is immediate that for every $n$ the image of the function $\phi_n$ is finite.
Then if $I$ denotes the image of $\phi_n$ for every element $p\in I$  the set $\phi^{-1}(\{p\})$ is measurable.
We have:$$\phi_n=\sum_{p\in I}p1_{\phi^{-1}(\{p\})}$$where $I$ is finite and the sets $\phi^{-1}(\{p\})$ are measurable, are disjoint and cover $X$.
Note that the inverse image of every set wrt $\phi$ is a finite union of measurable sets of the form $\phi^{-1}(\{p\})$ hence is measurable.
This makes clear that such a function is measurable.


Trying to serve IIS files on a Mac - IIS seems to see directory structure but not individual files

Question: So I've got a bit of a frankenstein setup - I am migrating a client's fairly old tech infrastructure (which is fairly extensive, it's a whole technology-based business) from Classic ASP to more modern architecture.
I am trying to replicate their current setup locally. The biggest problem is that to run Classic ASP, I need to do so on Windows - I am on an M Series (ARM-based) Mac. I've got a Windows 11 virtual machine running just fine and I've got IIS working and serving up files, however the problem is that when I try to serve files over a network drive (which is how the technology I am using represents my Mac's hard drive to Windows), I am getting:
<code>HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
</code>

Now I can see, and even access the files on the network drive with no problem otherwise. IIS theoretically seems to see them. IIS shows a directory of correct file names, but whenever I click one, I get the above 404 error. So somehow it is able to see the files as a directory tree, but not to serve them? It's unclear why.

If anyone has any idea why IIS would see the files in a directory structure, but not be able to serve any of them, please let me know. I imagine it's some sort of permissions or file routing issue. Unfortunately I'm not really an IIS guy - most of my devops/sysadmin type stuff has been on Linux boxes.
Comment: Try registering ASP.NET with IIS, as the failure mode you describe seems identical to that described in the documentation: https://learn.microsoft.com/en-us/aspnet/web-forms/overview/deployment/configuring-server-environments-for-web-deployment/configuring-a-web-server-for-web-deploy-publishing-web-deploy-handler#install-products-and-components
Comment: > If you installed the .NET Framework 4.0 before you installed IIS, you'll need to run the ASP.NET IIS Registration Tool (aspnet_regiis.exe) to register the latest version of ASP.NET with IIS. If you don't do this, you'll find that IIS will serve static content (like HTML files) without any problems, but it will return HTTP Error 404.0 – Not Found when you attempt to browse to ASP.NET content.
Comment: @neuro CLASSIC ASP, nothing .NET. We're talking exclusively 1999 stuff. This site should have been updated 15 years ago.

And static content also fails with the exact same error, so it's definitely not this. If I navigate to a plain HTML file, I get the exact same error
Comment: The ONLY thing that works is directory structure. Both ASP files as well as static content like HTML files DO NOT.
Comment: If you relied on the virtual machine solution to serve your files from Mac to Windows, then IIS dislikes that (and does not support any kind of mapped drives). For IIS sites on Windows, use local drives and local folders.
Comment: Can you change the application pool user to somebody with more access? But I would strongly recommend just copying the files to the local disk. And could you show the acl on the network files?
Comment: @LexLi Is there anyway to trick IIS? I'd prefer my file management to be on my Mac so that I don't need to have my VSCode pointing in some weird directory that is different from the rest of my work. Would symlink folders work?
Comment: @user189695 I can theoretically change anything - it's all on my local machine, I'll have to look into doing that for the application pool user - I am not super adept with IIS at this point but since it's all local and I am the only person with access to this device or VM, I have no issue even giving it full admin privs theoretically if necessary
Comment: The limitation has been well known for more than two decades, and you won't be the last to ask.
Answer: You can't. The VM layer is mounting the "network drive" through it's local pipeline, which is startet in user context. Nice for browsing files, when you ar a user, nice for browsing when you point a user context to that drive.
IIS is running in kernel mode (http.sys) and it's services are running in system context. They don't know anything about your userspace drives and never will. For security reasons, IIS will never execute any serveable content from such a local redirected drive.
Solution: Copy the files to a [IIS] local directory.
I am very sorry that there are no tricks to overcome this (from which I have ever heard).


Just want to make it clear for the Defintion of Splitting Field

Question: If $E = \mathbb{Q}(\alpha_1, \alpha_2, \alpha_3)$ the splitting field of $f(x)$ over $\mathbb{Q}$.
Then, does that have to be the case which $\alpha_1$, $\alpha_2$ and $\alpha_3$ are distinct roots of $f(x)$ ?
And also, does that have to be the case which $\alpha_1$, $\alpha_2$ and $\alpha_3$ are the only roots of $f(x)$ ?
Answer: No, it only means that $f(x)$ splits into linear factor in $E$ and in no proper subfield  of $E.$
For example, $\mathbb Q(\sqrt 2,\sqrt 3)$ is the splitting field of $f(x)=x^4-10x^2+1.$ Neither $\sqrt 2,\sqrt 3$ are roots of $f(x).$ (The roots are $\pm\sqrt 2\pm \sqrt 3.$)


Kotlin, Spring Boot, JPA - take value of a Generic Enum (E.valueOf(stringValue))

Question: Background
I'm developing a Spring Boot application and I'm using Kotlin, IntelliJ and Gradle (Groovy). I have some enum class in my code and I need to persist them (with JPA). I used a simple global converter.
// Sample Enum
enum class Policy {
    PUBLIC,
    INVITE_ONLY
}

// Sample Converter
@Converter(autoApply = true)
class PolicyConverter : AttributeConverter<Policy, String> {
    override fun convertToDatabaseColumn(attribute: Policy): String {
        return attribute.name
    }
    override fun convertToEntityAttribute(dbData: String): Policy {
        return Policy.valueOf(dbData.toUpperCase())
    }
}

Problem
Since I have 5-6 enums and I hate duplicated code, I thought about a generic converter that should do the work for every given enum. I tried to code something, but nothing worked. This is what I was thinking about:
abstract class EnumConverter<E: Enum<E>> : AttributeConverter<E, String> {
    override fun convertToDatabaseColumn(attribute: E): String {
        return attribute.name
    }

    override fun convertToEntityAttribute(dbData: String): E {
        return E.valueOf(dbData.toUpperCase())
    }
}

In this way I can only extend from one abstract class every enum converter, like so:
@Converter(autoApply = true)
class PolicyConverter : EnumConverter<Policy>() {}

Problem with this code is that I have two errors:

E is red because: Type parameter 'E' cannot have or inherit a companion object, so it cannot be on the left hand side of dot
valueOf is red because: unresolved reference (there are like 150+ types of .valueOf).

As suggested from this I tried to use following function:
private inline fun <reified E : Enum<E>> getValue(string: String): E {
    return enumValueOf(string.toUpperCase())
}

But when called from the .convertToEntityAttribute, the result is that "Cannot use 'E' as reified type parameter. Use a class instead."
Question
So the question is simple: how can I implement an easy and fast way to make one converter for all my enums, that all follows the same principle? I just need a return E.valueOf(<value>) function, but it's not present.
Answer: A simply workaround of this problem is to define an abstract method that every class will implement and it will return the correct type, given a string.
// Inside EnumConverter, the Generic Class
abstract class EnumConverter<E: Enum<E>> : AttributeConverter<E, String> {
    abstract fun getValueFromString(string: String) : E

    override fun convertToEntityAttribute(dbData: String): E {
        return getValueFromString(dbData)
    }
    [...]
}

// Inside Policy Enum, implementing
class PolicyConverter : EnumConverter<Policy>() {
    override fun getValueFromString(string: String): Policy {
        return Policy.valueOf(string.toUpperCase())
    }
}

But it's a workaround that I really dislike.


Associating nodes to a user

Question: I'm trying to create a Parish website. I have a list of parish members with email ids and without email ids. I've imported the users with email addresses as users, and the rest as nodes. Members that belongs to same family shares a common family code, and when a user log in I want to have a view of all family members and their necessary details (i.e. address,phone no,etc).
But the problem I have is that some users are created using user import and some (people without email) are created as nodes.
So how can I display all the members with same family code in a single view? How to relate a user with another user/nodes.
Is it with contextual filters/relationships? I tried with it but couldn't get it.
Answer: Firstly you must make all users users and not nodes. Somebody I know recently had an issue where users didn't have email addresses. His solution was to create fake email ids for those users since having an email id is mandatory for an account on a Drupal site.
Once you have everyone as users, I think you can add relationships between users using this module - User Relationships and hence easily show related users in views.

Associating nodes to a user


Proof of Simplification of Conditional Expectation of Product of Random Variables

Question: Could someone please provide detailed steps to prove or disprove the following?
$E[XY\mid XY>k] = E[XE[Y\mid XY>k]]$
Here, $X,Y$ are random variables that could be discrete or continuos and follow any probability distribution. $E$ is the expectation operator. $k$ is a constant.
As forum members have provided their feedback, a few interesting cases arise and are worth looking into.
CASE 1
If $X$ and $Y$ are dependent. Is the above identity true?
CASE 2
If $X$ and $Y$ are independent, and could be from any distribution. Is the above identity true?
CASE 3
How about the popular normal distribution? If $X$ and $Y$ are normally distributed, is the above identity true?
CASE 4
How about if one of them is normally distributed and the other is log-normal? Say, $X$ is normal and $Y$ and is log-normal, is the above identity true?
STEPS TRIED
A very rough sketch of the proof as given by another forum member:
$$E[XY\mid XY\in B] = \int\int_B xy f_{XY\mid B}\,dx\,dy = \int y \Big(\int x f_{X\mid B}\,dx\Big) f_Y\,dy$$
RELATED QUESTION
The above question is a generalization of a key step required in the simplification of this question: Conditional Expected Value of Product of Normal and Log-Normal Distribution
Comment: Suppose $X$ is non-constant and has a finite lower bound $L$, so that $\Pr(X\lt L)=0$. Let $Y=X$. When $k\lt 0$, $XY=X^2\gt 0\gt k$, whence $$\mathbb{E}(XY|XY\gt k)=\mathbb{E}(XY)=\mathbb{E}(X^2)$$ while $$\mathbb{E}(X\,\mathbb{E}(Y|XY\gt k))=\mathbb{E}(X\,\mathbb{E}(Y))=\mathbb{E}(X)\mathbb{E}(X)=\mathbb{E}(X)^2.$$ If these two expressions were equal, $$\text{var}(X)=\mathbb{E}(X^2)-\mathbb{E}(X)^2=0,$$ implying $X$ is constant. **This contradiction shows the assertion is not generally true when $Y$ and $X$ are dependent.**  It could hold by accident for particular $X,Y$ and $k$  however.
Comment: @Whuber. Much appreciated thanks ... 1) To confirm if $X$ and $Y$ are independent the identity in the question holds for all values of $X$ and $Y$.  2) How do you get E(XY|XY>k)=E(XY) and E(Y|XY>k)=E(Y) and E(XE(Y))=E(X)E(X)? Could you please elaborate?
Comment: For $k\lt 0$ the event $XY\gt k$ is the universal event of probability $1$, whence conditioning on it changes nothing.
Comment: @whuber. Thanks for the clarification. To confirm, if $X$ and $Y$ are independent does the identity in the question hold for all values of $X$ and $Y$.
Answer: The equation is not true even when $X$ and $Y$ are independent.

Suppose, for instance, that $X$ and $Y$ are positive variables with an Exponential distribution.  For any $k\gt 0$ and $X\gt 0$ we can easily work out that
$$\mathbb{E}(Y\,|\, XY \gt k)  = \frac{\int_{k/X}^\infty y \exp(-y)dy}{\int_{k/X}^\infty \exp(-y)dy}=\frac{\exp(-k/X)(1+k/X)}{\exp(-k/X)}= 1 + \frac{k}{X}.$$
Therefore
$$\mathbb{E}(X\, \mathbb{E}(Y\,|\, XY \gt k)) = \mathbb{E}\left(X\left( 1 + \frac{k}{X}\right)\right) = \mathbb{E}(X + k) = k+1.$$
On the other hand,
$$\mathbb{E}(XY\,|\, XY \gt k) = \frac{\iint_{xy\gt k}xy \exp(-x-y) dx dy}{\iint_{xy\gt k}\exp(-x-y) dx dy}.$$
After integrating over $y$ (from $k/x$ to $\infty$) and substituting $t = x/\sqrt{k}$, both integrals can be related to the modified Bessel function of the second kind, $K_n$ (for $n=1, 2$):
$$\iint_{xy\gt k}xy \exp(-x-y) dx dy = 2 k \left(\sqrt{k} K_1\left(2 \sqrt{k}\right)+K_2\left(2
   \sqrt{k}\right)\right),$$
$$\iint_{xy\gt k}\exp(-x-y) dx dy = 2 \sqrt{k} K_1\left(2 \sqrt{k}\right).$$
Therefore
$$\mathbb{E}(XY\,|\, XY \gt k) = k+\frac{\sqrt{k} K_2\left(2 \sqrt{k}\right)}{K_1\left(2 \sqrt{k}\right)}.$$
Asymptotically as $k$ grows large,
$$ k+\frac{\sqrt{k} K_2\left(2 \sqrt{k}\right)}{K_1\left(2 \sqrt{k}\right)} = k + \sqrt{k} + \frac{3}{4} + O(k^{-1/2}),$$
showing that it cannot equal $k+1$ for all $k$.  Therefore the equation of the question is not true.
Comment: I think there is a mistake on the first line. $\infty>E[Y] = E[E[Y\mid A]] = E[1 + \frac{k}{X}] = \infty$.
Comment: @Hunaphu Please explain what "$A$" is in your assertion, because I cannot match what you have written with anything that appears in this answer.
Comment: @whuber Please note, I added a few cases in the question (some unresolved) since I think these might be of interest to anyone following this topic, also for completeness, and to link it back to the question where this came up from. Hence, please add anything as you see fit.
Comment: @Hunaphu Could you please clarify whether the assertion at the top (The main question here) holds in all the four cases (as framed in the question). I am not sure if you remember, but this is from the steps you had out lined for the simplification of the following question: http://stats.stackexchange.com/questions/157954/conditional-expected-value-of-product-of-normal-and-log-normal-distribution


Conditional distribution of product of two random variables given one of the random variables

Question: Let's say I have two independent random variables $X$, $Y$. Let's define a new random variable $Z = XY$. I know that the distribution of $Z$ follows: $f_{Z}(z) = \int_{-
\infty}^{\infty}f_{X}(x)f_{Y}(z/x)\cfrac{1}{|x|}$.
Is it possible to derive the algebraic expression for $f_{Z|Y}$ in terms of $f_{Z}$, $f_{X}$, and/or $f_{Y}$?
Comment: The answer is the same as that to [your previous question:](https://stats.stackexchange.com/questions/619578/) take out what is known to conclude that $f_{Z\mid Y=y}$ is the density of $Xy.$
Comment: Thanks again @whuber so if I'm understanding you correctly, you are saying that $f_{Z|Y}(z) = f_{X}(z/y)$?
Comment: No, because you have forgotten about the Jacobian.
Answer: Start with the conditional cdf of $Z|Y$:
\begin{align}
P(Z\le z | Y=y) &= P(XY \le z | Y=y) \\
&= P \left( X \le \frac{z}{y} \right)
\end{align}
Then differentiate to find
$$f_{Z|Y}(z|y) = \frac{1}{y} f_X \left( \frac{z}{y} \right) $$
EDIT: This proof relies on the assumption that $X$ and $Y$ are positive. It can be adjusted if this assumption does not hold.
Comment: @AndrasVanyolos: Which notation do you prefer?
Comment: The derivation is intuitive and the final result is correct. Note, however, that in OP the random variates are implicitly assumed to be continuous, in which case the notation above is slightly sloppy as the conditional probabilities with $Y=y$ are both zero (being Lebesque measure zero). This is just notation though and can be fixed easily.


How can I use the chart.addButton() method?

Question: A Highcharts chart object has an addButton() method that seems to be undocumented in the Highcharts API. I assumed it would support the usual button options from navigation.buttonOptions so I experimented with this:
    chart.addButton({
            customButton: {
                text: 'Test',
                onclick: function () {
                    alert('clicked');
                },
                symbol: 'circle'
            }
        });

It creates a new (invisible!) button to the left of the Export contextButton but seems to have ignored all my options. Although the button is rendered invisible, it is highlighted on mouseover. But when I click on it, Highcharts generates the error "TypeError: d is undefined".
If someone has got this working, I'd appreciate some guidance. Thanks.
Comment: For me it works, make sure you have loaded exporting.js file, see: http://jsfiddle.net/3bQne/262/
Comment: @PawełFus: Thanks! My error was the use of {customButton: {}} wrapping the options.
Answer: Buttons created in that way are accessible only via chart.exportSVGElements, see: http://jsfiddle.net/3bQne/288/
To update title or fill color use attr(options).
    var l = chart.exportSVGElements.length,
        button = chart.exportSVGElements[l - 2], //-2 because structure is: [button, symbol, button, symbol ...]
        symbol = chart.exportSVGElements[l - 1];

    button.attr({
        title: "New title!"
    });
    symbol.attr({
        fill: "green"
    });

Comment: Works perfectly. Thanks. One difference. My button & symbol were in positions 0 & 1 of the array, presumably because I call addButton() in a callback from the Highcharts.Chart() constructor, rather than in a function assigned to the load event.

Do you know if it's possible to change the symbol?
     symbol.attr({symbolName: "square"});
changes the attribute in the object but doesn't have any effect on the screen. Thanks again.
Comment: It's not possible. I think you should just remove that button and create new one..


How to prove $\cos(x)=\cos(-x)$?

Question: Couldn't I just argue with the definitions $\cos(z):=\frac{1}{2}(e^{iz}+e^{-iz})$?
So $\cos(z):=\frac{1}{2}(e^{iz}+e^{-iz})=\frac{1}{2}(e^{-iz}+e^{iz})=\cos(-z)$
???
Comment: Mh, a correct definition would be better...
Comment: There are some issues with the question: there are $x$ and $z$ in the equations and only one of the := signs is correct.
Comment: now the definition is correct.
Comment: If that is your definition then yes you can do that.  But if this is an earlier course and $\cos$ has a geometric interpretation you can use symmetric reflexivity of a circle.  How you prove it depends entirely on your definitions and context.
Comment: sorry, I am a little off today.
Answer: Since you are told that the definition of cosine is $$\frac12\left(e^{ix} + e^{-ix} \right),$$
yes, you have proven it by using commutative property. Note that there is a slight inconsitency for confusing $z$ with $x$.
Comment: I would say it's rather $e^{ix}$ than $e^x$ (and the same concerning $e^{-x}$).
Comment: thanks for pointing that out.
Answer: There is nothing wrong with your argument, although some of the notation is wrong, as long as that identity has not been used in the proof that formula, which it has not. There are a plethora of other ways to prove this, though.

How to prove $\cos(x)=\cos(-x)$?


Using reset css - any reasonable drawbacks/counterarguments?

Question: So far, including a CSS reset was a standard step for me at the very beginning of web page designing.
I heard once the opinion that this is bad; however I had no opportunity to ask the guy who said that for the reasons.
Now I'd like to know what drawbacks can you specify.
Comment: I don't really want to talk about CSS frameworks. the difference between the reset and the complete css framework is the overhead which comes with the layout / grid styles.
Comment: I'm sorry, I must have been sleeping. Resets, however, have also been discussed before, even more extensively than frameworks. This is probably the best one: http://stackoverflow.com/questions/167531/is-it-ok-to-use-a-css-reset-stylesheet more here: http://stackoverflow.com/search?q=css+reset
Comment: possible duplicate of [Are CSS Frameworks Really Worth Using?](http://stackoverflow.com/questions/506523/are-css-frameworks-really-worth-using)
Comment: Good question but already discussed several times. See also http://stackoverflow.com/search?q=css+frameworks
Comment: I don't see any specifically asking for drawbacks though. I'd keep this question.
Answer: Using a CSS reset means you, in many cases, will have many rules that are not necessary. You will first set body { margin: 0; padding: 0; } in reset.css and then set body { margin: 0 auto; padding: 20px; } in style.css or something, when only specifying the latter would give the same result. And will you really use all those obscure elements that are included in the reset?
What I sometimes do is that I add a reset.css, start coding, and then I check my page in Dragonfly or Firebug and there I will see which rules from reset.css are overridden. Those I can remove from reset.css, and in the end the file is likely to be very small or empty.
Comment: Your method sounds good. One question though — how big is the "unnecessary rules" issue? Have you saved a lot of bandwidth removing the overridden rules? I would have thought with any reasonably substantial stylesheet, it'd be a pretty small percentage.
Answer: I dont think there is any problems with css resets as a concept.
The only problem maybe using the wrong reset like the * reset which may have performance penalty for the browser.
If using something like Eric Meyer's css reset  http://meyerweb.com/eric/tools/css/reset/index.html then you wont have any problems.
The other advice is you can tweak the reset to your specific needs and not treat it as a read only file :).


Getting error You are not authorized to access this page in custom module

Question: I have a custom module which previously working fine before adding its view part.
form_example.module
   <?php
function form_example_permission() {
  return array(
    'submit form_example' => array(
      'title' => t('Submit form_example'),
      'description' => t('Submit the form_example form'),
    ),
    'access form_example submissions' => array(
      'title' => t('Access form_example submissions'),
      'description' => t('Access the form_example submissions'),
    ),
  );
}
function form_example_menu() {
  $items = array();

  $items['form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit form_example'),
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'),

      );

 $item['form-submissions'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_submissions',
    'access callback' => TRUE,
    'access arguments' => array('access form_example submissions'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['file'] = array(
  '#weight' => '2',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
 $form['submit'] = array(
     '#weight' => '3',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('
'.print_r($form_state['values'],1).'
');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

function form_example_form_submit($form, &$form_state) {
   $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));

 $fe_id = db_insert('form_example')
        ->fields(array(

          'empcode' => $form_state['values']['empcode'],
          'empname' => $form_state['values']['empname'],
          'empphoto' => $file->filename,
        ))
        ->execute();
        drupal_set_message(t('Successfully added'));

}
/*function form_example_list(){
    //$form_example =drupal_get_form('form_example_search_form');
    // If wants to implement searching.
    //$content = '
'.drupal_render($form_example).'
';
    //$content .= '

';
    $header = array(
        array('data' => t('empcode'), 'field' => 'empcode', 'sort' => 'asc'),
        array('data' => t('empname'), 'field' => 'empname'),
        //array('data' => t('empphoto'), 'field' => 'empphoto'),
    );

    $query = db_select('form_example', 'pd');
    if(isset($_GET['empcode']) && $_GET['empcode'] != ''){
        $query->condition('pd.empcode', $_GET['empcode'],'=');
    }
    if(!empty($_GET['empname'])){
        $query->condition('pd.empname', $_GET['empname'],'=');
    }
    $query->fields('pd');

    $table_sort = $query->extend('TableSort')->orderByHeader($header);
    $pager = $table_sort->extend('PagerDefault')->limit(10);

    $result = $pager->execute();
    $rows = array();

    foreach($result as $res){
      $rows[] = array($res->empcode, $res->empname);
    }
    $content .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));
    $content .= theme('pager');
    return $content;
}*/

/* view the form submissions*/
function form_example_submissions()
{
  $results =  db_query("Select * from {form_example}");
  $header = array(t('ID'),t('Empcode'));
  $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->fe_id,
        $result->empcode,
      );

  }
  return theme('table',array('header=>$header','rows' => $rows));
}
/*function form_example_list(){
    //$form_example =drupal_get_form('form_example_search_form');
    // If wants to implement searching.
    //$content = '
'.drupal_render($form_example).'
';
    //$content .= '

';
    $header = array(
        array('data' => t('empcode'), 'field' => 'empcode', 'sort' => 'asc'),
        array('data' => t('empname'), 'field' => 'empname'),
        //array('data' => t('empphoto'), 'field' => 'empphoto'),
    );

    $query = db_select('form_example', 'pd');
    if(isset($_GET['empcode']) && $_GET['empcode'] != ''){
        $query->condition('pd.empcode', $_GET['empcode'],'=');
    }
    if(!empty($_GET['empname'])){
        $query->condition('pd.empname', $_GET['empname'],'=');
    }
    $query->fields('pd');

    $table_sort = $query->extend('TableSort')->orderByHeader($header);
    $pager = $table_sort->extend('PagerDefault')->limit(10);

    $result = $pager->execute();
    $rows = array();

    foreach($result as $res){
      $rows[] = array($res->empcode, $res->empname);
    }
    $content .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));
    $content .= theme('pager');
    return $content;
}*/

?>

Answer: I think this should be the error 'acccess callback' => TRUE, , you have typo which should

'access callback' => TRUE,

Clear the cache and check.
Change $item['form-submissions'] to $items['form-submissions'] and clear the cache.
Comment: please check my edited question. now form-example is working fine its show form and insert the data but when i type in form-submissions in url its give me error page not found
Answer: Remove 'access arguments' => array('administer users'), and add 'access callback' => TRUE,
$items['form-submissions'] instated of this $item['form-submissions'] need to write. (missing "s").
Clear the cache before check.
Comment: please check my edited question. now form-example is working fine its show form and insert the data but when i type in form-submissions in url its give me error page not found
Comment: updated my answer please check.
Comment: You always welcome :)


How can I make gson exclude my object's superclass?

Question: Im trying to serialize/deserialize using Gson. I don't want the super class (which is abstract) to be considered, the problem is that I don't have access to the super class code.
I've tried with an ExclusionStrategy but it didn't work.
private class SuperClassExclusionStrategy implements ExclusionStrategy {

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return clazz.equals(SuperClass.class);
        }

        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            return false;
        }

    }

How can I solve this?
Edit:
I need the fields in the superclass to be ignored, this is because I am getting this error: MyClass declares multiple JSON fields named.
I can not change the conflicting fields name.
Solution:
Solved with the following strategy:
private static class SuperClassExclusionStrategy implements ExclusionStrategy {

  public boolean shouldSkipClass(Class<?> clazz) {
   return false;
  }

  public boolean shouldSkipField(FieldAttributes field) {
   return field.getDeclaringClass().equals(MySuperClass.class) && field.getName()
    .equals("id");
  }
 }

Answer: From the Gson documentation

Exclude fields and objects based on a particular class type:

private static class SpecificClassExclusionStrategy implements ExclusionStrategy {
    private final Class<?> excludedThisClass;

    public SpecificClassExclusionStrategy(Class<?> excludedThisClass) {
        this.excludedThisClass = excludedThisClass;
    }

    public boolean shouldSkipClass(Class<?> clazz) {
        return excludedThisClass.equals(clazz);
   }

   public boolean shouldSkipField(FieldAttributes f) {
        return excludedThisClass.equals(f.getDeclaringClass()());
   }
}

Comment: Say that there is a superclass `Mammal` and a subclass `Human`. Whenever `Mammal` is passed directly to GSON, I would like it to be serialized. However, whenever GSON comes across a `Human` object, I only want GSON to serialize the `Human`-specific fields and not the fields inherited from `Mammal`. Can an `ExclusionStrategy` handle this?
Comment: `getDeclaringClass` does the job not `getDeclaredClass`
Comment: @RenéLink No, the OP wanted to exclude all fields of a particular class, not fields being of some type. That is (e.g class Clazz { String f;}) if all fields of class Clazz are to be excluded, then we should use "f.getDeclaringClass() == Clazz.class", not "f.getDeclaredClass() == String.class".
Answer: Another way to do this is:
    builder.excludeFieldsWithoutExposeAnnotation();

Then explicitly expose only the fields you want exposed.


Unable to verify SSL certificate issuer for LDAP server

Question: I have just setup SSL on my LDAP server by following this guide - http://www.linux.com/archive/feature/114087
I have made a self signed certificate using openSSL and set it up. When something tries to connect to the server using SSL it comes up with an error saying "The issuer of the certificate could not be found"
The common name is set to ldap.redmeetsblue.com.au which is pointing to our network, only port 636 is forwarded to the machine .
Ive looked over the internet but cannot find an answer, im pretty new to this so im stumped
Thanks in advance
Answer: you have to add the self-signed certificate as trusted to your client certificate store.
This way the client will accept it and establish a connection.
Answer: Since you're using a certificate signed by your own certificate authority (CA), rather than a globally recognized one (such as verisign, etc), you need to configure LDAP clients to recognize your CA, by telling them to trust the CA's certificate.
For the ldap* command line clients, this can be done by adding the following line to /etc/ldap/ldap.conf or /etc/ldap.conf:

TLSCACertificateFile /etc/ldap/cacert.pem

(I'm guessing this is where your CA certificate is, based on the link you posted. You will of course need to distribute this file to other clients.)
Hope this helps.
Comment: The actual option for the client is TLS_CACERT. TLSCACertificateFile is the same but for the server (which may use it to check client certificates).


hasSystemFeature is not returning anything

Question: I'm having a strange problem. I'm implementing a bluetooth connection in an android app. In the manifest I have permissions for:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Also I have these intents in the activity:
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
    <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
    <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Since I am using a service and receiver for bluetooth process in the background I also have this permissions for the service:
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
        <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
        <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
        <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />

Now, inside the service, I am calling to the following code:
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
   //it is true. bla bla bla
}else{
   //it is false. bla bla bla
}

Well, I cannot understand why, if I enter in debug mode, the getPackageManager is not returning anything. If I put a boolean variable with this line in the if, I can clearly see that nothing is returned. In fact, it is like if the code were killed in that moment because any other line in the code is accessed but I can still operate the app. Is it because what is being killed because of an error is the service and not the app itself? how can I debug this? Because I cannot see any error line. Any idea where the error is coming from?
EDIT: I'm running it on Android 8.0
Answer: Something additional: the function was called inside the constructor of an object that I was calling from the service. You need to pass the context to the object:
your_object = new your_object( getApplicationContext() );

and inside the object constructor:
public class your_object{

 public your_object(Context context){
     context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
}


Contar quantidades de um determinado atributo dentro de uma tabela

Question: tudo bem?
Tenho a seguinte dúvida, criei um banco de dados para um jogo de cartas no estilo de Magic. Tenho uma tabela que mostra as habilidades e outra que mostra as cartas e, mais uma que chamei de carta_habilidade que mostra a carta e sua respectiva habilidade.
Eu gostaria de listar as habilidades e quantas cartas possuem uma determinada habilidade. Por exemplo a habilidade desaparecer apresenta 3 cartas que a têm. Abaixo está o código, mas dá o seguinte erro: "unknow column 'ch.idcarta' in 'where clause'
Como posso resolver esse problema? Agradeço pela ajuda.
select h.nome, count(h.nome)as quantidade
from carta_habilid
inner join habilidades h on ch.idhabilidades=h.idhabilidades
where ch.idcarta=c.idcarta
group by h.nome;

Answer: Apenas está faltando dizer à query quem é o ch que você quer referenciar:
from carta_habilid ch
inner join habilidades h on ch.idhabilidades=h.idhabilidades
where ch.idcarta=c.idcarta
group by h.nome;


How to give a ML model an information that a store is closed or open?

Question: When predicting sales, how can you make ML models predict 0 sales when the shop is closed?
I tried to use a dummy variable with 2 columns one for open and the other one for close but it's not efficient.
I don't understand why my models can't figure out that when there is a 1 in a column they should always predict 0.
edit :
Indeed, to predict 0 sales with a model of ML, just simply remove the days without sales or if the variable store_open = 0 do not use the prediction algorithm and simply predict 0.
However, the reason I asked this question is to use my dummy variable with time series. I wanted to check if an ML model was able to predict 0 for a closed day and therefore understand in a time series that some days are at 0 because the shop is closed and others are at 0 because there were no sales. That's why I try to predict sales when a shop is closed.
This being said, in the case of a model using time series as an RNN, how can I integrate the closed and open day in my data?
Comment: Which model? The function sales = f(predictors) they fit might not be flexible enough to allow that if is_closed=1, then sales should always be 0, whatever the values of the other predictors. An additive model for instance can't do this. A decision tree can but since the're fit in a greedy way it might be missed nontheless.
Comment: Why waste your energy modeling that? You know the answer. If a store is closed, you predict zero sales. If you need some kind of software system to make predictions, write some kind of if/else screening code: if store closed, predict zero sales; else, apply your model to the data.
Comment: @CloseToC I tried this with Random forest and RNN, and yes it works better with a decision tree but it's not perfect
Comment: @Dave And I want to add this feature for multiple reasons. I know that when a shop is closed it's always 0 but I will use times series with RNN or LSTM.  I think this feature is important so that the model knows that sometimes it's 0 sales because stores are closed and sometimes it's 0 sales simply because no product has been sold.
Comment: @Dave Also, I will add a feature for public holidays. And sometimes shops are closed during public holidays but sometimes thay are open and as I am working with different shops I think I need a dummy variable for open/closed days.
Comment: As a practical matter, you can fit your model excluding days on which the store is closed, since if the store is closed, those other predictions are irrelevant any way. This should also improve the model's ability to predict sales on open days
Comment: @CloseToC yes indeed like Dave said "Why waste your energy modeling that? You know the answer. If a store is closed, you predict zero sales.", but this might not be a good solution for time series
Answer: There is actually a line of research dealing with a similar problem: rules-first classification.
It may be considered an open topic of research (without much activity), but a nice paper on the topic was recently published in PMLR.
Short summary: The authors propose a classification problem where the output label can be perfectly predicted by a binary rule (like the store_open variable you describe) and otherwise predicted with some error by a linear classifier. They go on to study the properties of this problem and limitations of algorithms designed to solve it.
On a more practical note, you may consider filtering your feature vectors based on the store_open variable by short-circuiting your outputs to be 0 when store_open==true, and running an alternative algorithm when store_open==false.
Comment: I'm going to take a look at it thank you !
I added an edit, this solution work for model with "simple" input, but the reason behind my question concerns the use of this dummy  variable with time series.
My question may not have been explicit, so I re-explained my objective in the edit.


Proper use of the following functions:describeBy, statsBy, and stat.desc

Question: I am using R 3.2.0 and have been successful using the aggregate function but it gives minimum statistics, tapply gives more than the aggregate function but the summary statistics are limited. For the following data with 4 groups of different n's can anyone show me how to use following functions properly: describeBy, statsBy, and stat.desc? Following is the data and incorrect syntax for the above functions that I used.
data <- c(62, 60, 63, 59, 63, 67, 71, 64, 65, 66, 68, 66, 71, 67, 68, 68, 56, 62, 60, 61, 63, 64, 63, 59)
grp <- factor(rep(LETTERS[1:4], c(4,6,6,8)))
df <- data.frame(group=grp, dt=data)
describeBy(data, df$dt, df$group, mean,median,min,max,sd)
statsBy(df,mean,median,min,max,sd)
stat.desc(df,basic=F)

Comment: @Pascal - `psych` I think
Comment: From which package(s) are `describeBy`, `statsBy`, and `stat.desc` coming?
Comment: @thelatemail Probably, but it is the job of the OP to provide such details.
Comment: `aggregate` can deliver any statistic you ask for.
Answer: library(DescTools)  # not asked for, but better
Desc(df, plot = T)

library(psych)
describeBy(df, df$group)
# statsBy tries to find correlations, but you have only 1 numerical variable here.

library(doBy)
library(pastecs)
summaryBy(dt ~ group, data = df, FUN = stat.desc)


Geo fencing, ip address list of different geographies

Question: I need to provide different webpage experiences based on geographies divided as Western, Asian, African audience etc.
I plan to do this with Nginx geo module by segmenting ip addresses and routing to the webserver with headers set from the Nginx reverse proxy
Now, where can I get the list of ipaddress blocks that can tell me if a user is from a e.g: western country, Asian etc?
Which is the canonical source to get this?
Comment: possible duplicate of [Best way to block a country by IP address?](http://serverfault.com/questions/166812/best-way-to-block-a-country-by-ip-address)
Comment: It isn't a duplicate.  That is about blocking access to specific countries, whereas this is about providing differing content based on country.  They are related, but not exact duplicates, and there aren't many good answers to the suggested duplicate either.
Answer: Did you see this page about Creating geo.conf From MaxMind GeoIP Country Database?  It's linked from the bottom of the nginx Geo Module you mentioned.
You will have to divide the countries up into categories (Western, Asian, African audience etc.) yourself but that shouldn't be too difficult.
If it were me doing this, I would do it in the app using one of the APIs that MaxMind provide with the actual data or pushing the data from the CSV file into my database.  Don't forget that there are functions available to convert IP addresses from dotted-quad to numerical formats and back (ip2long(), INET_NTOA(), etc.) so you don't have to use the sample code given there.