PHP time interval of at least ten days

Question: The idea is to query the users latest time stamp of their latest profile change. If it has been less than ten days when they try to update it they will be denied. No matter what I seem to do I cant get the 10 day difference logic correctly.  $stamp is is Y-m-d date format in the database.
    <?php
ini_set('display_errors',1);
$json=$_POST['user'];
$json=str_replace('\\','',$json);
$user=json_decode($json);
$pdo=new PDO('mysql://hostname=localhost;dbname=database', 'user', 'password');
$update = $pdo->prepare("update  `accounts` set  stamp=CURDATE(),`title`='{$user->title}' ,`radio_hanlde`='{$user->radio_handle}' , `carrier`='{$user->carrier}' ,`hometown`='{$user->hometown}'  WHERE user_id='{$user->user_id}' AND DATE_DIFF(CURRDATE(),stamp) > 10");
$update->execute();
if ($update->rowCount() != 0 ){
     echo json_encode(array('success'=>'1','message'=>'Your profile has been updated successfully!'));}
     else {echo json_encode(array('success'=>'0','message'=>'It has been less than ten days since your latest profile change. You will have to wait!'));}
?>

Comment: it should be a problem. Print out both the date to see if the values are correct or not..date_create($stamp[1]); specially this value
Comment: $stamp[0] returns "Array" , $stamp[1] returns " ". I dont get it. When I look in sql workbench it contains "2016-23-01" and field is a not-null date.
Comment: What can I possibly be doing wrong here?
Comment: here's my query $query=$pdo->query("Select stamp FROM channel1_db.accounts where user_id='{$user->user_id}'");
 $stam=$query->fetchAll(PDO::FETCH_ASSOC);
Comment: you are doing it wrong @Robert ... iterate over the stamp and take a variable..in the foreach loop assign the value..and use that variable for comparison
Comment: I'm so new to php its ridiculous.  The php script is for my Android app which is my forte. I was expecting a single value to be returned with my query. I asked it for a single column from a specific row. My understanding of php is that it returns a multi-layered array regardless.  So $stamp[1] would be the 2nd row.  There are no other layers.  Can you give me an example of what you mean with the foreach loop?
Comment: You don't need two queries here. You only need an UPDATE
Comment: well I query the last time they updated theyre profile i.e. "stamp" from "accounts"...if it's been more than ten days I update the profile and stamp to 'now' and the posted information from the user inside client android app
Answer: Function strtotime returns timestamp in seconds, so you can get diff in seconds very simple like this
$secs = strtotime('now') - strtotime($stamp);
$days = $secs / 60 / 60 / 24;
if($days <= 10) {
    ..your code...
}

Comment: From review, thanks for your answer on SO, to improve your answer consider to not only provide code but also some description about why and what your code does. Example what is the `strtotime` function ecc.
Answer: PHP's mysqli and PDO APIs have functions for detecting whether an UPDATE affected any rows (mysqli_affected_rows() and PDOStatement::rowCount(), respectively), so you can pretty much throw away all of your code.
All you need to do is UPDATE all rows for the given user that match the criteria, e.g.:
UPDATE accounts
   SET stamp = '$stamp'
     , title = '{$user->title}'
     , radio_hanlde [SIC] ='{$user->radio_handle}'
     , carrier  = '{$user->carrier}'
     , hometown = '{$user->hometown}'
 WHERE user_id  = '{$user->user_id}'
   AND DATEDIFF(CURDATE(),stamp) > 10;

If PDOStatement::rowCount() returns a value other than 0, print message 1 otherwise print message 2.
As per the following example, assembled by the OP...
$pdo->exec("
UPDATE accounts
   SET stamp = '$stamp'
     , title = '{$user->title}'
     , radio_hanlde ='{$user->radio_handle}'
     , carrier = '{$user->carrier}'
     , hometown = '{$user->hometown}'
 WHERE user_id = '{$user->user_id}'
   AND DATEDIFF(CURDATE(),stamp) > 10
 ");

if (PDOStatement::rowCount() < 1 ){
     echo json_encode(array('success'=>'0','message'=>'It has been less than ten days since your latest profile change. You will have to wait!'));
 } else {
     echo json_encode(array('success'=>'1','message'=>'Your profile has been updated successfully!'));
 }

Comment: @RobertGoodrick That looks like the right kind of thing, but see prepared statements.
Comment: Okay Stawberry! Thats what i'm talking about! Thank you very much
Comment: Yeah It's having issues with if (PDOStatement::rowCount() > 0 ){
 echo json_encode(array('success'=>'0','message'=>'It has been less than ten days since your latest profile change. You will have to wait!'));
 }else{
 echo json_encode(array('success'=>'1','message'=>'Your profile has been updated successfully!'));
 }
Comment: Not sure what those might be - nor why "< 1" would work if "> 0" doesn't - but I'm not much of a PHP coder
Comment: I'm not either. I had one set up the php end of my application and then he disappeared.  But i've slowly added some functions and additions after the fact. And yes > 0 would be more appropriate. Problem is I'm not receiving the else echo in either case
Comment: okay i'm using a prepared update statement and so able to use rowcount() afterwards and it works great. Problem is now the AND condition is never true even though stamp is more than 10 days in the past....
Comment: the column is a date() ...any ideas why the date_diff($date, $date2) > 10 wouldnt like this?
Comment: This is driving me up the wall...now i'm trying this AND new DateTime(curdate()) > new DateTime(stamp) condition and it aways results in count() of 0
Comment: @RobertGoodrick I think I mistyped the DATEDIFF function (was DATE_DIFF!!).
Comment: Yeah I actually caught that early.  I'll edit my code portion in the original question to show my current php. Still haven't solved the issue.  Rows affected is always 0 because the date difference is never over ten.
Comment: Really? It seems worse now then it was before (`DATE_DIFF(CURRDATE`). And can we please have some formatting
Comment: SO..wasnt accessing $stamp correctly. Here is what Ive figured out to do so. $stamp = $query->fetchAll(PDO::FETCH_ASSOC);
$shifted=array_shift($stamp); and then $shifted['stamp'] contains the value :)
Comment: Great. So, either edit my question and accept it, or add an answer below and accept that instead.
Answer:  $today=date_create(date('Y-m-d'));
 $date2=date_create("2013-12-12");
 $diff=date_diff($today,$date2);

if($diff<10){
  echo "Your alert";
}

Comment: i'm trying this date_diff(date1, date2) call but I seem to have some issue with the date object. I've been racking my brain on this for days and cant seem to see the error.
Comment: Danyal could you perhaps review my edited code post to see what you think might be going on to where $wait is returning 10.
Answer:  $querydata="SELECT CURDATE()";
                                 $result_data= mysqli_query($link, $querydata);
                                  $data=mysqli_fetch_array($result_data)[0];
                                $intervaloTempo = gmdate("d:H:i:s", time() + (10 * 24 * 60 * 60);

Use this for your query
 "(().data=\"".$data."\" and ()>=\"".$intervaloTempo."\"" )"

                                    $query = sprintf("select stamp from accounts where user_id='{$user->user_id}, mysqli_real_escape_string($link, $_SESSION['cliente_id']));
                                    $result = mysqli_query($link, $query);
                                    if (!$result) {
                                        die("Query error: " . mysqli_error($link));
                                        //con_close();
                                    }

Answer: Use time() function to get current time in seconds (Unix timestamp) and strtotime() to convert any date format to timestamp. Here is refactored code of your example:
<?php

ini_set('display_errors', 1);

$messages = [
    'error_invalid_json' => 'Error. Invalid json',
    'error_account_not_found' => 'Error. Account is not found',
    'success' => 'Your profile has been updated successfully!',
    'wait_1_day' => 'It has been less than ten days since your latest profile change. You must wait until tomorrow!',
    'wait_n_days' => 'It has been less than ten days since your latest profile change. You have %s more to go!',
];

function message($message, $success = true)
{
    echo json_encode([
        'success' => ($success) ? 1 : 0,
        'message' => $message,
    ]);

    exit;
}

// get and validate incoming data
$json = $_POST['user'];
$json = str_replace('\\', '', $json);
if (empty($json)) {
    message($messages['error_invalid_json'], false);
}
try {
    $user = json_decode($json);
} catch (\Exception $e) {
    message($messages['error_invalid_json'], false);
}
if (empty($user->user_id)) {
    message($messages['error_invalid_json'], false);
}

// find last modified date
$pdo = new PDO('mysql://mydb', 'a_user', 'password');
$query = $pdo->query("Select stamp FROM accounts WHERE user_id='{$user->user_id}' LIMIT 1");
$stamp = $query->fetchAll(PDO::FETCH_ASSOC);
if (empty($stamp)) {
    message($messages['error_account_not_found']);
}

// calculcate when user is allowed to change profile
$daysShouldPassBeforeEdit = 10;
$allowEditAfter = ($stamp[1]) ? strtotime($stamp[1]) + $daysShouldPassBeforeEdit * 86400 : time(); // if empty `stamp` then user have not edited and allow to edit now

if (time() < $allowEditAfter) {
    $daysLeftBeforeAllowEdit = ceil(($allowEditAfter - time()) / 86400);

    if ($daysLeftBeforeAllowEdit == 1) {
        message($messages['wait_1_day'], false);
    } else {
        message(sprintf($messages['wait_n_days'], $daysLeftBeforeAllowEdit), false);
    }
}

// save changes
$stamp = date("Y-m-d");
$sql = "update  `accounts` set  stamp='$stamp',`title`='{$user->title}' ,`radio_hanlde`='{$user->radio_handle}' , `carrier`='{$user->carrier}' ,`hometown`='{$user->hometown}'  where user_id='{$user->user_id}'";
$pdo->exec($sql);
message($messages['success']);

Comment: `$stamp[0]['stamp']`
Comment: okay. Stupid question I know but please help me with this last deal. Okay with Limit 1 stamp[0] finally returns the value i'm looking for in another array as {"stamp":"2016-01-29"}.  how to simply extract the date?  That's all I need now.  $stamp[0]->stamp..?????????

PHP time interval of at least ten days


Imprimir todas as condições if

Question: Queria um modo que quando o usuário digitasse a key = 4, todas as condições que eu atribui fossem impressas, tem algum modo ou eu teria que atribuir uma condição if e repetir tudo novamente?
import math
import sys

print()
print("#" * 51)
print("Este programa calculará o SENO, COSSENO e TANGENTE.")
print("#" * 51)
print()

lista1 = [1,2,3,4,5]

a = int(input("Para realizar os cálculos digite: \n\nSENO = 1 \nCOSSENO = 2 \nTANGENTE = 3 \nTODOS = 4 \nENCERRAR PROGRAMA = 5 \n\nDigite a seguir: "))
print("#" * 51)
print()

while a not in lista1:
        print("Ei, digite um dos números informados!")
        print()
        a = int(input("Para realizar os cálculos digite: \n\nSENO = 1 \nCOSSENO = 2 \nTANGENTE = 3 \nTODOS = 4 \nENCERRAR PROGRAMA = 5 \n\nDigite a seguir: "))
        print("#" * 51)
        print()

if a == 1:
    co = float(input("Digite o valor do CATETO OPOSTO: "))
    hi = float(input("Digite o valor da HIPOTENUSA: "))
    print("#" * 51)
    print()

    sen = co / hi

    print(f"O valor do SENO é igual à {round(sen, 3)}!")
    print()

if a == 2:
    ca = float(input("Digite o valor do CATETO ADJACENTE: "))
    hi = float(input("Digite o valor da HIPOTENUSA: "))
    print("#" * 51)
    print()

    cos = ca / hi

    print(f"O valor do COSSENO é igual à {round(cos, 3)}!")
    print()

if a == 3:
    co = float(input("Digite o valor do CATETO OPOSTO: "))
    ca = float(input("Digite o valor do CATETO ADJACENTE: "))
    print("#" * 51)
    print()

    tan = co / ca

    print(f"O valor da TANGENTE é igual à {round(tan, 3)}!")
    print()

if a == 5:
    print("Encerrando programa...")
    print()
    sys.exit(0)

#Quando o usuario digitasse a key 4 todos os cáculos seriam impressos

Comment: Separe as porções de código específico em função e para cada opção chame a função ou funções relacionada(s).
Comment: Não bastaria adicionar um `or` nas suas condições? `if a == 1 or a == 4`, ou de forma mais simples `if a in {1, 4}`
Comment: @Woss obrigado amigo, ajudou muito, resolveu meu problema
Comment: O ideal seria você fazer uma lógica diferente para o valor 4 mesmo, pois se fizer a chamada novamente dos ifs anteriores irá pedir ao usuário para digitar valores repetidamente.
Answer: É uma simples questão de lógica. Se você quer que um código seja executando quando a = 1 ou quando a = 4, basta fazer tal condição.
Hoje você tem:
if a == 1:
  ...

Basta fazer:
if a == 1 or a == 4:
  ...

Ou, como alternativa, você pode criar um conjunto dos possíveis valores e verificar se o a está nesse conjunto:
# testa se a é 1 ou 4
if a in {1, 4}:
  ...

Answer: Primeiro separe o código recorrente em funções.
Em linguagem de programação a ideia básica de função é encapsular um código que poderá ser invocado/chamado por qualquer outro trecho do programa, ou seja uma função nada mais é do que uma sub-rotina a ser usada em seu programa.
A utilização de funções visa modularizar um sistema podendo dividi-lo em várias partes no qual cada parte realizará uma tarefa bem definida.
Em python definimos uma função com o uso da palavra chave def.
Como todas as operações realizam o mesmo processamento, coletar dois valores e os dividir, foi criada uma função calc(opr, l1, l2) que aceita três parâmetros de texto onde:

opr é o texto a ser exibido informando qual a operação realizada.
l1 é o texto a ser exibido informando um dos lados do triangulo a ser operacionalizado.
l2 é o texto a ser exibido informando o outro lado do triangulo a ser operacionalizado.

As funções seno(), cosseno() e tangente() apenas chamam calc() com os argumentos adequados.
Em seguida melhore simplifique o laço onde serão escolhidas as opções de processamento do sistema, removendo o código verboso pela chamada das respectivas funções para cada opção.
Para simplificar o exemplo nenhum código de verificação e validação de entrada foi adicionado.
def calc(opr, l1, l2):
  a = float(input(f"Digite o valor do {l1}: "))
  b = float(input(f"Digite o valor da {l2}: "))
  r = a / b
  print(f"\nO valor do {opr} é igual à {round(r, 3)}!\n{'#' * 51}\n")

def seno():
  calc("SENO", "CATETO OPOSTO", "HIPOTENUSA")

def cosseno():
  calc("COSSENO", "CATETO ADJACENTE", "HIPOTENUSA")

def tangente():
  calc("TANGENTE", "CATETO OPOSTO", "CATETO ADJACENTE")

print(f"\n{'#' * 51}\nEste programa calculará o SENO, COSSENO e TANGENTE.\n{'#' * 51}\n")
while True:
  a = int(input("Para realizar os cálculos digite: \n\nSENO = 1 \nCOSSENO = 2 \nTANGENTE = 3 \nTODOS = 4 \nENCERRAR PROGRAMA = 5 \n\nDigite a seguir: "))
  print(f'{"#" * 51}\n')
  if a == 1:
    seno()
  elif a == 2:
    cosseno()
  elif a == 3:
    tangente()
  elif a == 4: #Quando o usuário digitar 4 todos os cálculos serão realizados.
    seno()
    cosseno()
    tangente()
  elif a == 5:
    print("Encerrando programa...\n")
    break
  else:
    print("Ei, digite um dos números informados!\n")

Teste o código no Repl.it

Imprimir todas as condições if


How do you make npm install locally?

Question: NPM will not install packages locally, update package.json, nor update package.lock. It's a very perplexing issue honestly.
Pseudo-steps to reproduce are:

mkdir testFolder
cd testFolder
npm init -> use defaults
npm install dotenv

I'm running Windows 11.

I tried running with Developer mode on and off
I tried installing node (16.15.1)/npm via NVM4W (1.1.9) and using npm install <package>
I uninstalled NVM4W and installed node (18.4.0) directly

I'm kind of at a loss for things to try now.
It feels like there's some Windows setting somewhere I'm missing that's causing all these problems
Answer: For me, it turned out that I had modified my C:\Users{user}.npmrc file which had the setting "location=global" set. I deleted the setting and it all worked.
This got set, I believe, because I did npm config set local=global earlier due to a deprecation warning I received using an older version of npm.

How do you make npm install locally?


Soprano recorder vibrato

Question: How should I vibrate the sound of my soprano recorder?
Note: I'm not sure to use the correct term. By vibration I mean producing the sound similar to vibrating your hand on a Violin during playing a long note (a whole note for example).
Comment: That's technically correct, actually; the name of the technique is _vibrato_.
Answer: Since the recorder is a type of flute that doesn't have an embouchure which affects pitch, all you have control over is the speed of the airstream. As a result, recorder vibrato is executed by adding pulses to the airstream at a regular interval. Since the airstream should be driven by the diaphragm, we call this diaphragmatic vibrato.
Locate your diaphragmatic support muscle by laughing, coughing, or by saying the word "Ha!" in rapid repetition. Then, try adding pulses of this muscle to a steady and smooth airstream. Start with a very slow interval between pulses, and gradually increase the speed of the pulses at regular rhythmic intervals, with the aid of a metronome for control.
Comment: @niggles That is the opposite of correct diaphragmatic breathing. When you breathe in, your diaphragm is lowering, and should be pushing your tummy _out_ as a result.
Comment: This explanation was really great @NReilingh, but also too technical to imitate :). Could you provide a link to a training tutorial (preferably a video) which shows this technique?
Comment: Heh, if that's true then I didn't do the job properly! The second part is just a detailed explanation of how to develop the technique properly from scratch; if you just want to experiment, it doesn't get any simpler than "pulse the airstream."
Comment: To help locate your diaphragm, when you breath in, your tummy should go in, not out and you'll then be holding the air in the right place to do the vibrato. The effect is sort of like "fluttering your stomach muscles"

Soprano recorder vibrato


Try/Catch PDOException não funciona quando ocorre erro

Question: Criei o seguinte método para executar as minhas querys:
public function setQuery($query) {
    try {
        $stmt = self::$conn->prepare($this->limpaQuery($query));
        return $stmt->execute();
    } catch (PDOException $Exception) {
        var_export($query);
        die();
    }
}

Funciona perfeitamente, mas quando executo uma query errada apresenta o seguinte erro:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42S22]: Column not found: 1054 Unknown column...

O que eu não entendo é o porque ele não pega a PDOException, eu queria que toda query que não executasse fosse exibida.
Updade
/**
 * Conexao
 */
public function openConection() {
    try {

        //Verifica se uma instancia já existe
        if (!isset(self::$conn)) {
            //String de conexão
            self::$conn = new PDO("mysql:host=$this->servername;dbname=$this->banco", $this->username, $this->password);

            // set the PDO error mode to exception
            self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        //Mensagem de status
        $this->status = "Conectado no host $this->servername, no banco dbname=$this->banco com o usuário $this->username";
    } catch (PDOException $e) {
        //Mensagem de status
        $this->status = "Falha ao tentar conectar: \n" . $e->getMessage();
    }
}

Comment: Tem certeza que a exceção é disparada neste método?
Comment: Sim, ele fala exatamente esta linha, e coloquei o try catch em todos os métodos que executam querys.
Comment: Essa resposta pode te ajudar [Para que servem os Blocos Try/Catch e quando devem ser utilizados?](https://pt.stackoverflow.com/questions/58536/para-que-servem-os-blocos-try-catch-e-quando-devem-ser-utilizados/424523#424523)
Answer: Você precisa setar a configuração PDO::ATTR_ERRMODE para PDO::ERRMODE_EXCEPTION.
$conn = new PDO($host, $usuario, $senha);
$conn->setAttribute(PDO::ATTR_ERRMODE, $conn::ERRMODE_EXCEPTION);

Comment: Salvei até como favorito, quem save um dia aconteça ai já sei aonde encontrar. :)
Comment: Já esta assim :/
Comment: Então adicione também `setAttribute(PDO::ATTR_EMULATE_PREPARES, false);`
Comment: Deu o mesmo efeito
Comment: Estranho porque eu testei aqui e funciona.
Comment: Eu postei a resposta, era por causa do namespace.
Answer: Encontrei o problema, ele estava interpretando o PDOException como conexao\PDOException por causa do namespace.
namespace conexao;

Então eu importei o PDOException.
use PDOException;

Fonte: https://stackoverflow.com/questions/39826052/pdo-catch-pdoexception-error
Comment: Bem que eu ia pedir isso nos comentários, mas não lembrava se dava erro de classe não definida ao utilizar no *catch*.
Comment: O estranho foi isso, ele não deu erro de classe não definida @AndersonCarlosWoss
Comment: Eu tive o mesmo problema. Passei a implementar namespace nas classes e o PDOExecption deixou de funcionar como esperado.
Answer: Uma contrabarra antes do PDOxception resolveria seu problema, colocando a contrabarra, ele "quebra" seu namespace e não interpreta mais como "conexao\PDOxception".
public function setQuery($query) {
    try {
        $stmt = self::$conn->prepare($this->limpaQuery($query));
        return $stmt->execute();
    } catch (\PDOException $Exception) {
        var_export($query);
        die();
    }
}


How to specify updates in WSUS

Question: I have WSUS on Windows server 2003 64 bit. I want to specify updates for my clients, for example some PCs I don't want them to update to Internet explore 8 and WSUS has downloaded and updated by itself and I don't want to go to one by by one to install it by hand so is it possible to tell WSUS that this PC do not install/update Internet explore or other updates?
Any advice would be appreciated
Thanks
Answer: Yes, you can build Computer Groups and allow Updates for specific subgroups.
Comment: I have tried to prevent internet explore to install by itself but I didn't find it in WSUS could you please tell me what is the name of this update?
Comment: What exactly do you mean? Do you want to prevent that Internet Explorer is installed at all or do you want to prevent that certain PCs get Security Updates for Internet Explorer?

How to specify updates in WSUS


How to test if two independent variables correlations are statistically different?

Question: I have two independent variables (A and B), and one dependant variable (Y). I can calculate all the correlations (A-B, A-Y, B-Y...).
I see a difference between the Pearson correlations A-Y and B-Y (e.g.: 0.86 and 0.94). How to check whether this difference is statistically different?
There should be also a bottom limit for the sample size. How do I calculate that?
Thanks!
Answer:
A variable in common (overlap) e.g. of form r(W,X) = r(W,Z).

A test for this comparison goes under various names the Williams test, Williams-Hotelling or Hotelling test.

Cited from https://imaging.mrc-cbu.cam.ac.uk/statswiki/FAQ/WilliamsSPSS where the use of SPSS is also dicussed.
http://crr.ugent.be/archives/546 has a formula to conduct that.
Williams-Hotelling and Steiger-Test are implemented in R in the package psych in the function r.test: https://personality-project.org/r/psych/help/r.test.html
The publication by Steiger cited on the help page to psych::r.test can be found here: http://ww.w.statpower.net/Steiger%20Biblio/Steiger80.pdf
There also is an online calculator for these tests here: https://blogs.gwu.edu/weissba/teaching/calculators/hotellings-t-and-steigers-z-tests/
I have found a more modern overview and treatment of the question of which methods to use when here, however tl;dr; ;-) : https://uh.edu/~ttian/dependentCorr.pdf
Comment: you're amazing. Thanks a lot for all the resources!


Infimum of distance between two sets

Question: I have come across one little snippet in my Real Analysis book and I can not get it through. It generally says:
$E\subset [0,1] \subset G$ and $E$ is closed $G$ is open. Define $\delta=\inf\{|x-y|,x\in E \text{ and }y\in G^c \}$, then $\delta>0$.
I know $\delta\ge 0$, but I do not know how to prove $\delta$ could not be $0$.
Thanks.
Comment: It may be helpful to include work you have already done. This will also help you understand your own proof better.
Answer: As $G$ is open and $[0,1] \subset G$, there exists a connected component  of $G$, say $G_1$, containing the unit interval. Then we have $G_1=(a,b)$ with $a<0 <1 <b$ (as connected open subsets of the real line are open intervals). You should be able to conclude from here.

Note (after an edit): my original answer ("As $G$ is open and $E=\overline{E} \subset G$, around every point of $E$  there's a ball of positive radius all contained in $G$.") is incorrect as the radii can have infimum $0$, as pointed out by the OP in the comments.
Comment: but we do not know how small this radius could be, and the distance of $E$ and $G^c$ could still be as small as possible and thus $\delta$ could be zero?
Comment: You are right. That wasn't enough. See my edit.
Comment: You are correct, again. The statement doesn't hold in general (without knowing $[0,1]\subset G$).
Answer: Although, the requirement is that $E$ be a proper subset of the unit interval, it is easy to see this by assuming $E=[0,1]$. Since if it is true for this latter set, it must be true for the smaller set.
Now, $[0,1] \subset G \implies \exists x \in G, x \not \in [0, 1].$ It is clear that the distance from any such element to any element of $E$ must be non-zero. And since any such point in $G$ satisfies this property, the complement, $G^c$, here must also since it will contain points farther away.
Answer: If $G$ is open, then for the points $0, 1$ exist $r(0), r(1)$ such that $B(x, r(x)) \subseteq G$, where $x = 0, 1$. Let $r = \min (r(0), r(1))$. Then $B(0, r), B(1, r) \subseteq G$. But by this, it follows that $(- r, 1 + r) \subseteq G$. But then $[ - r / 2, 1 + r / 2] \subseteq G$. So if $t \not \in G$, then either $t > 1 + (r / 2)$, or $t < - r / 2$. In either case, $d(t, x) \geq r / 2 > 0$, where $x \in E$, concluding the proof.
Comment: You have proved that $d(t,x)>0$ for $t\in G^c$ and $x\in E$, which is correct absolutely. But it does not mean the infimum of this distance could not be zero
Comment: I showed something stronger: that $d(t, x) \geq r / 2$.
Answer: Assuming $E$ not empty (so $\delta$ exists).
$E$ and $G$ are disjoint closed sets,but $E$ is also compact. If $\delta = 0$ then there is a sequence $(x_n)_n$ in $E$ and  a sequence $(y_n)_n$ in $G$ with  $\lim_{n\to \infty}|x_n-y_n|=0.$ But since $E$ is compact,there would be a subsequence $(x_{f(n)})_n$ of $(x_n)_n$ converging to a point $x,$ and since $E$ is closed, $x\in E.$ Then $\lim_{n\to \infty}|x-y_{f(n)}|=0,$ implying $x\in \bar G=G,$ a contradiction ( because $x\in E$ and $E\cap G=\phi).$
Note.If $E$ and $G$ are closed,non-compact subsets of $R$, it is possible that $\delta=0.$ E.g. $E=N$ and $G=\{n+2^{-n}:n\in N\}.$
Comment: The more I see, the more I feel it makes perfect sense. Thank you for your knowledge. By the way, could I use Weierstrass Theorem to prove every sequence of compact set has a convergent subsequence whose limit is in the set?
Comment: Weierstrass had a lot of theorems.Which one are you referring to?
Comment: each bounded real sequence has a converging subsequence
Comment: Yes. A compact subset $C$ of the reals is necessarily a closed set. Because if not there is an injection $f:N\to C$ where $\{f(n):n\inN\} has no limit point in $C$, from which you can find an open cover of $C$ with no finite sub-cover, using the fact that the complement in $R$ of a finite set is an open set.

Infimum of distance between two sets


Silverlight data binding in the code behind

Question: I am doing something like this in a Silverlight 3 datagrid:
for (int x = 0; x < ThisForecast.Periods.Count; x++)
{
   var TextColumn = new DataGridTextColumn();
   TextColumn.Header = ThisForecast.Periods[x].Name;
   TextColumn.Binding = new Binding(String.Format("Periods[{0}].Quantity", x));
   TextColumn.Binding.Mode = BindingMode.TwoWay;
   TextColumn.IsReadOnly = false;
   dgItemForecast.Columns.Add(TextColumn);
}

And it works great, but I want to change the ready only to something more like:
    TextColumn.IsReadOnly = new Binding(String.Format("Periods[{0}].IsReadOnly", x));
And while it seems easy to do in XAML, I can't figure out the correct method to do this in the code behind.  Obviously I can't set it to a 'binding', but where would I be able to set something like that?
EDIT #1:
I looked at the BindingOperations.SetBinding() given below, but could not find a DependencyProperty for IsReadOnly.  Is there a way to inject/add one?
Answer: BindingOperations.SetBinding(textColumn, DataGridTextColumn.IsReadOnlyProperty, new Binding(...));

Comment: That is awesome and addresses the general understanding issue I am having, but DataGridTextColumn does not have a IsReadOnlyProperty.
Comment: DataGridTextColumn has an IsReadOnly property, inherited from DataGridColumn, but it's not clear from the docs whether it's a dependency property (and I don't have the tools at hand to check it out, sorry) -- the docs don't mention an IsReadOnlyProperty field as you would expect for a DP.  If it's not a DP, it can't be data bound.  You may therefore need to use a DataGridTemplateColumn instead, and with your DataTemplate consisting of a TextBox; you can then bind the IsReadOnlyProperty of that TextBox.
Comment: @itowlson can you explain the `DataGridTemplateColumn` approach? how to access the textbox inside it? how to set the binding in code?
Comment: @HosseinNarimaniRad Urgh, apologies; I haven't looked at Silverlight in four years and no longer even have the dev tools installed to try to remind myself.  If you're after WPF ping me, but I can't help with Silverlight, sorry.


Small question about the mean not being in its confidence interval

Question: To study a certain characteristic about a population of people we take a sample of $100$ individuals. The $80$ percent confidence interval for the mean is $(0.9,1.1)$.
Part I: Find the sample mean and standard deviation (easy). $\bar x = 1$ and $\hat \sigma = 0.7752$
Part II: What is the probability that $(0.9,1.1)$ doesn't contain the mean.
What about Part II? Is it just $1 - 0.8 = 0.2$, or is it a trick question?
Comment: Seems right to me, but I'm only about 80% confident in my answer :P
Comment: @George this question is just mean.
Comment: @George Do you see the possible misunderstanding here?  To take a clearer instance:  if you roll a fair die there is a $\frac 16$ chance of getting a $6$.  So, you roll it and you get a $4$.  This does not mean that there is a $\frac 16$ chance that $4=6$.
Comment: @PatrickStevens it seems to me that confusion is normal in such situations
Comment: Maybe they are after a technical point:  There is a standard abuse of language involved here, discussed in (eg) https://en.wikipedia.org/wiki/Confidence_interval .  Once the interval is chosen, there is no probability involved.  The mean is either in it or it isn't.  The "$80\%$" means that the method of choosing the band results in a band which will contain the mean "$80\%$" of the time.
Comment: i now see what you mean @lulu
Answer: Part 2 isn't a trick question. The answer is 0.2. The trick question which tends to be asked in these situations is "what is the probability $\mu$ lies in the confidence interval?" Then the answer is "either $1$ or $0$, depending on whether it does or does not."
Comment: thank you, but how does the question you suggested differ from that in my post?
Comment: or what is the kind of situation that you are supposing so that this question means something else
Comment: It's all in the wording. In your question, they are referring to the confidence interval as a variable, and the mean is fixed, which is correct. In the trick question, they are implying that the mean is a variable, which it is not.


Uncaught TypeError: $(...).slick is not a function, Slick Carousel on local machine

Question: I have followed all the tutorials I could find but I can't get it to display a simple carousel. The console says

"Uncaught TypeError: $(...).slick is not a function".

        <title>T_T</title>

        <link rel="stylesheet" type="text/css" href="//email@example.com/slick/slick.css"/>

Content 1

Content 2

Can someone tell me what am I missing?
It seems to work just fine in the code snippet, but when I launch it locally on my computer it doesn't work :(
Comment: Thank you so much! I was breaking my head over this. Now it works!
Comment: Why does it work here but not if I launch the website locally on my browser????
Comment: Welcome to Stack Overflow! This really doesn't answer the question, but you can remove the `type="text/javascript"` from the `script` tags. That attribute is essentially deprecated since HTML5 was adopted. For your local issue, try adding the `https://` to the slick URL. On your local machine, it may be trying to look in *your* file directory.
Comment: I'll write it as an answer, as this may help others.
Answer: The reason is that the src for the carousel script is "looking" on your local machine (or may not know where to "look") since the URL Protocol (http/s:) is not defined.
//firstname.lastname@example.com/slick/slick.min.js
Add the https: to the start of the URL.
https://email@example.com/slick/slick.min.js


SELECT em 2 tabelas MySql com PHP

Question: Estou com uma duvida ao dar um select, pois  tenho 3 tabelas, são elas profissionais, experiencias, endereco.
Vamos dizer que tenho um profissional e esse profissional tem mais de 2 experiencias. Tem alguma forma de trazer em uma linha essas informações, se não como posso fazer isso em php, para que não se repita o nome do profissional.
Tabelas:
Profissional:
id
nome
sobrenome
estado_civil
experiencias:
id
cargo
dt_entrada
dt_saida
id_profissional
Meu select por enquanto é assim
SELECT pro.id, pro.nome, exp.cargo
FROM Profissional pro
INNER JOIN experiencias exp ON exp.id_profissional = pro.id
WHERE pro.id = :algumacoisa GROUP BY pro.id

Exemplo de saida
Temos 1 profissional com 2 cargos cadastrado.
ID             Nome                  Cargo           Cargo

1             romario            programador        Técnico

Mais ou menos assim, sei que o nome de tabela não se repete, mas se tiverem uma solução, agradeço.
Comment: Tentou usar inner join?
Comment: Você vai precisar usar tanto MySQL como PHP para fazer isso. Poste as estruturas das tabelas para te ajudarmos.
Comment: Pronto, consegui exemplificar mais um pouco a minha duvida.
Answer: Galera consegui resolver,
Bastava eu usar GROUP_CONCAT();
Ficou assim:
SELECT pro.id, pro.nome, GROUP_CONCAT(exp.cargo)
FROM Profissional pro
INNER JOIN experiencias exp ON exp.id_profissional = pro.id
WHERE pro.id = :algumacoisa GROUP BY pro.id

Ele traz todos os cargos desse usuário em uma linha só sem repetir o nome e separados com virgula.
Comment: Aqui deu certo também!
Answer: SELECT pro.id,pro.nome,exp.id,exp.nome
   FROM Profissional pro, experiencias exp
WHERE exp.id = pro.id and pro.id = :algumacoisa

Comment: Ainda não tirou minha duvida!
Comment: O ideal é usar join pra "mesclar" as tabelas e mostrar tudo em uma.
Comment: Disso eu já sei, ele repeti o nome para mostrar mais de uma experiencia.
Comment: da uma olhada aqui http://stackoverflow.com/questions/15603650/mysql-2-select-in-one-query

SELECT em 2 tabelas MySql com PHP


A question comparing $\pi^e$ to $e^\pi$

Question: I was doing an algebra problem set following a chapter on logarithms and exponentiation, and it presented this "bonus question":

Without using your calculator, determine which is larger: $e^\pi$ or $\pi^e$.

I wasn't able to come up with anything, and I'm just curious how you might tackle this, keeping in mind it came out of a college algebra textbook, less than halfway through, so I don't imagine the author had any super-advanced tactics in mind.
Comment: Similar to http://math.stackexchange.com/questions/7892/comparing-pie-and-e-pi
Comment: Ah, I see this has been asked before (I didn't find it when I searched initially).
Comment: It is a bit hard to search for, I agree, but it is kind of a classic. I would have been surprised if it had never been asked before on this website ^^
Comment: @ivan: have you had calculus?
Comment: @robjohn: yeah, but it was quite a while ago. I started getting into statistics, and found I needed a calc review. I started reviewing calc and found I could really use some precalc review. Etc... :)
Answer: Consider the function $x^{\frac{1}{x}}$. Differentiating gives $x^{\frac{1}{x}}(\frac{1}{x^2})(1-\ln x)$, so the function attains its global maximum at $x=e$.
Thus $e^{\frac{1}{e}} \geq \pi^{\frac{1}{\pi}}$, and it is clear that the inequality is strict, so $e^{\pi}>\pi^{e}$.
Comment: @deftfyodor Why not? We cover differentiation in grade 10 here. At college with those types of bonus questions, you would assume that differentiation would have been taught already.
Comment: He's working from a college algebra textbook, there is no reason to suspect that he even knows what differentiation is.
Comment: I have taken calculus, but I'm reviewing algebra in order to shore up the fundamentals before reviewing calculus. The author keeps stopping short of using calc, so I'm pretty sure there's another way to solve this. I like your solution though.
Comment: @user1887919: the derivative of $x^\frac{1}{x}$ is $> 0$ for $x < e$ and $< 0$ for $x > e$. So the global maximum at $x=e$ is unique.
Comment: Wow!  Very nice.  +1
Comment: I've never seen this solution, but it's probably my favorite now. +1
Comment: @deftfyodor I think that using differentiation for college algebra is perfectly fine. Not to mention that it is supposed to be a "bonus question".
Comment: Can someone explain the very last step? Why is it clear that the inequality is strict? Thanks :)
Comment: How is this answer upvoted more times than that by @nkhuyu?! This doesn't even answer the question!
Answer: If you know Taylor expansion: then
$$e^x=1+x+\frac{x^2}{2!}+...$$
We can get (Or you may take derivative to prove it)
$$e^{x}>1+x, \forall x>0$$
Then set
$$x=\frac{\pi}{e}-1>0$$
We get
$$e^{\frac{\pi}{e}-1}>1+\frac{\pi}{e}-1\Leftrightarrow \frac{e^{\frac{\pi}{e}}}{e}>\frac{\pi}{e}\Leftrightarrow e^{\frac{\pi}{e}}>\pi\Leftrightarrow e^{\pi}>\pi^e$$
Comment: I would have never thought $e^x>1+x$ was enough, +1.
Comment: And why the downvote?
Comment: Wow, I like. I'm not familiar with Taylor expansion, but that's awesome!
Comment: @ivan If you really want to, you can prove that $e^x>1+x \, \forall x>0$ without using differentiation or Taylor series.
Comment: Indeed I found this proof even more interesting than the others.
Comment: I found Taylor expansions are very powerful! But sometimes, it is hard to come up with it.
Answer: Note that if $f(x) = \dfrac{\log(x)}x$, we have
$$f'(x) = \dfrac{x \times \dfrac1x - \log(x)}{x^2} \begin{cases} < 0 & \forall x > e\\ > 0&  \forall x < e\end{cases} $$
Hence, $f(x)$ is a strictly montone decreasing function for $x \geq e$ and strictly montone increasing function for $x \leq e$. Since $\pi > 3 > e$, we have
$$f(\pi) < f(e) \implies \dfrac{\log(\pi)}{\pi} < \dfrac{\log(e)}{e} \implies \pi^e < e^{\pi} \implies \pi^{1/\pi} < e^{1/e}$$
Comment: In fact, $e^x\gt x^e$ for all $x\ge0$ and $x\ne e$ (+1)
Answer: So, we want to prove $e^\pi>\pi^e$. Taking $\log$ (where $\log$ means $\ln$) of both sides tells us this is equivalent to showing that
$$\pi\log(e)>e\log(\pi)$$
or
$$\frac{\log(e)}{e}-\frac{\log(\pi)}{\pi}>0$$
But,
$$\frac{\log(e)}{e}-\frac{\log(\pi)}{\pi}=-\int_{e}^{\pi}\frac{d}{dx}\left(\frac{\log(x)}{x}\right)  dx$$
but,
$$-\frac{d}{dx}\left(\frac{\log(x)}{x}\right)=\frac{\log(x)-1}{x^2}$$
Thus, we see that
$$\frac{\log(e)}{e}-\frac{\log(\pi)}{\pi}=\int_e^\pi \frac{\log(x)-1}{x^2} dx\,$$
Since, for $x\in(e,\pi)$ we have that
$$\frac{\log(x)-1}{x^2}>0$$
it follows that
$$0<\int_e^\pi \frac{\log(x)-1}{x^2}dx=\frac{\log(e)}{e}-\frac{\log(\pi)}{\pi}$$
Answer: Another way of doing it:
Since $\ln x$ is monotonically increasing for $x>0$, by taking the log we see that $e^\pi > \pi^e$ iff $\pi > e\ln\pi$.  Taking the natural log again we see this is true iff $\ln\pi > 1 + \ln\ln\pi$.
To show this, consider the function $f(x) = \ln x - 1 - \ln\ln x$.  Then $f'(x) = \frac1x - \frac{1}{x\ln x}$.  This derivative is continuous for $x>0$ and has one zero at $x = e$.  It is easy to see that $f' < 0 $ for $x < e$ and $f' > 0$ for $x > e$, so $x = e$ is a minimum.
Therefore $f(\pi)$ > $f(e) = 0$, which means $\ln\pi > 1 + \ln\ln\pi$, which by the above iffs means $e^\pi > \pi^e$.
Answer: This may not help much, but if you know your $\ln$-values well, and/or have encountered $\ln(\pi)$:
Note that $\ln(e^\pi) = \pi$ and $\ln(\pi^e) = e\ln(\pi)$, and we have that $\pi > e\ln(\pi)$.
Hence $\;e^\pi > \pi^e$.
But admittedly, the inequality isn't immediately obvious! (which can be seen if you do approximate with a calculator!)
Comment: Yes, this is kind of a non-answer at the moment. You still need to find a method to show that $\pi > e \ln{(\pi)}$, as Jen proposes above, simply saying it is so is equivalent to saying that $e^{\pi} > \pi^e$ is so. Unless this is somehow an obvious fact that everyone just knows, but I'm not seeing it.
Comment: I can't speak for others, but I had calculus before college algebra (as opposed to high school algebra). In any case, calculus doesn't seem unreasonable. However, the OP *did* specify no calculator.
Comment: "Without using your calculator..."
Comment: You can get that $\pi>e\ln(\pi)$ without using a calculator by showing that $x/e\geq\ln(x)\forall x$, which is straightforward when looking at the derivatives.
Comment: @Thomas - Yes, I know there are ways suggested that work, but the OP indicated that this problem was an exercise in a *College Algebra* textbook, and was perplexed as to how this can be shown using material one would have encountered *at that point*, which certainly precedes calculus and derivatives.
Comment: @robjohn I was trying to restrict myself to what one will have encountered only up to and including College Algebra, per the OP's request.
Comment: If you can calculate elnpi, why don't you just directly calculate the values then compare?

A question comparing $\pi^e$ to $e^\pi$


Problem with cookie and session cache

Question: I have a problem with the Drupal cache. The cache remembers session and cookie values. Everything works fine when I'm logged in or when I completely turn off any cache.
Is it possible to use cookies and avoid they are cached for anonymous users?
Answer: First of all, you need to add the correct cache context when rendering cookie/session values. See https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts. Then you should no longer need to completely turn off caching and sessions should work fine, anonymous and logged in.
Using non-session cookies server-side can be a problem with reverse proxies in general and the built-in Internal Page Cache in specific. Disable it by triggering the kill switch on pages depending on cookies without a session:
<code>\Drupal::service('page_cache_kill_switch')->trigger();
</code>
Don't use this trigger too often, it disables all page caching. If you need it on the majority of your pages then uninstall the Internal Page Cache, but keep the Internal Dynamic Page Cache enabled. If the dynamic page cache is too slow then put a third-party page cache in front which has the options you need to manage your cookies.

Problem with cookie and session cache


Configuring Apache for localhost

Question: I am new to Linux and Apache. I have tried to configure Apache2 to serve a website I develop on my local Linux Mint machine. I have not attepted to use PHP yet.
In spite of trying to follow all the instructions, I still got a 404 Not Found or 403 Forbidden.
The name of the directory that holds the website is Web and has permissions
drwxr-xr-x  4 www-data www-data   4096 May 15 18:46 Web

I also tried my own user group with no luck. All files inside Web have the usual r-x or r-- permissions for both Group and Others.
/etc/hosts is
127.0.0.1   localhost

/etc/apache2/ports.conf is
Listen 127.0.0.1:80

/etc/apache2/sites-available/Web.conf is
<VirtualHost 127.0.0.1:80>

    ServerName Web

    ServerAdmin webmaster@localhost
    DocumentRoot /xxx/xxxx

</VirtualHost>

Note that /xxx is my custom partion on my local machine and xxxx is a directory in this partion.
/etc/apache2/sites-enabled is
lrwxrwxrwx 1 root root 27 May 23 13:04 Web.conf -> ../sites-available/Web.conf

Finally, the /etc/apache2/apache2.conf included this
<Directory /xxx/xxxx/Web/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

I finally did get localhost to work, but it was not as above. I simply made a link to the directory Web in /var/www/html.
/var/www/html is
-rw-r--r-- 1 root root 11321 Apr 14 15:11 index.html
lrwxrwxrwx 1 root root    17 May 22 16:54 Web -> /xxx/xxxx/Web

This worked with no chances in apache2.conf and I did not have to enable the site (make a link with a2ensite).
The url
localhost/Web

now works with no errors.
It works, but it can not be the right way. What am I doing wrong?
Comment: Have you reloaded the Apache config or restarted the server after changing its config? On Ubuntu/Debian, it could be done using `sudo service apache2 reload`. Try reloading it and edit your answer appropriately.
Comment: Yes, I have done this every time I have made a chance, either sudo service apache2 reload or sudo service apache2 restart.
Comment: What do logs say?
Comment: The error log in /var/log/apache2 only reports each time I reload Apache. The access log typically only says this: `localhost:80 127.0.0.1 - - [23/May/2017:15:43:52 +0200] "GET /Web/ HTTP/1.1" 404 494 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.` I don't know how to get more information out of the logs.
Comment: I have seen that this post has had a number of hits. Therefore I think it is necessary (over 2 years later) to clarify the issue.  If you host **multiple** localhost websites, add a link to each one in /var/www/html. In addition, you need to add folder rights in apache2.conf. I hope this helps others.
Answer: /xxx/xxxx also needs to be readable by www-data in order to work as document root. You'll also need the permissions defined in a directory block.
<Directory /xxx/xxxx/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Or set your DocumentRoot /xxx/xxxx/Web
Comment: I set  `DocumentRoot /xxx/xxxx/Web ` and have ` ... `, set permissions on Web as `drwxr-xr-x  4 me www-data   4096 May 15 18:46 Web` (me is the owner) ,  did a `sudo service apache2 reload` and emptied the browser cache. With url `localhost/Web` I still got a 404 Not Found.
Comment: The `/data/Gallery/Web/` is of course what I called `/xxx/xxxx/Web/`. I used the xxx's to make things clearer. Thank you anyway for the answer.

Configuring Apache for localhost


Imprimir todas as cartas do baralho (Java)

Question: Olá.
Estou tentando criar um programa que imprima todas as 52 cartas do baralho, do 1 até o 10 e com todos os naipes (Paus, Ouros, Copas, Espadas) e também imprimir as cartas Valete, Dama e rei.
Achei o uso do "for" mais apropriado nesse caso, porém não tenho muito conhecimento com funções de repetições, gostaria de saber como imprimir uma "String" utilizando o "for"?
Estou utilizando essa lógica mas ela não é prática, pois eu teria que criar um "for" para cada número, preciso de uma lógica que simplifique isso.
<code>    for (int i = 1; i <= 10; ++i) {
        System.out.println(i  +  " De Paus");
    }

    }
}
</code>
Answer: Não sei se foi na hora de copiar aqui, mas tem muitos fecha colchetes ali.
Eu te recomendaria estudar arrays, pensa neles como um conjunto de variáveis, ao invés de ter um valor int na variável tu tens um array (conjunto) de 13 ints dentro desse array.
Tu pode ter um array de naipes e depois disso usar o for para fazer o que tu fez, ou um array de naipes, sendo que cada item é outro array para as cartas.
Depois tu pode percorrer esse array (chamamos de iterar no array) para imprimir.
Segue um link com uma referência inicial para ti ter como base, conteúdo do DevMidia
Comment: Certo, obrigado ! Vou dar uma estudada..
Comment: @CésarAugusto se der certo não esquece de aceitar a resposta como correta, é importante para outras pessoas que venham a ter dúvidas semelhantes no futuro
Comment: Farei isso.. Mas uma dúvida, nesse link ele está criando o Array com "int" , se eu quiser criar um Array de naipes eu não teria que guardar como "String" ?
Comment: Arrays podem ser do tipo que tu quiser, pode ser um array de int, String, se tu quiser um Array de Arrays, isso é o que chamam de Matriz
Comment: Entendi, no caso de um array de String essa seria a forma correta de declarar ?

String[] naipesCartas = {"Copas,Ouros,Espadas,Paus"};
Comment: Uma String é limitada pelas aspas, então o correto é usar `String[] naipesCartas = {"Copas","Ouros","Espadas","Paus"}`, assim tu tens 4 strings sendo passadas pro teu array, no teu exemplo tinha apenas uma string, com o conteúdo sendo o nome dos 4 naipes.
Comment: Quando for escrever código usa um ` antes e depois do código para ficar mais legível.
Comment: Perfeito ! Estou conseguindo criar uma lógica com base no material que você me enviou, não é tão difícil, obrigado pela ajuda !
Comment: De nada, a comunidade está aqui para isso, ajudar quem está começando, qualquer dúvida sinta-se à vontade aqui no Stack Overflow


relation between exponentials in modulus operation

Question: I am high school student preparing myself to math olympics, I found the following question in my text book written in Hungarian,but I have translated it into English
Assume that we are in group $Z_p^*$ under multiplication operation. Our $p=97$ , It is observed that for any generator $k$ of $p$, $k^{x_1}=2$ and $k^{x_2}=5$ under modulo operation where $x_1$ is always even number and $x_2$ is always odd number.
I want to see the reason behind why $x_1$ is always even number and $x_2$ is always odd number. I know that $5$ is one of the primitve root of $97$, but what is the reason, is it a coincide ?
Can you please explain it, if you give links in your answers, i can learn the new terms and topics. I am smart high school student but if you write your answers detaily, it would be better for me .
Comment: Hint: what is the order of $2\pmod {97}$?  What about $5$?
Comment: @lulu 5 is generator,so its order is $p-1=96$, but it is even integer. question says that $k_2$ is odd
Comment: @lulu am I wrong ?
Comment: $5^{96}\equiv 1$ and $5^{97}\equiv5\bmod 97$; $97$ is odd
Comment: @J.W.Tanner but the other generators are derive from $x_2$ where $x_2$ and $96$ are coprime. I could not understand
Comment: If $5\equiv k^{2n}$ then $5^{48}\equiv \left(k^{2n}\right)^{48}=\left(k^{96}\right)^n\equiv1^n=1\pmod{97}$, contradicting that $5$ is a generator
Answer: Note that $k$ is a generator if and only if its multiplicative order modulo $97$ is $96$.
Since $5$ is a primitive root modulo $97$, it has multiplicative order $96$, as does $k$. But the order of $k^a$ is $\frac{96}{\gcd(96,a)}$.
So if $k^{x_2}\equiv 5\pmod{97}$, then $\gcd(96,x_2)=1$, so $x_2$ is odd.
For $2$, note that the multiplicative order of $2$ modulo $96$ is $48$. That means that the order of $k^{x_1}$ must satisfy $48=\frac{96}{\gcd(96,x_1)}$, which requires $\gcd(x_1,96)=2$. In particular, $x_1$ must be even.


Can Websockets be combined with Inter Process Communication?

Question: I wonder if a server-side application uses Websockets for communicating
with a Web browser, can this server-side application also use
Inter Process Communication?
The idea is to use the WildFly Web server to execute an application using
Websockets. This application shall also be able to communicate with
another process. The server-side application shall thus be able to listen
both on events from the Web client and from the other process.
All applications and the other process are implemented in Java.
All help in this area is appreciated!
Thanks
Comment: Why wouldn't it be possible? Do you foresee running into some problem?
Comment: Thanks Gaelan and immibis for your answer! The reason for my question was just that I was unsure about this area. I have never used IPC together with Websockets before.
Answer: Yup, this should work fine. Neither of these features should affect each other in any way.


Universal cover of a $3$-manifold is isometric to a cylinder

Question: Let $(M^3,g)$ be a compact, connected and orientable Riemannian $3$-manifold with boundary. Suppose that the universal cover of $M$ is isometric to the right cylinder $\tilde{M} = D \times \mathbb{R}$, where $D$ is a geodesic ball of the round unit sphere $\mathbb{S}^2$. Is it true to assert that $M$ is isometric to $D \times \mathbb{S}^1(r)$, where $\mathbb{S}^1(r)$ denotes the round circle of radius $r$, for some $r > 0$?
Answer: In this situation, you have to have $D=S^2$ since otherwise $\tilde{M}$ is incomplete which is impossible. The manifold $M$ need not even be homeomorphic to the product: It can be the total space of a nontrivial circle bundle over the projective plane.

Since in the edit you indicated that $M$ is a manifold with boundary, if the boundary is nonempty, $M$ has to be homeomorphic to $D\times S^1$, where $D$ is the closed 2-disk. However, it need not be isometric to a product, just take an infinite cyclic group $G$ acting on $D\times R$ freely and generated by a skew motion (with nontrivial rotational component). Then $M:= (D\times R)/G$ is not isometric to a product.
Comment: I am considering $M$ to have nonempty boundary.
Comment: A cover of a manifold with non-empty boundary always has non-empty boundary so it cannot be homeomorphic to $D \times \mathbb{R}$ if $M$ has non-empty boundary.
Comment: @NickL: Sorry, I cannot follow the logic of your comment. Of course a compact manifold with nonempty boundary can be covered by the product of a closed disk with the real line.
Comment: Oops, I assumed it was an open disk. You are right, thanks.


Como obter a referência à ListView de um ListFragment?

Question: Estou com um ListFragment tentando acessar a ListView em que o Adapter inseriu os objetos, mas o findViewById está retornando null, alguém tem alguma ideia?
O código do fragment em XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
    android:id="@+id/listViewTipos"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</ListView>
<RadioGroup
    android:id="@+id/rgTipo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
<RadioButton
    android:id="@+id/rbTipo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</RelativeLayout>

O código do Adapter:
public class TipoAdapter extends ArrayAdapter {
    private ArrayList<Tipo> tipos;
    private Context context;
    private int mResource;
    public TipoAdapter(Context context,int resource,ArrayList<Tipo> tipos) {
        super(context,resource,tipos);
        this.tipos = tipos;
        this.context = context;
        mResource= resource;
    }

    @Override
    public int getCount() {
        return tipos.size();
    }

    @Override
    public Tipo getItem(int i) {
        return tipos.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if(view == null){
            view= LayoutInflater.from(context).inflate(R.layout.fragment_tipo_trilha,viewGroup);
            holder= new ViewHolder();
            holder.rb=(RadioButton) view.findViewById(R.id.rbTipo);
            view.setTag(holder);
        }else{
            holder=(ViewHolder)view.getTag();
        }
        Tipo b = getItem(i);
        holder.rb.setText(b.tipNome);
        return view;
    }

    private static class ViewHolder{
        RadioButton rb;
        public ViewHolder(){
        }
    }
}

O código do fragment:
public class TiposFragment extends ListFragment implements ListView.OnItemClickListener{
private ArrayList<Tipo> tipos;
private TipoAdapter tipoAdapter;
private int selecionado;

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    try {
        Bundle bundle = getArguments();
        if(bundle!=null){
            tipos=bundle.getParcelableArrayList("tipos");
        }

    }catch (Exception e){
        Toast.makeText(getContext(),e.toString(),Toast.LENGTH_LONG).show();
    }

    if(tipos!=null) {
        try {
            tipoAdapter = new TipoAdapter(getContext(), R.layout.fragment_tipo_trilha, tipos);
            setListAdapter(tipoAdapter);
            ListView listaTipos = (ListView) getView().findViewById(R.id.listViewTipos);//returning null
            listaTipos.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            listaTipos.setOnItemClickListener(this);
        }catch (Exception e){
            Toast.makeText(getContext(),e.toString(),Toast.LENGTH_LONG).show();
        }
    }

}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    selecionado=tipos.get(i).tipCod;
}

Answer: Para tirar partido de todas as funcionalidades do ListFragment a ListView deverá ter o id declarado assim:
android:id="@id/android:list"

ou
android:id="@android:id/list"

Assim é possível obter a referência à ListView recorrendo ao método getListView():
ListView listaTipos = getListView();

Deverá também implementar o método onCreateView() do ListFragment.
Qualquer coisa assim:
@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.list_fragment, container, false);
   return view;
}

Substitua R.layout.list_fragment pelo nome do layout do seu fragment.
Comment: Muito Obrigado!
Comment: Mas Eu ainda não consigo utilizar a ListView, o setOnItemClickListener não funciona, se a ListView está certa? qual pode ser o problema?
Comment: Isso é outro problema. O melhor é fazer outra pergunta com o código actualizado.


Why add before dividing in this equation?

Question: For the following equation, I know the correct answer is $9$:
$$
x / 3 + 2 = 5
$$
You subtract $2$ from each side, and the multiply each side by $3$...
But why do you subtract the $2$ first?
Doesn't the order of operations say I should do division before addition?
Comment: The order of operations isn't referring to the order you perform operations, it's there to tell you what an expression written on paper actually means. So the expression that you've written means that $x$ has first been divided by $3$, and then $2$ has been added to it, and the result is $5$. You are free to perform further operations in any order you like, as long as you perform the same operation to both sides!
Comment: It does, as far as the division of $x$ is concerned.  However, when solving for $x$ you undo all operations around it, which means that you enact them in reverse order.
Comment: Is there some reason why my answer was down-voted.  In particular, @user138021, do you have some objection to it?
Comment: @MichaelHardy I did not down-vote your answer. Maybe it was down-voted because many of the other answers say that the order of operations does not matter as long as the equation remains balanced, while your answer implies that there is a specific order? But, again, I did not down-vote and obviously still have a lot to learn, so I am only speculating.
Answer: Any order of operations is fine, as long as you are consistent in applying the same operation to both sides of the equation in every step. If you want to multiply by $3$ first:
$$
\frac{x}{3} + 2 = 5
$$
Multiply both sides by $3$:
$$
x + 6 = 15
$$
Subtract $6$ from both sides:
$$
x = 15 - 6
$$
Just work out the solution:
$$
x = 9
$$
Look at equations as a scale balance: anything you do will keep the scale in balance as long as you do it to both sides. The trick is to come up with a sequence of operations that eventually leaves the unknown on one side, and only knowns (in this case, numbers) on the other.
As a bad example, when we have $x+6=15$ we could, if we wanted to, decide to add $100$ to both sides. The equation would still be perfectly valid, but we wouldn't be any closer to finding $x$!
Finding a good sequence of operations will be challenging at first, but after some practice, it will become second nature.

If you were taught to solve equations in terms of "a $+$ when moved across the $=$ becomes a $-$", etc., I suggest that you forget all that and think instead in terms of a scale balance. This was certainly a breakthrough moment for me.
PS: The "rules" you refer to are just a convention for working out
expressions with non-existent or ambiguous parentheses, and have nothing to do with solving equations.
Answer: No, you're getting confused. The "order of operations" doesn't matter here, it's only for solving an expression (i.e. $4(5)-\left(\frac52\right)^3$). Here you just do something to two sides that are equal. You can choose whatever you want to do to both sides, but you have to make sure that you are doing it to both sides. You don't have to subtract 2 first, you can also multiply by 3 first:
$$3\left(\frac{x}3+2\right)=3(5) \\ x+6=15 \\ x=9$$
And you will get the same answer as subtracting first:
$$\left(\frac{x}3+2\right)-2=(5)-2\\\frac{x}3=3\\x=9$$
Comment: Well, you can do anything you want as long as it is reversible! (i.e. you cannot multiply by $0$, or square, else you're gonna get extra solutions...)
Comment: @PedroTamaroff you can square as long as both members have the same sign.
Answer: What gets done last gets undone first.  Since you do division first, you undo division last.
Comment: Despite its silly sounding. this is a perfectly valid answer. Sometimes to undo math, you just have to do all the parts backwards
Comment: Is there some reason for the down-votes here?  Down-votes should be explained.
Comment: They should be. Maybe they just thought that it wasn't explained enough.
Comment: Exactly. We multiply before we add, and we put on soicks before we put on shoes. Therefore, to isolate $x$ (or your feet) you have to subtract  (put off the shoes) first
Answer: As regards correctness of the solution, the order is irrelevant as long as the operations are legal.
$$\frac x3+2=5.$$
First times $3$:
$$x+3\cdot2=3\cdot5,\\x+6=15,$$
followed by minus $6$:
$$x=15-6,\\x=9.$$
Or first minus $2$:
$$\frac x3=5-2,\\\frac x3=3,$$
followed by times $3$:
$$x=3\cdot3,\\x=9.$$
It's a matter of taste, except that in the first case you perform two multiplies and one subtract, vs. one subtract and one multiply in the second.
Answer: Order of operations more so tells you how you should read the problem unambiguously. Here we have "$x$ is divided by $3$, THEN added with $2$ to achieve $5$." To figure out what $x$ was originally, we sort of backtrack.
What did the equation look like before we added $2$?
$$x/3=5-2$$
Then what was it before we divided by $3$?
$$x=(5-2)\times3$$


.NET - MySQL query parameter from non user input

Question: I understand that using parameters with your queries prevents SQL injection (when obtaining values from user input). But if I wanted to construct a query that uses predefined values e.g.
MySqlCommand Command = Connection.CreateCommand();
Command.CommandText = "SELECT employee_address FROM employees WHERE employee_name = @employee_name";
Command.Parameters.AddWithValue("employee_name", "John");

Can I not use this instead?
MySqlCommand Command = Connection.CreateCommand();
Command.CommandText = "SELECT employee_address FROM employees WHERE employee_name = 'John'";

Is it necessary to use parameters in this scenario?
Can I also do it this way?
string employee_name = "John"; //value depends on some sort of selection (not user input)

MySqlCommand Command = Connection.CreateCommand();
Command.CommandText = "SELECT employee_address FROM employees WHERE employee_name = '" + employee_name + "'";

Comment: If you don't take this `'John'` as an input, no, not necessary.
Comment: Then your code is fine
Comment: @Joachim - See the UPDATE - the value 'John' may be something else say e.g. 'Jack' depending on some sort of selection, would that make any difference?
Comment: @langjacques Actually, reading up on the subject, it seems MySQL still only has a query cache, not a query _plan_ cache. The query cache will not have any impact on your parameterization, while a query plan cache would have had. In other words, the statements should behave the same cache wise, parameterized or not.
Comment: @Joachim - OK, thanks for the info!
Answer: I recommend always using parameters. With a string it is simple, but guess you have a boolean, decimal or date. It helps not to think about the formatting.
With parameters your sql-statement can be shorter if you use @0, @1, @2. You could even write a function with a param-array which replaces according to the order of @0, @1, @2. This saves a lot of code. (e.g. ExecuteSql(sql as string, paramarray myParameters as object)


Can't access web service with server name - only with ip address

Question: I have a web service running under IIS 6.
I changed the identity of the application pool to a specfic user (it was under local system).
Since this change I can't access the service using the server name anymore. I can access the service only by using the IP of the server.
I want to access the service using the server name and not the IP address.
What went wrong?
Answer: I doubt that the change of the application pool identity is related to this issue.
I suspect a missing host header or another web site claiming the name. If a web site accepts all host headers (there could only be one per IP adress in IIS) and another defines a specific host header (your server's name for example), then the second web site "wins" and will process the requests for that host header.
Also, check your DNS settings. Does nslookup SERVERNAME resolve the right IP address?
Answer: Check this question - it seems to be the same situation.
Comment: Unfortunately, that question doesn't seem to have a good, accepted  answer...


The definition of syzygies - free or projective?

Question: For a module $M$ there is always a surjection $F \to M$ with $F$ free. As free modules are projective, there is always a surjection $P \to M$ with $P$ projective, and one may form the first syzygy $\Omega^1(M) := \text{ker}(P \to M)$. Iterating this process one obtains a projective resolution, and one can form the extension groups which can be shown to be independent of the choice of $P$ and the surjection.
The general impression I get from the stub Wikipedia article is that they here demand the modules to free, i.e. they form the syzygies (and thereby the extension groups) from a free resolution. While the word syzygy is never mentioned in Hatcher (I ctrl+F'ed it!), this seems to be the general approach taken in the formation of extension groups there as well.
As free implies projective, is this simply a case of "Yes, these things may be formed by projective modules, but for us it will be convenient to work with free modules" or is there a significant distinction to be made here? In particular, is it often the case that there is no surjection $P \to M$ with $P$ projective but not free?
Comment: For your last sentence: over a local ring, every projective module is free.
Comment: That's a strong point in favor of those who define this in terms of free moduels.
Comment: Moreover, over any PID (for example, $\mathbb{Z}$), every projective module is free. Correct me if I am wrong, but doesn't Hatcher use only $\mathbb{Z}$-modules? In such a case, there would be no distinction.
Comment: @Crostul, in general yes. Some exercises (at least one) is based on doing things over other modules.
Answer: As an argument in favor of using projective instead of free resolutions, I would point to this paper of Auslander and Reiten, in which they define (on page 6) syzygies in term of minimal projective resolutions. (There may be better references, but it is the first one I could find.)
For finitely generated modules over Artin algebras, the kernels of all surjections $P\to M$ with $P$ projective are the same up to projective direct summands, so whichever definition you use will give the same result if you pass to the stable category (that is, the quotient of the module category by the ideal of morphism factoring through a projective module).
Comment: This answer is very much in line with the direction I want to go. Thanks a bunch.


Cumulocity CEL Check if event exists

Question: I am trying to implement that if I send Event A it will create a new Event B if it does not exist. If Event B already exists it should update it instead.
I tried making a counter that counts occurences of the event but it didnt work.
Also it seems that "not exists" should be implemented but I do not get it to work.
Thanks in advance Greets
Comment: May you provide more details? Are you using Esper or Apama? Also if you post what you have done (ex: code), more people can help you!
Comment: Hey, I actually fixed the problem with creating an event if it does not exist. Right now I have the problem that I cannot access this event with UpdateEvent. When I create an event with an ID it still creates a automatic ID
insert into CreateEvent
select
    "testid" as id,
    "testtype" as type,
    part.event.source as source,
    "testext" as text,
from EventCreated as part

insert into UpdateEvent
select
    "testid" as id,
    "updatetext" as text
from EventCreated part
where
part.event.type = "testtype"

This does not work because the event is never giben the id correct
Comment: Oh and I am using Esper
Answer: If I got it well. Your are trying to create o update an event depend if an event with the same "key" exist.
One approach is to create your custom "key" like so:
insert into
   CreateEvent
select
   "testtype" as type,
    part.event.source as source,
    "testext" as text,
    {
     "mycustomkey" , "customValue",
     } as fragments
from EventCreated;

Here we create an event with a custom key => "mycustomkey" with a custom value  => "customValue".
Then when a new event is create you can use the "where" clause to know is you need to create a new event or update other event.
// create a new event if the firstEvent function return an event which
// the "mycustomkey" key if different to "customValue"
insert into
   CreateEvent
select
   "testtype" as type,
    part.event.source as source,
    "testext" as text,
    {
     "mycustomkey" , "customValue",
     } as fragments
from EventCreated e
where getString(cast(
      findFirstEventByFragmentTypeAndType("mycustomkey", "testtype"),
      com.cumulocity.model.event),
      "mycustomkey") != "customValue";

Here just update the event if the if the firstEvent function return an event which the "mycustomkey" if equal to "customValue"
insert into
   EventUpdated
select
   "testtype" as type,
    part.event.source as source,
    "testext" as text,
    {
     "mycustomkey" , "customValue",
    } as fragments,
    cast(findFirstEventByFragmentTypeAndType("mycustomkey",
    "testtype"), com.cumulocity.model.event), "mycustomkey").getId() as
     id
from EventCreated e
where getString(cast(
      findFirstEventByFragmentTypeAndType("mycustomkey", "testtype"),
      com.cumulocity.model.event),
      "mycustomkey") = "customValue";

This solution needs that "customValue" must we know it and also the findFirstEventByFragmentTypeAndType function assumes it is going to return the event you need. We can improve this solution buy calling other function like findOneEventByFragmentType, findEventByFragmentTypeAndSourceAndTimeBetweenAndType etc..(you can find more information here) and find the event you need using a  javascript function like :
 insert into
   CreateEvent
select
   "testtype" as type,
    part.event.source as source,
    "testext" as text,
    {
     "mycustomkey" , "customValue",
     } as fragments
from EventCreated e
where findTheCorrectEvent(
    findEventByFragmentTypeAndSourceAndTimeBetweenAndType(
    "mycusto mkey", "source", datefrom, dateTo).toJSON(),
    "customValue") = true;

 insert into
   EventUpdated
select
   "testtype" as type,
    part.event.source as source,
    "testext" as text,
    {
     "mycustomkey" , "customValue",
     } as fragments
from EventCreated e
where findTheCorrectEvent(
    findEventByFragmentTypeAndSourceAndTimeBetweenAndType(
    "mycusto mkey", "source", datefrom, dateTo).toJSON(),
    "customValue") = false;

create expression Boolean findTheCorrectEvent(evens, "customValue") [
   var result = _findTheCorrectEvent(events, "customValue")
   function _findTheCorrectEvent(events, referenceKey){
      var _events = JSON.parse(events)
      var result = false
      _events.forEach(function(event){
          if(event.mycustomkey === referenceKey) result = true
      })
      return result
  }
  result
];

Other approach, which in long term is easier, is create a microservice that do this. One microservice could check the last events created and check is the keys already exist and then update the same event otherwise create a new event.
In both solutions we need to create a "customkey" with a "customvalue" in other to find out if the event already exist. This "customkey" can be created using the a unique key like currentime which is a number.
Hope this can help you.
Good luck!
Comment: Hey, thanks for the elaborate answer first:)
It is sadly not a solution to my problem. Hmm.. I will try to give an example that makes my problem more clear..
For example, I want to create an event that acts like an updateevent for many other events - Lets call this event UpdateEvent.
So in my SmartRule the "from" and "where" clause will take this UpdateEvent into account and not the events actually being updated. I already tried a join in my "from" clause but the smartrule did not trigger anymore.
Comment: If I could create the events which are to be updated with an ID when UpdateEvent is called for the first time, everything would work.

The Update is triggered when my UpdateEvent is called and in my UpdateEvent I have already all IDs from the Events updated. But creating an event with an ID seems not possible.
Comment: Not, create your custom id is not possible, but you can create your customkey with the value you want as I described in the answer. Then you just need to save the customsKey value and not the IDs of the events.

Cumulocity CEL Check if event exists


hook_commerce_shipping_service_info() rate callback: What does the 'data' array do?

Question: hook_commerce_shipping_service_info() allows to specify a rate callback.
<code>function snailmail_commerce_shipping_service_info() {
  [..]
  $shipping_services['snailmail']['callbacks']['rate'] = '_snailmail_rate';
  return $shipping_services;
}

function _snailmail_rate($shipping_service, $order) {
  return array(
    // Amount in EUR Cent
    'amount' => 250,
    'currency_code' => 'EUR',
    // What is this?
    'data' => array(),
  );
}
</code>
Question: What can I do with the 'data' array in the return value?
Answer: Prices in commerce have a data array to establish the original components and component modifiers that these might have. For example, discounts and taxes add components to alter a price after taxes.
I'd say you can use 'data' array as storage of context information like the line items do (they store the product display where the product has been added to the cart) and the price system stores the components there, so it's needed to add elements to it.
Check commerce_price_component_add and commerce_tax_rate_calculate for examples on where this is used.
Comment: Hm, I am not sure I understand it completely, but it also went out of my focus of attention for the time being. Thanks anyway!


Derivative given separate constant for given function

Question: I do not understand what is meant here.
I must find the equation of the tangent line to a graph at $x = 0$ given the following function:
$y = 3e^x − 7x$
How do I compute this problem?
Comment: What don't you understand? This is as straightforward an exercise as they come.
Comment: This can help you.
http://tutorial.math.lamar.edu/Classes/CalcI/Tangents_Rates.aspx
Comment: Is your trouble with calculating the derivative $y'(x)$, or you know how to calculate derivative and you have problems with writing the equation of the tangent line (or both)? (EDIT: Now I see that my comment is a few months late. I should have looked at the date question was posted - the fact that it was recently bumped was what made me ask this comment. Still, even if the question is not new, adding some details into the question could improve it.)
Answer: HINT
The slope of the tangent line at a point is given by the value of the derivative at the point. So since, in your function $$\frac{\mathrm{d}y}{\mathrm{d}x}=3e^{x}-7$$
The value at $x=0$ (which is the slope) is $-4$.
Comment: It's probably best to give some hints rather than just give the answer.
Comment: It's also more efficient for homework cheating. Better to tease out the real issue.
Comment: @symplectomorphic I think that it's more clear to give an answer to the OP.
Comment: @Donnie If you already tried something, I think it's best if you add that to the answer.
Comment: @symplectomorphic OK. I edited.
Comment: "The value, and thus the slope of the derivative" should be "the value of the derivative, and thus the slope of the tangent line."
Comment: @symplectomorphic Done.
Comment: Giving a direct answer helps me work recursively to note where I went wrong. I appreciate the input though.
Comment: Okay then. Will do.
Answer: So you're starting with $y=3e^x-7x$. The derivative will give you, at every point, the slope of the tangent line to that point.
So you first need to find the derivative.
$$\frac{dy}{dx} = 3e^x-7$$
When you plug in an x-value to this, it's going to give you the slope of the tangent line. So, we're trying to find the slope at $x=0$, so we plug in $0$ for $x$.
Then you're going to want to use the linearization formula:
$$y = f'(k)(x-k)+f(k)$$
Where k is the x-value where you're trying to find the tangent line.
So when you plug in $x=0$, that's giving you $f'(k)$, which is $-4$.
You should be able to plug in from there.


How to deallocate objects in NSMutableArray?

Question:
i have this Mutable Array:
NSMutableArray *points = [pgroute getPoints:self];

where [getPoint...] do this:
{
 NSMutableArray *normPoints = [[NSMutableArray alloc] init];
 [normPoints addObject:@""];
 [...]
 return normPoints;
}

now,
points is an array of objects, right?
is correct to release *points array in this way?
for (int i = 0; i < [points count]; i++) {
    [(NSString *)[points objectAtIndex:i] release];
}
[points release];

or it is another correct way?
Xcode compiler, with RUN_CLANG_STATIC_ANALYZER tell me there is an

Incorrect decrement of the reference
  count of an object that is not owned
  at this point by the caller

How can i resolve this?
thanks,
alberto.
Comment: If you want to memory-manage that `NSMutableArray` yourself, you should consider renaming your method such that it contains the word `new`. This is to adhere to Apple's naming conventions that any methods with `alloc`, `init`, `new` or `copy` return objects that must be manually released.
Answer: If you want to empty the array, just do this:
[points removeAllObjects];

If you want to release the array, you can even skip that and release it right away:
[points release];

The array will handle releasing the objects on its own. Then again if you're only adding NSString literals (@"using this notation") to the array, they don't need to be released since they are constants. That's a different story of course; my point is that NSMutableArray will deal with releasing stuff where necessary for you.
Comment: removeAllObjects, remove also all object reference? It release the n objects in?
Comment: @pask: Yes, the moment you remove an object from the array, it releases its pointer to that object.


WPF Textbox and Label are overlapping

Question: I am learning WPF (Windows Presentation Foundation) on Visual Studio 2013. I have an issue with the layout of elements. I am using stackpanel and grid for element layout. Here is the simple layout which i have created:
... code omitted....

    <StackPanel Style="{StaticResource ersStackPanel}">
        <Grid Style="{StaticResource ersGrid}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="497*"/>
            </Grid.ColumnDefinitions>

        </Grid>
        <Grid Style="{StaticResource ersGrid}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="150*"/>
                <ColumnDefinition Width="347*"/>
            </Grid.ColumnDefinitions>

            <TextBox x:Name="VS" Grid.Column="1" Style="{StaticResource ersTextBox}" />

            <TextBox x:Name="EV" Grid.Row="1" Grid.Column="1" Style="{StaticResource ersTextBox}" />

            <TextBox x:Name="ENo" Grid.Row="2" Grid.Column="1" Style="{StaticResource ersTextBox}" />

            <ComboBox Grid.Row="3" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" FontFamily="Verdana" FontSize="10" Background="White"/>
        </Grid>
    </StackPanel>

... code omitted...

Style Resource
<Window.Resources>

</Window.Resources>

The problem is that all elements (Label, TextBox ..) are overlapping each other, Why they are not positioning like a stack (one after another) ??
Comment: because your grid has no rows and you are relying on your set Heights, Margins and Alignments to place your elements, if you want to "Stack" elements put them inside a `StackPanel` not a `Grid`
Answer: If you are using grid layout you need to define rows and columns. If u don't define them, XAML will stack them  one over the other. The last element defined will be the visible one.
<Grid>
 <Grid.RowDefinitions>
  <RowDefinition Height="*"/>
  <RowDefinition Height="*"/>
 </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
   <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*"/>
  </Grid.ColumnDefinitions>

  <TextBlock Text="A"/> // The first is assumed that it is Grid.Row="0" Grid.Column="0"
  <TextBlock Grid.Row="0" Grid.Column="1" Text="B"/>
  <TextBlock Grid.Row="1" Grid.Column="0" Text="C"/>
  <TextBlock Grid.Row="1" Grid.Column="1" Text="D"/>
</Grid>

This will look like this:
A B
C D
In your code the problem is that you are setting elements to the second, third and fourth row, but you didn't defined the rows in the first place.
Also remember that enumeration is Zero-based (First row is actually 0).

WPF Textbox and Label are overlapping


Known Hosts ECDSA Host Key Multiple Domains on One IP

Question: Hello, world!,
I have a VPS set up with multiple domain names pointing to it.  Arbitrarily, I like to access it via SSH through the domain name I'm dealing with.  So for example, if I'm doing something with example1.com, I'll log in with ssh email@example.com, and if I'm working with example2.com, I'll log in with ssh email@example.com.  They both point to the same user on the same machine.  However, because SSH keeps track of the server's fingerprint, it tells me that there is an offending host key, and makes me confirm access.
$ ssh email@example.com
Warning: the ECDSA host key for 'example2.com' differs from the key for
the IP address '22.214.171.124'
Offending key for IP in /home/me/.ssh/known_hosts:33
Matching host key in /home/me/.ssh/known_hosts:38
Are you sure you want to continue
connecting (yes/no)?

Is there a way to ignore this warning?  Thanks!
Answer: Add this to your .ssh/config file:
Host 184.108.40.206
   StrictHostKeyChecking no
   UserKnownHostsFile=/dev/null

This will disable the host key checking and the warnings, but only for that IP. It will also save the host key for that machine in /dev/null thus avoiding future mismatches.
Host example*.com
  StrictHostKeyChecking no
  UserKnownHostsFile=/dev/null

EDIT: My first answer wasn't exactly correct for your this case. These settings will take effect the next time you ssh into a matching hostname. The asterisk acts as a wildcard, so it will match example1.com, example2.com and so on.
Comment: Do I need to logout/login for it to take affect?  Or delete those lines from the `known_hosts` file?
Comment: You'll have to add one entry (Host + StrictHostKeyChecking + UserKnownHostsFile) for every domain. If you're only going to connect to the VPS or if you don't care too much about security, you could have a .ssh/config file with just two lines and nothing else: `StrictHostKeyChecking no` and `UserKnownHostsFile=/dev/null`.


Cookie not expiring per StartUp.cs settings

Question: I have tried a plethora of solutions over the course of 2 days and still have not been able to get this to work. What I want is for a user cookie to expire after a set amount of time
E.g. User A logs in and goes to home page, User A goes for a lunch break. User A comes back and clicks on the nav bar and gets redirected to the login page.
I have tried everything from AddAuthentication(), AddSession() and AddCookie() options all having an ExpireTimeSpan and Cookie.Expiration of my choosing. Nothing seems to work. The project uses ASP.NET Identity and I am aware this service should be called before the cookie options. Please see my current StartUp.cs below, this is the last thing i tried:
Startup.cs
public class Startup
    {
        public IConfiguration Configuration { get; }
        public IContainer ApplicationContainer { get; private set; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
                {
                    config.SignIn.RequireConfirmedEmail = true;
                })
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            //other services e.g. interfaces etc.
            services.AddAuthentication().AddCookie(options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.Expiration = TimeSpan.FromSeconds(60);
                options.LoginPath = "/Account/Login";
                options.LogoutPath = "/Account/Logout";
                options.AccessDeniedPath = "/AccessDenied";
                options.ExpireTimeSpan = TimeSpan.FromSeconds(5);
                options.SlidingExpiration = true;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddSession();

            var containerBuilder = new ContainerBuilder();
            containerBuilder.Populate(services);
            this.ApplicationContainer = containerBuilder.Build();
            var serviceProvider = new AutofacServiceProvider(this.ApplicationContainer);

            return serviceProvider;
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.ConfigureCustomExceptionMiddleware();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            //app.UseSession();
            app.UseMvc();
        }
    }

Answer: The following code isn't affecting the Identity cookie:

services.AddAuthentication().AddCookie(options => ...);

Instead, it's adding a new cookie-based authentication scheme, named Cookies, and configuring that. With all the standard Identity setup, this scheme is unused, so any changes to its configuration will have no effect.
The primary authentication scheme used by Identity is named Identity.Application and is registered inside of the AddIdentity<TUser, TRole> method in your example. This can be configured using ConfigureApplicationCookie. Here's an example:
services.ConfigureApplicationCookie(options => ...);

With that in place, the cookie options will be affected as intended, but in order to set a cookie with a non-session lifetime, you also need to set isPersistent to true inside your call to PasswordSignInAsync. Here's an example:
await signInManager.PasswordSignInAsync(
    someUser, somePassword, isPersistent: true, lockoutOnFailure: someBool);


Copy data to file in matrix format

Question: I have a loop which returns 4 values every time:
rowValue, columnValue, x, y.

I want to copy these values to a file in below format:
            columnValue1 columnValue2 . . . columnValueN
rowValue1       x,y         x,y        . .      x,y
rowValue2       x,y         x,y        . .      x,y
.                .           .          ..       .
.                .           .          ..       .
.
rowValueN

I want to map x,y values at intersection of column and row values.
x,y values are of type Double and are random.
Please let me know how to do this? or if there is a java library available?
Comment: Do you get the values in defined order (eg. from *x1,y1*, through *x1,y2*, **x1,y3*, ..., *x1,yN*, .., *xM,yN*)?
Comment: based on rowValue and columnValue, x and y values are calculated. They are of type Double and are random. I also edited my question.
Comment: Are you know at least how many rows and columns is?
Comment: No. I get that data from a webservice
Comment: I think you have to store data in array and create method which stores this array in file. And after each adding value you have to clean file and write it again. Or, if you don't need to update file in real time, you can store data in array and write it all to file at the end. It's hard (I think) to update file and keep it well formated
Comment: Could the columns have gaps in a row? e.g. one row `{rowValue1, columnValue1, x1, y1} and {rowValue1, columnValue2, x2, y2}` another row `{rowValue2, columnValue1, x3, y3} and {rowValue2, columnValue3, x4, y4}`. Or all matrix points are filled?
Comment: Why not use an existing format for spreadsheets, like CSV?
Answer: Following sketch might be a solution for your requirement.

store the loop values in a map Map<rowValue, Map<columnValue, Double[]>>, keep a set of columnValues
output of the columnValues in the first line
iterate over all entries of map Map<rowValue, Map<columnValue, Double[]>>

iterate over all stored columnValues
if the map Map<columnValue, Double[]> contains a value pair for a columnValue
output the values
else output blanks

Here a small working code snippet (see it as a verbose PoC, not as a final solution suiteable for production use).
public static void main(String[] args) throws Exception {
    Object[][] input = {
        {"rowValue1", "columnValue2", 33.33, 44.44},
        {"rowValue2", "columnValue1", 55.55, 66.66},
        {"rowValue1", "columnValue1", 11.11, 22.22},
        {"rowValue2", "columnValue3", 77.77, 88.88},
    };
    Map<String, Map<String, Double[]>> map = new TreeMap<>();

    Set<String> columnHeaders = new TreeSet<>();
    for (Object[] in : input) {
        String rowValue = (String) in[0];
        String columnValue = (String) in[1];
        columnHeaders.add(columnValue);
        Double xValue = (Double) in[2];
        Double yValue = (Double) in[3];
        if (map.containsKey(rowValue)) {
            Map<String, Double[]> rowMap = map.get(rowValue);
            rowMap.put(columnValue, new Double[] { xValue, yValue });
        } else {
            Map<String, Double[]> rowMap = new TreeMap<>();
            rowMap.put(columnValue, new Double[] { xValue, yValue });
            map.put(rowValue, rowMap);
        }
    }

    System.out.print("            ");
    for (String header : columnHeaders) {
        System.out.printf("%s  ", header);
    }
    System.out.println("");

    for (Map.Entry<String, Map<String, Double[]>> entry : map.entrySet()) {
        System.out.printf("%-12s", entry.getKey());
        Map<String, Double[]> rowMap = entry.getValue();
        for (String header : columnHeaders) {
            if (rowMap.containsKey(header)) {
                Double[] columnValue = rowMap.get(header);
                System.out.printf("%s, %s  ", columnValue[0], columnValue[1]);
            } else {
                System.out.print("              ");
            }
        }
            System.out.println("");
    }
}

Copy data to file in matrix format


From oscillating speed along curve to constant speed along same curve

Question: Let a parameterization of the curve
$$
\{(x,y)\in \mathbb{R}^2: x=y, \|(x,y)\|\leq 1\}
$$
be $\{\alpha(t)\}_{t\in [0,t^\alpha]}$ such that $\alpha(t) = (1,1)*(-cos(t^2))$. Determine from this parameterization another parameterization $\{\beta(t)\}_{t\in [0,t^\beta]}$ such that the corresponding speed along the curve $\{\{\|\beta'(t)\|\}_{t\in [0,t^\beta]}$ is constant $s$. That is, determine a final time $t^\beta$ and a function $f$ such that $\beta = \alpha \circ f$, $f(0) = 0$, and for every $t$ in $[0,t^\beta]$, $s=\|(\alpha\circ f)'(t)\|$. It is that
\begin{align}
 s&=\|(\alpha\circ f)'(t)\|\\
&= \|\alpha'(f(t))f'(t)\|\\
&=\|\alpha'(f(t))\||f'(t)|\\
&=\|(1,1)\sin(f(t)^2)2f(t)\||f'(t)|\\
\end{align}
Hence, this is a differential equaion in terms of $f$. When I try to numerically solve this it appears that I get into trouble due to the $\|(1,1)\sin(f(t)^2)2f(t)\|$ periodically assuming the value zero, which then forces |f'(t)| to be infinite. This occurs at the endpoints of the curve, where the velocity changes direction instaenously. Maybe I am missing a specification on the derivative of $\alpha\circ f$ that defines this change in velocity?
Comment: I constructed this example because I am trying to learn the subject better. Otherwise it would be more efficient to write down the parameterization by inspection.
Comment: Does anything prevent writing down the parametrization by inspection instead of inverting a non-elementary integral?
Answer: The theory is, if $\alpha$ is a regular parametrization (continuously-differentiable with non-vanishing velocity) on some interval $[0, t^{\alpha}]$, and if we define the arclength function $s$ by
$$
s(t) = \int_{0}^{t} \|\alpha'\|
$$
and set $\ell = s(t^{\alpha})$, then $s:[0, t^{\alpha}] \to [0, \ell]$ has a continuously-differentiable inverse since $s' = \|\alpha'\|$ is strictly positive, and the path $\beta = \alpha \circ s^{-1}$ has unit speed.
As you note, there is a theoretical obstacle in the proposed example: The velocity vanishes at the endpoint $\sqrt{\pi/2}$, so $\alpha$ is not a regular path and the inverse mapping is not differentiable at the corresponding endpoint. If we pick a positive upper bound $t^{\alpha} < \sqrt{\pi/2}$, however, things work out as expected.

The remarks below may not apply to your situation, but are included for posterity. In general, practical obstacles can arise when we try to reparametrize a regular path by arc length:

The arc length element $\|\alpha'(t)\|\, dt$ may have no elementary antiderivative.
Even if the arc length integral can be calculated in closed form, it may be impossible to invert in closed form.

Differential geometry textbooks carefully construct regular paths for which the arc length can be computed, and sometimes inverted. If we write down a "random" regular path, one of these two points is likely to obstruct our ability to "find" a unit-speed path.
Here are some examples where the arc length can be calculated, and (in some cases) explicitly inverted:
$$
\alpha(t) = (t^{2}, t^{3});\quad
\alpha(t) = (t, \cosh t);\quad
\alpha(t) = (t, \sqrt{1 - t^{2}});\quad
\alpha(t) = (t, e^{t}).
$$


spring and angulaJS(i am getting error like HTTP Status 404 )

Question: I am getting an HTTP Status 404 error in my controller.
Server code
@RequestMapping(value="/showMsg/",
method=RequestMethod.GET,produces=
{
"application/json"
})'

public ResponseBody String show(){
    HashMap hash = new HashMap();
    hash.put("msg", "welcome to spring angular js");
    return hash;
}

AngularJS code
$http.get('HelloWorld/showMsg').success(function(data){
    alert("Success");
}).error(function(data){
    alert("Error");
});

I get an HTTP Status 404 error.
Comment: It's clear that your URL is wrong. Can you show the complete class?
Answer: URL is wrong in this case.
Define correct URL something like below:
$http.get('http://localhost:8000/HelloWorld/showMsg')