Analyzing Set of all Perfect squares

Question: I have been reading Velleman's How to Prove book and the following statement in the book confuses me:
For example, suppose we wanted to define S to be the set of all perfect squares. Perhaps the easiest way to describe this set is to say that it consists of all numbers of the form $n^2$, where n is a natural number. This is written $S = \{n^2 \mid n \in \mathbb N \}$. Note that we could also define this set by writing $S = \{ x \mid \exists n \in \mathbb{N}(x=n^2)\}$
The last logical form confuses me. Shouldn't it be like this:
$S = \{ x \mid \forall n \in \mathbb{N}(x=n^2)\}$
Comment: The second describes the empty set. Since $1^2 \neq 2^2$, there is no $x$ that simultaneously equals all squares of natural numbers.
Comment: @DanielFischer Thanks, I get that now. Can you post that as an answer ?
Answer: The part on the left of the "$\mid$" is a "prototype" for an element of the set.  The part on the right describes what must hold for such a prototype to actually be in the set.  The first definition means you can find some $n$ so that your prototype $x$ is equal to $n^2$.  So, if e.g. $x$ is $36$, you can find $n=6$, so $x$ is in the set.  Your second definition would mean that $x$ could only be in the set if it were simultaneously equal to all $n^2$ for all $n$ and as there is no such $x$ your set would be empty.
Comment: What if `x` is `7` ?
Comment: If $x=7$ then there is no $n\in\mathbb N$ such that $n^2=x$, i.e. the sentence $\exists n \in \mathbb{N} (x=n^2)$ is false and thus $x\notin S$.

Analyzing Set of all Perfect squares


AWS : How to guarantee availability of static Private IP while bootstrapping

Question: I am launching EMR cluster and while bootstrapping I am assigning a Private IP address to it master node. So this get associated when cluster starts and gets released when cluster gets terminated.
How do i guarantee that this IP is always available for my cluster and no other process picks it up even when not in use.
Once I get this Ip, I submit my spark jars to 8998 port of this IP, using Apache livy REST API
So my use case is to expose the IP on master node, so that LIVY APIs can submit job to EMR.
Comment: Could you please tell us more about your use-case? For example, why do you want a static private IP address? There might be another way to achieve your objective (eg using DNS names), but you'll need to tell us more. Please edit your question to add details rather than adding a comment.
Comment: You can create a `network interface` and attach it to master node. But you need to configure other services (like yarn, hadoop, etc.) to work with the 2ndary network interface. Once the cluster is terminated your interface will automatically gets detached.
Answer: It is not possible to request a specific private IP address for the cluster.
Instead, I would suggest:

Create a Route 53 private hosted zone with a Record Set for the cluster (eg cluster.private)
After launching the EMR cluster, update the Record Set for the IP address of the master node
Have Apache Livy reference the cluster by DNS Name rather than IP address

Updating the Record Set can be done programmatically. A script would do something like:

Call list_clusters()
For each cluster, call describe_cluster()
Look for a tag (eg DNS=cluster.private)
If the DNS tag is present:

Update the named Record Set in Route 53 to use an A-Record to point to the IP address of the master node

This script would need to be triggered after the cluster is launched.
Comment: Thanks much. I will try this out and post here.


SQL syntax error urgnet

Question: I have this scrip that reports

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-5,5' at line 1

And can't seem to find the error.
This is the script would be happy to get any help.
<?
require_once("conn.php");
require_once("includes.php");
require_once("templates/HeaderTemplate.php");
require_once("pageList.php");
//  ADVANCED SEARCH
//require_once("advanced.php");
//require_once("templates/AdvancedSearchTemplate.php");
$showall = false;
if ($_REQUEST['stateid']) {
    $sql = "Select full_name From states where state_id = ".$_REQUEST['stateid'];
    $myr = mysql_query($sql) or die(mysql_error());
    $isAny = mysql_num_rows($myr);
    $state_name = mysql_fetch_array($myr);
    $show = "

Showing Listings For $state_name[full_name]

";
}
else {
    $show = "Showing All Listings";
    $showall = true;
}

//print "The Value Of ... ".$isAny;
//echo "
   ".$show;
if ($_REQUEST['stateid'])
    $addsql = "and re_listings.state_id=".$_REQUEST['stateid'];
else
    $addsql ="";
$q1 = "select * from re_listings, re_agents, re_priority where re_listings.AgentID = re_agents.AgentID and re_agents.PriorityLevel = re_priority.PriorityLevel and re_agents.AccountStatus = 'active' ".$addsql;
$rsQ = mysql_query($q1);
$total_records = mysql_num_rows($rsQ);
if($total_records== 0)
{
        $ListingTable = "
\n";
    $ListingTable .= "
\n$links
\n\t";
    $ListingTable .= "
\n
\n\t";
    $ListingTable .= "
\n
\n\n";
    $ListingTable .= "

No Results Was Found!";
require_once("templates/HeaderTemplate.php");
require_once("templates/SearchTemplate.php");
require_once("templates/FooterTemplate.php");
}
$records_per_page = 5; // no of records per page
$current_page_no = 1;

    if ($_REQUEST['page'])
    {
        $current_page_no = $_REQUEST['page'];
    }
    $pageL = new pageList($total_records, $records_per_page, $current_page_no);
    $pageL->generate();
//print $addsql."
";
//print "startRecord: ".$pageL->startRecord;
$q2 = "select * from re_listings, re_agents, re_priority where re_listings.AgentID = re_agents.AgentID and re_agents.PriorityLevel = re_priority.PriorityLevel and re_agents.AccountStatus = 'active' ".$addsql." order by visits desc LIMIT $pageL->startRecord,$pageL->numOfRows";
$r1 = mysql_query($q2) or die(mysql_error());
$lrows = mysql_num_rows($r1);
if($lrows > '0')
{
    $ListingTable .= "
\n";

    $ListingTable .= "
\n 	\n\t";

//  $ListingTable .= "<a class=BlackLink href=\"search.php?c=$_GET[c]&s=$_GET[s]&AgentID=$_GET[AgentID]&search_city=$_GET[search_city]&search_state=$_GET[search_state]&search_country=$_GET[search_country]&search_PropertyType=$_GET[search_PropertyType]&MinPrice=$_GET[MinPrice]&MaxPrice=$_GET[MaxPrice]&rooms1=$_GET[rooms1]&rooms2=$_GET[rooms2]&bath1=$_GET[bath1]&bath2=$_GET[bath2]&before=$_GET[before]&school=$_GET[school]&transit=$_GET[transit]&park=$_GET[park]&ocean_view=$_GET[ocean_view]&lake_view=$_GET[lake_view]&mountain_view=$_GET[mountain_view]&ocean_waterfront=$_GET[ocean_waterfront]&lake_waterfront=$_GET[lake_waterfront]&river_waterfront=$_GET[river_waterfront]&city=1&page=$_REQUEST[page]\">address	\n\t";

//  $ListingTable .= "<a class=BlackLink href=\"search.php?c=$_GET[c]&s=$_GET[s]&AgentID=$_GET[AgentID]&search_city=$_GET[search_city]&search_state=$_GET[search_state]&search_country=$_GET[search_country]&search_PropertyType=$_GET[search_PropertyType]&MinPrice=$_GET[MinPrice]&MaxPrice=$_GET[MaxPrice]&rooms1=$_GET[rooms1]&rooms2=$_GET[rooms2]&bath1=$_GET[bath1]&bath2=$_GET[bath2]&before=$_GET[before]&school=$_GET[school]&transit=$_GET[transit]&park=$_GET[park]&ocean_view=$_GET[ocean_view]&lake_view=$_GET[lake_view]&mountain_view=$_GET[mountain_view]&ocean_waterfront=$_GET[ocean_waterfront]&lake_waterfront=$_GET[lake_waterfront]&river_waterfront=$_GET[river_waterfront]&r=1&page=$_REQUEST[page]\">bed, bath, garage	\n\t";

//  $ListingTable .= "<a class=BlackLink href=\"search.php?c=$_GET[c]&s=$_GET[s]&AgentID=$_GET[AgentID]&search_city=$_GET[search_city]&search_state=$_GET[search_state]&search_country=$_GET[search_country]&search_PropertyType=$_GET[search_PropertyType]&MinPrice=$_GET[MinPrice]&MaxPrice=$_GET[MaxPrice]&rooms1=$_GET[rooms1]&rooms2=$_GET[rooms2]&bath1=$_GET[bath1]&bath2=$_GET[bath2]&before=$_GET[before]&school=$_GET[school]&transit=$_GET[transit]&park=$_GET[park]&ocean_view=$_GET[ocean_view]&lake_view=$_GET[lake_view]&mountain_view=$_GET[mountain_view]&ocean_waterfront=$_GET[ocean_waterfront]&lake_waterfront=$_GET[lake_waterfront]&river_waterfront=$_GET[river_waterfront]&p=1&page=$_REQUEST[page]\">price	\n";

    $ListingTable .= "
\n
\n\n";
    $ListingTable .= "
\n";

$start = $pageL->startRecord+1;
$end = $records_per_page*$current_page_no;
$totalpages = $pageL->getTotalPage();
if ($current_page_no==$totalpages)
$end = $pageL->getTotalRecords();
    $rec_info = "Showing Listings $start - $end";
    $ListingTable .= "
\n$rec_info
\n\t";

    while($a1 = mysql_fetch_array($r1))
    {

        $ListingTable .= "
\n\t";

        $ListingTable .= "";
        $ListingTable .= "
\n";

        $ListingTable .= "
\n\n$a1[PriorityName] listing	\n
\n";
//      $ListingTable .= "
$a1[PriorityName] listing
\n";
        $ListingTable .= "
\n\t";
//Price formatting
        $MyPrice = number_format($a1[Price], 2, ".", "'");
//State Formatting
    if(empty($a1[state_id]))
        $state = "Not Available";
    else
        {
            $state_id = $a1[state_id];
            $sql = "Select full_name from states where state_id=$state_id";
            $myrs = mysql_query($sql) or die(mysql_error());
            $statename = mysql_fetch_array($myrs);
            $state = $statename[full_name];

        }

    $ListingTable =$ListingTable."
Country: 	 $a1[country]	";
    $ListingTable =$ListingTable."State: 	$state
";
    $ListingTable =$ListingTable."
\n\tCity: 	$a1[city]	";
    $ListingTable =$ListingTable."Address: 	 $a1[address]
";
    $ListingTable =$ListingTable."
Price: 	 $$MyPrice	";
    $ListingTable =$ListingTable."SqMeters: 	 $a1[SquareMeters] sq.m.</TD
";
        $ListingTable .= "	\n\t";
        $ListingTable .= "
\n";

        $ListingTable .= "
";
        $ListingTable .= "
\n\n	\n
\n\n";
    }
    $ListingTable .= "
";

}
else
{
    $ListingTable = "
\n";
//  $ListingTable .= "
\n$links
\n\t";
    $ListingTable .= "
\n
\n\t";
    $ListingTable .= "
\n
\n\n";
    $show = "

No Results Was Found!

";

}
echo "
   ".$show;
/*
 if ($_REQUEST['stateid'] == 0){
echo "

<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" width=\"400\" height=\"275\">
  <param name=\"movie\" value=\"usmap.swf\">
  <param name=\"quality\" value=\"high\">
  <embed src=\"usmap.swf\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"500\" height=\"325\"></embed>\"
</object>

";
 }*/

require_once("templates/SearchTemplate.php");
require_once("templates/FooterTemplate.php");
?>

Comment: first alarm: "Select full_name From states where state_id = ".$_REQUEST['stateid']; Don't EVER put this in production, it's highly insecure. Did you hear about SQL injections ?
Comment: If you want to be responded instead of buried with downvotes do not use "URGENT", "IMPORTANT". It is neither urgent or important for anyone but you.
Comment: first thing to do: instead of writing `mysql_error()`, write `mysql_error() . " Query: queryhere", where queryhere is the query variable.
Comment: urgent isn't a word for stackoverflow
Comment: @yes123 "urgnet" even less :)
Comment: no @yes123 he wrote urgnet :)
Answer: Try this one,
$start_record = ($pageL->startRecord>=0) ? $pageL->startRecord : 0;

    $q2 = "

    select
        *
    from
        re_listings,
        re_agents,
        re_priority
    where
        re_listings.AgentID = re_agents.AgentID
        and re_agents.PriorityLevel = re_priority.PriorityLevel
        and re_agents.AccountStatus = 'active'
        ".$addsql."
    order by
        visits desc
    LIMIT
        $start_record,$pageL->numOfRows
    ";

Answer: Although it isn't apparent in the code, I think the query that is casuing error is this one:
$q2 = "

select
    *
from
    re_listings,
    re_agents,
    re_priority
where
    re_listings.AgentID = re_agents.AgentID
    and re_agents.PriorityLevel = re_priority.PriorityLevel
    and re_agents.AccountStatus = 'active'
    ".$addsql."
order by
    visits desc
LIMIT
    $pageL->startRecord,$pageL->numOfRows
";

You are probably passing a negative value in the limit clause, which you can't do.
You should check if $pageL->startRecord is less than 0 and if it is, change it to zero.
Answer: $ListingTable = "
\n";

I think you forgot the put "." on this.
$ListingTable .= "
\n";

In dreamweaver line no. 123

SQL syntax error urgnet


Visual studio 2019 Google test nuget package restore failing

Question: I have this error when I try to open some students' assignments in Visual Studio 2019, stating that nuget can't restore a package. I'm concerned about the direction of the slashes, but have no idea how to fix this. The package is googletest. It says to look at the Error list window, but unfortunately, this is the Error list window.
The error information is;

Severity   Code    Description Project File    Line    Suppression State
Error       NuGet Package restore failed for project MathsLib-test: Could not find a part of the path 'Y:\test\AMF-2022\Assignment2\submissions\s1\s1\MathsLib_Start1\packages\Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.220.127.116.11\build/native/Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.targets'.. Please see Error List window for detailed warnings and errors.
Answer: It can be caused by having your project located within a subfolder that is too deeply nested. Possibly there's some limit for the folder path length?
I saw the same error when I downloaded a zip with some demo projects and when I unzipped it created a folder with many subfolders. The project I was interested in was down pretty deep in the subfolders and when I tried to restore its NuGet packages I got the same errors.
I moved the project folder up nearer to c:\ and then the restore errors went away.
Comment: I did the same with the clean_it repo from David Sackstein's CPP Con talk, and it stopped that same error from happening for me


Enviar tarefa pelo server para clients nodejs

Question: Estou utilizando socket.io  e fazendo um server e client em nodejs. A comunicação entre eles está funcionando. Servidor recebe notificação quando cliente conecta e desconecta. Estou precisando agora enviar tarefas do server para o client e armazenar em um array por clientes essas mensagens
server.js
io.on( 'connection', ( socket ) =>{
console.log( 'Nova conexão, exibindo o ID desse cliente:', socket.id )

if( socket.id )
{
    socket.on('task', ( task ) => {

        let arrTask = [];

        cron.schedule('*/10 * * * * *', () => {
            console.log( task )
        })

        socket.on('disconnect', () => {
            console.log( 'Cliente desconectado' )
        })

    })

}
})

client.js
socket.on( 'connect', () =>{

  console.log( "Cliente conectou" );
  socket.emit( 'task', 'Cliente '  + socket.id + ', recebi sua tarefa' );

})

socket.on('msg', (msg) => {

  console.log( msg );

});

Se alguém puder me auxiliar ficaria grato. Ah, me desculpem mas não consegui colar o codigo certo.
Comment: @Sorack obrigado por ter editado, não estava conseguindo. Saberia me auxiliar nessa questão do código?
Answer: Acho que não entendi exatamente ... Mas estou confuso um pouco com o seu código.
Vamos partir do principio básico:
socket.emit => envia uma mensagem
socket.on => fica escutando o canal e assim que receber faz algo.
no lado do cliente:
socket.on( 'connect', () =>{
  let tarefa = {dados: "fazer algo", tempo: 50, teste: false};
  console.log( "Conectou com o servidor de socket" );
  socket.emit( 'task', tarefa); // emite a tarefa assim que conecta no servidor.
});

socket.on('mensagem-retorno', (msg) => {
  console.log( msg );
});

Já no server.js
io.on( 'connection', ( socket ) =>{
    console.log( 'Nova conexão, exibindo o ID desse cliente:', socket.id )

    if( socket.id )
    {
        socket.on('task', ( tarefa) => {
            // essa parte de armazenar eu não sei como você irá fazer.
            console.log( tarefa ); // << sua tarefa está aqui.
            let arrTask = [];

            cron.schedule('*/10 * * * * *', () => {
                console.log( tarefa )
            })

            socket.on('disconnect', () => {
                socket.emit('mensagem-retorno', 'Sua tarefa foi recebida e processada'); // o cliente vai estar observando o "canal" mensagem-retorno
                console.log( 'Cliente desconectado' );
            });

        });

    }
});

Conseguiu entender? se você quiser mandar a mensagem para todos os clientes conectados ao servidor, você deve usar broadcast.
Comment: obrigado @Thomaz Diogo Cimin
Comment: Conseguiu rodar sem problemas? Se tiver mais dúvida comenta ai.


Branch and Bound algorithm on an integer problem

Question: When performing the branch and bound algorithm on an integer problem, multiple integer feasible solutions may be found.
Generally, is the second best integer feasible solution found during the branch and bound process
necessarily the second best integer solution of the Integer Problem??
Answer: No, a second-best solution might be pruned away and never encountered.  A simple modification to find the best two solutions is to keep a pair of solutions (instead of just one) as the incumbent, updating the incumbent whenever a solution is found that is better than the worse one.  This idea extends to the $k$ best solutions.
Comment: The branch and bound algorithm prunes any node that cannot improve the incumbent solution. In particular, after an optimal solution has been found, any alternate optimal or worse solutions will be pruned away.
Comment: why would the second-best solution not be encountered?


Jordan canonical form with more than 1 eigenvector

Question: I need to solve: $$ v'=\left(\begin{array}{ccc}
5 & -1 & -2\\
-4 & 5 & 4\\
4 & -2 & -1
\end{array}\right)v $$
After finding the characteristic polynomial and finding the eigenvectors I found
$$ p(A)=(x-3)^3,ker(A-3I)=span\left\{ \left(\begin{array}{c}
1\\
2\\
0
\end{array}\right),\left(\begin{array}{c}
1\\
0\\
1
\end{array}\right)\right\} $$
Now I want to find the Jordan chains and I'm struggling a bit.
$$ \left.\begin{array}{ccc}
2 & -1 & -2\\
-4 & 2 & 4\\
4 & -2 & -4
\end{array}\right|\begin{array}{c}
\alpha+\beta\\
2\alpha\\
\beta
\end{array}\xrightarrow[2R_{1}-R_{3}\to R_{3}]{\substack{2R_{1}+R_{2}\to R_{2}}
}\left.\begin{array}{ccc}
2 & -1 & -2\\
0 & 0 & 0\\
0 & 0 & 0
\end{array}\right|\begin{array}{c}
\alpha+\beta\\
4\alpha+2\beta\\
2\alpha+\beta
\end{array}\Rightarrow\beta=-2\alpha $$
After that I took $ \alpha =1,\beta =-2 $ and tried continuing the chain with
$$\left.\begin{array}{ccc}
2 & -1 & -2\\
-4 & 2 & 4\\
4 & -2 & -4
\end{array}\right|\begin{array}{c}
-1\\
2\\
-2
\end{array}\Rightarrow2x-y-2z=-1\Rightarrow\left(\begin{array}{c}
x\\
y\\
z
\end{array}\right)=\left(\begin{array}{c}
0\\
1\\
0
\end{array}\right) $$
After doing this, I cant keep my chain as the 3rd vector I need has no solution:
$$ \left.\begin{array}{ccc}
2 & -1 & -2\\
-4 & 2 & 4\\
4 & -2 & -4
\end{array}\right|\begin{array}{c}
0\\
1\\
0
\end{array}\Rightarrow \text{no solution} $$
How do I fix it and reach the Jordan form? I know how to make it work when I have only 1 eigenvector but I can't find examples for this case.
Answer: you don't need a third vector, you have:
$$ker(A-3I)=span\left\{ \left(\begin{array}{c}
1\\
2\\
0
\end{array}\right),\left(\begin{array}{c}
1\\
0\\
1
\end{array}\right)\right\}=span\left\{ \left(\begin{array}{c}
-1\\
2\\
-2
\end{array}\right),\left(\begin{array}{c}
1\\
0\\
1
\end{array}\right)\right\}$$
so we can have
$$A=\begin{pmatrix}
1&-1&0\\
0&2&1\\
1&-2&0
\end{pmatrix}
\begin{pmatrix}
3&0&0\\
0&3&1\\
0&0&3
\end{pmatrix}
\begin{pmatrix}
1&-1&0\\
0&2&1\\
1&-2&0
\end{pmatrix}^{-1}$$
so, for your differential equation
$$e^{tA}=\begin{pmatrix}
1&-1&0\\
0&2&1\\
1&-2&0
\end{pmatrix}
e^{t\begin{pmatrix}
3&0&0\\
0&3&1\\
0&0&3
\end{pmatrix}}
\begin{pmatrix}
1&-1&0\\
0&2&1\\
1&-2&0
\end{pmatrix}^{-1} =\begin{pmatrix}
1&-1&0\\
0&2&1\\
1&-2&0
\end{pmatrix}
{\begin{pmatrix}
e^{3t}&0&0\\
0&e^{3t}&e^{3t}t\\
0&0&e^{3t}
\end{pmatrix}}
\begin{pmatrix}
1&-1&0\\
0&2&1\\
1&-2&0
\end{pmatrix}^{-1} = \begin{pmatrix}
e^{3t}(2t+1)&-e^{3t}t&-2e^{3t}t\\
-4e^{3t}t&e^{3t}(2t+1)&4e^{3t}t\\
4e^{3t}t&-2e^{3t}t&e^{3t}(1-4t)
\end{pmatrix}$$
Comment: Yes you could, it's arbitrary, any linearly independent eigenvector would do, they just need to span the eigenspace.
Comment: Mind explaining how you got the $ \left(\begin{array}{c}
1\\
0\\
1
\end{array}\right) $ vector?
You could just as likely take the other vector $ \left(\begin{array}{c}
1\\
2\\
0
\end{array}\right) $ ?


What's the difference between an axiomatization and a characterization of a structure?

Question: Regarding structures such as the natural numbers, complex numbers, groups, etcetera.
Would it make sense to say that a collection of properties is a characterization of sets? I know that there are axiomatizations (ZFC, NBG, New foundations, etcetera) but I have never heard them referred to as characterizations, is that convention or due to a fundamental difference?.
It's much better for me if you can also mention a reference that discusses the topic of axiomatization vs characterization.
Regards and thanks.
Answer: I think of a characterization generally as describing a structure uniquely up to isomorphism. Thus for example the system of real numbers is characterized as the (unique up to isomorphism) complete ordered field. Universal properties also serve to characterize a structure. Or, a characterization (perhaps more often called a classification) may specify a particular class of structures; for example one may classify finite simple groups in terms of well-known families.
An axiomatization is just part of a theory: the signature of a theory describes the data for a certain class of structures one may be interested in, and axioms describe properties we would like the structures to satisfy because we consider them particularly relevant to a given subject. Thus the signature for the theory of monoids consists of a constant (for the identity element) and a binary function symbol; the axioms are associativity and unit axioms, which we feel are particularly relevant for capturing what we expect of endomorphisms (e.g., functions from a set to itself). The same would apply to more complicated theories such as ZFC. There are many non-isomorphic models which satisfy these axioms, so we don't have anything like a characterization in the sense of the first paragraph.
I can't think of any references which discuss this distinction, but it's the one that I'm familiar with.
Answer: A characterization of a structure is to give some properties of the structure, but the structure must then first be defined.
The axioms define a structure and of course give it it's form, or if you want: it's character.
So axiomatization is about forming a structure while characterization is about describing an already formed structure.


Layout in AVD not the same as ADT?

Question: I don't see it but the layout on AVD isn't the same as what i expected based on ADT. I have one image button 1/3 and one regular button which should be 2/3 of the width.
I created a realtivelayout and for the buttons a linearlayout, why is the layout in ADT en AVD not the same and how can i fix this?

and this is the AVD

<TextView
    android:id="@+id/textHeaderView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/imageQuoteView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="18dp"
    android:text="@string/textHeaderQuote"
    android:textColor="#FFFFFF"
    android:textSize="24sp" />

<TextView
    android:id="@+id/viewQuote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textHeaderView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="18dp"
    android:text="@string/textViewQuote"
    android:textColor="#FFFFFF"
    android:textSize="20sp" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    android:paddingLeft="0dp"
    >

<ImageButton
    android:id="@+id/btnShare"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#CCCCCC"
    android:contentDescription="@string/btnsharetext"
    android:onClick="shareQuote"
    android:src="@android:drawable/ic_menu_share" />

<Button
    android:id="@+id/btnSendQuote"
    android:layout_weight="2"
    android:layout_height="80dp"
    android:onClick="sendQuotePage"
    android:text="@string/btn_text_sendQuote"
    android:background="#FEFEFE" />

</LinearLayout>

Comment: are both screens the same size?
Comment: @robin sorry what do you mean? AVD is just the virtual screen of the ADT screen, right?
Answer: An AVD(Android virtual device) has ofcourse its screen size and resulution. In the ADT(Android development tool) you can select a screen for your layout, just above the screen layout. Default is Nexus one. Try to set an other screen and see what happens.
Comment: i have even tried "preview all screens" and the layout in ADT is as expected. On AVD and Samsung s3 the buttons aren't covering the width of the screen.
Comment: In your image i can see you have not set a width. Use fill_parent to cover the width of the screen
Answer: Set a margin for you linear layout. For example:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    android:paddingLeft="0dp"

    android:layout_margin="5dp">

As to why the ADT display simulation differs from the AVD; the ADT dialog you see is a quick representation of what it can look like --not what it will absolutely look like.  The AVD is an emulator of a physical device meaning that it will give you the most accurate view.
EDIT: Actually answering your question
As for you button widths, you need to set their relative widths using weight for the parent layout, as well as specify widths of 0.
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    android:paddingLeft="0dp"

    android:layout_weight="3">

<ImageButton
    android:id="@+id/btnShare"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#CCCCCC"
    android:contentDescription="@string/btnsharetext"
    android:onClick="shareQuote"
    android:src="@android:drawable/ic_menu_share"

    android:layout_width="0dp"/>

<Button
    android:id="@+id/btnSendQuote"
    android:layout_weight="2"
    android:layout_height="80dp"
    android:onClick="sendQuotePage"
    android:text="@string/btn_text_sendQuote"
    android:background="#FEFEFE"

    android:layout_width="0dp"/>
</LinearLayout>

Personally I don't use the Auto-Layout tools (ADT) that they offer since they don't give you much freedom.

Layout in AVD not the same as ADT?


GreaseMonkey, change some js functions

Question: I use Greasemonkey for some changes in pages.
There's a web page that has SomeFunction() placed in a javascript file.
I ignored the javascript file with some add-ons.
Now SomeFunction() should be overwritten.
But when I define SomeFunction() in GM script, I get "SomeFunction() is not defined" which has not been resolved by run-at document-start in GM script neither by adding SomeFunction() in a file and writing that on the page with document.getElementsByTagName('head')[0].appendChild(js);.
How can I define a custom Somefunction()?
Thank you
Answer: Consider reading exportFunction and all the others stuff about unsafeWindow.
Basically:
exportFunction(SomeFunction, unsafeWindow, {defineAs: "SomeFunction"});

GreaseMonkey, change some js functions


I need an adaptor to read my old laptop harddisk

Question: I want to find an adaptor that will allow me to read my old Laptop harddrive. Can someone help me find the right adaptor for this?
Comment: I would suggest starting with google. It's not a *high* bar to cross.
Comment: yes, i agree with vidarlo, google is your friend
Answer: What you have there is an M.2 NVMe drive. You need to plug in those keywords, plus perhaps "USB adapter" to find an appropriate product.
Answer: Something like this will do the trick:
https://www.orico.cc/us/product/detail/7207.html
Comment: Product Suggestions are offtopic
Comment: That would be why I closed it as offtopic, yes.


Why can generator expressions be iterated over only once?

Question: This program:
def pp(seq):
    print(''.join(str(x) for x in seq))
    print(''.join(str(x) for x in seq))
    print('---')

pp([0,1,2,3])
pp(range(4))  # range in Python3, xrange in Python2
pp(x for x in [0,1,2,3])

prints this:
0123
0123
---
0123
0123
---
0123

---

It is a result of the difference between container.__iter__ and iterator.__iter__. Both are documented here: https://docs.python.org/3/library/stdtypes.html#typeiter. If the __iter__ returns a new iterator each time, we see two repeating lines. And if it returns the same iterator each time, we see just one line, beacuse the iterator is exhausted after that.
My question is why it was decided to implement generator expressions not similar to other objects that seem to be equivalent or at least very similar?
Here is another example that generator expressions are different than other similar types which may lead to unexpected outcome.
def pp(seq):
    # accept only non-empty sequences
    if seq:
        print("data ok")
    else:
        print("required data missing")

pp([])
pp(range(0))
pp(x for x in [])

output:
required data missing
required data missing
data ok

Answer: A generator runs arbitrary code, and returns a lazy sequence with the items yielded by that code.

That code could be providing an infinite sequence.
That code could be reading contents off a network connection.
That code could be modifying external variables every time it iterates.

Thus, you can't cache the results safely in the general case: If it's an infinite sequence, you'd run out of memory.
You also can't simply rerun the code when it's read from again: If it's reading off a network connection, then the connection may no longer be there again in the future (or may be in a different state). Similarly, if the code is modifying variables outside the genexp's scope, then that state would be changed in hard-to-predict ways based on the readers' behavior -- an undesirable propery for a language that values predictability and readability.

Some other languages (notably Clojure) do implement generators (there, generalized as "lazy sequences") that cache results if and only if a reference to the beginning of the sequence is retained. This gives the programmer control, but at a cost of complexity: You need to know exactly what is and is not referenced for the garbage collector.
The decision not to do this for Python is entirely reasonable and in keeping with the language's design goals.
Comment: Caching the elements is clearly out of question. I was thinking only about re-running it. I do not know nothing about Clojure, but it ie quite obvious that reusable generators could be written in a way that each run produces a different sequence. You said that should be avoided. This is the core of your answer as I understand it. Did I get it right?
Comment: The risk is not just a different sequence -- if you're reading from a network (which is actually a quite common use for generators, if trying to process data while it's still coming in), then once you've finished that network stream, then there's nothing left to read more items from; thus, in that use case, what you have is *inherently* read-once.
Comment: But, yes, having a value that behaves differently each time it's read is also a Bad Thing in a Pythonic explicit-is-better-than-implicit sense.
Comment: Sounds reasonable. Thank you for answering my question. If you don't mind an additional question: looking at the example at the bottom of my question, there are two different ways to avoid the problem. Would you agree with "_never pass a generator expression to a function_" or with "_do not try to iterate over an unknown sequence more than once_"? Thanks.
Comment: Hmm. The former makes it the caller's responsibility to cast to `list` (or similar) when needed; the latter makes it the callee's. Absent cases where the function is written and documented to support a single-use iterator (which is appropriate in many cases, as when writing code for use in network-streaming scenarios), I'd call putting that responsibility on the caller more reasonable, as it's the caller that knows when a genexp is in use.
Comment: Thank you for sharing your opinion. For me it's a new "gotcha" and I will be more carefull with generator expressions from now on.
Answer:
My question is why it was decided to implement generator expressions not similar to other objects that seem to be equivalent or at least very similar?

Because that's exactly what a generator is. If you make it similar to other iterables then you have to preserve all of the items in memory and then what you have is no longer a generator.
The main benefit of using generators is that they don't consume as much memory. They simply generate the items on demand. This makes them one-shot iterables, because if you wanted to be able to iterate over them multiple times then you would have to preserve all of the items in memory.


What can be "two horizontal intervals of equal distance and discordant" on diatonic scale?

Question: I keep reading this set of rules for counterpoint.
The rule number G5 states:

If there are two horizontal intervals of equal distance and
  discordant, the next interval must differ.

I try to figure out in what situation the rule can be triggered. First, among the allowed intervals (m2, M2, m3, M3, P4, P5 and m6) only m2 and M2 are dissonant (discordant).
In a diatonic scale to m2 in a row are impossible. So, the only what remains is M2. Therefore, I guess, that the rule can be formulated like this:

If you go F - G - A, you are not allowed to go further to B.
  Similarly, if you go B - A - G, you are not allowed to go to F.

Is my interpretation correct?
ADDED
There is a clarification of the rule, which made me even more confused:

Rule G5 is another case of IR. Many observations against redundancy,
  similar sequences and other forms of repetition can be found in all
  five textbooks we analysed. However, the supporting examples were
  extremely variable and context-dependant, and the prescriptions
  imprecise and subject to personal taste. Therefore, our rule vetoes
  only the most extreme form of repetition, the trill (see Figure 3)

Could it be that "discordant intervals", does not mean "dissonant" and, instead, it mean that intervals are in opposite direction?
Comment: It might help to indicate where these quotes are from. The context of the work might provide clues as to the intended meaning.
Comment: @MichaelCurtis, here is the source: https://www.researchgate.net/profile/Marcella_Mandanici2/publication/298981984_The_Counterpoint_Game_Rules_Constraints_and_Computational_Spaces/links/59639fd9458515a3576141fd/The-Counterpoint-Game-Rules-Constraints-and-Computational-Spaces.pdf?origin=publication_detail . And it is not a paper about "computer program".
Comment: Heck, trills aren't even banned in counterpoint to my knowledge--Bach's Little Fugue has trills in a countersubject.
Comment: @ Roman: you can't go on asking the next day without referring to the sources - especially if it's not the one you were quoting in your earlier question but one that you got in an answer. I had also to look up again as I didn't remember exactly to whom this point was concerning:  https://music.stackexchange.com/questions/84339/should-we-avoid-two-consecutive-leaps-forming-triads-in-cantus-firmus
Comment: -1 down voted. You have been asked twice to provide a source for these quotes. From the last question, it seems you got them from a paper about computer program.
Comment: @Roman, a paper published in the Proceedings of the International _Computer_ Music Association is certainly about computer programming. The abstract talks about an _algorithm_ to judge counterpoint validity.
Answer: The modes were not only written in C.
Your formulation of this rule would be correct if it were in relative doremi as there have been altered tones like F# or Bb etc. (not all - originally!)
I don't mind if you didn't look up in google as I learn each time a lot if I don't know what means concordant and discordant - or anything else ...
"Every interval is either concordant or discordant. The concordant comprise all perfect intervals and all major and minor 3rds and 6ths; the discordant comprise all augmented and diminished intervals and all 2nds and 7ths. It therefore follows that all concordant intervals when inverted remain concordant and all discordant intervals remain discordant."
https://www.encyclopedia.com/literature-and-arts/performing-arts/music-theory-forms-and-instruments/interval
Answer:
...G5. If there are two horizontal intervals of equal distance and discordant, the next interval must differ. IR (Implicit Rule)

I think it's important to show the illustrating example from the article...

The see a horizontal interval C4 to E4 and it repeats so there are two of them and they are equal distances, both are major thirds. But, these intervals are not discordant!
If the word 'discordant' were removed from the rule, the the rule and example would be perfectly clear. But, the authors add a lot of caveats to the rule. I think their intention is clear from this...

...Many observations against redundancy, similar sequences and other forms of repetition...

I pointed out this principle to you in my answer to your previous question. Notice how the authors call this an implicit rule. They are saying it is so fundamental that it is taken for granted by the authors of many counterpoint treatises. You really want to understand how important that concept of non-repetitive variety is to counterpoint aesthetics, especially at the note to note or per beat level of movement.
While the rule wording is kind of unclear, and the caveats do not really provide much clarity, they thankfully conclude with one simple point for their algorithm...

...Therefore, our rule vetoes only the most extreme form of repetition, the trill (see Figure 3.)

I don't understand why the rule G5 is worded as it is when the actual rule applied seems so clear, simple, and quite different than G5.
If you really want to understand the author's meaning, I think you need to contact them. You may be able to find their email addresses with some online searching. I have contacted authors in this way a few times and I have always received a reply.


Infinite hotel +1 guest

Question: Can anyone explain how is it possible to fit another guest in an infinite hotel that is already full?
Here's how the explanation (supposedly) goes:
A guest arrives at an infinite hotel, where every one of the infinite number of rooms is occupied by a guest. The manager tells the guest to go to the first room and ask the person there to move to the next room, and to ask the occupant in the next room to do the same. Thus, they say, the new guest will get accommodation, and since the hotel is infinite, the chain will go on forever.
However, let's look at what is happening step by step:
the hotel is full, there's one potential guest (a) that is not in any room
guest knocks on a door, asks the tenant (b) to go to the next room, now there are two guests (a and b) not in any room, and one room is empty
guest a goes into the empty room 4 = 1) the hotel is full, there is one potential guest (b) not in any room.
Thus there will always be at least one guest not in a room, so we cannot fit another guest into an infinite hotel that is already full, can we?
My question is where is my logic flawed, since it seems that it is commonly understood that you can?
Comment: The idea is that the person currently in room $1$ goes to room $2$. The person currently in room $2$ goes to room $3$, the person currently in room $n$ goes to room $n+1$.  Thus room $1$ is empty and available for the new guest, and everybody else has a private room.
Answer: The moving of the guests is not sequential. Or, to keep the with the hotel story, the manager does not go to tenant b to move to the next room. Instead, the hotel manager uses the hotel's computer systems to call all phones in all the rooms at the same time and instructs the guests to all exit their room at the same time, then enter the next room, again all at the same time.
Once all the guests (the infinitely many of them) have done what they were instructed, the manager takes the new guest to room #1 which is now empty.

Now, of course, you could say "well but the electrical signal for the instructions goes first to room 1, then room 2, and cannot reach all rooms"... but that would be missing a point. Of course it is not physically possible to make the move because it is physically impossible for the hotel itself to exist. That's not the point of the analogy, the point is to show that infinities are strange and sometimes counterintuitive.
The real mathematical message behind the story is that it is relatively easy to translate the story into a rigorous proof that there exists a bijection between a countable set and a countable set to which we add one more element. For example, one can quickly see that there exists a bijection $f$ between $\{1,2,3,\dots\}$ and $\{-1\}\cup\mathbb N$ by defining
$$\begin{align}
f(n) = \begin{cases}-1&n=1\\
n+1& \text{otherwise}\end{cases}
\end{align}$$
This is counterintuitive, because from finite sets, we are used to the facts that

if you add one element to the set, then the result is a bigger set
If you take a proper subset of the set, then that subset is smaller than the set containing it

but this is simply not the case with infinite sets, where two sets that may seem of different sizes are in fact the same size.
Comment: The idea that all of the guests could step out at the same time and go to the next room never occurred to me. That way it does sound reasonable that the hotel could fit one more guest (or any number of guests for that matter)

Infinite hotel +1 guest


What do I look over when looking at sheet music?

Question: Imagine I was just handed a piece of sheet music, and I had however long I'd want to look over it before I actually started playing. What exactly would I look over so I'd sight read better?
Comment: Since we don't know what instrument you are playing, what level you have reached,  and what the piece is, the question is unanswerable, because "we" are not "you". Do you really think the answer would be the same if you were asked to sight-read a lead sheet of "Happy birthday to you", or to play a keyboard version of a movie theme (for a movie that you have never seen) *by reading the full orchestral score* (not somebody else's keyboard arrangement of the music)?
Comment: You can [edit] your question to include the needed information
Answer: There are two interesting levels:

What is this sort of music? (Try to hear the melody, the rhythm, where are the notes one should emphasize, ...)
Where are problematic notation parts? (Unexpected key changes, modulations, accidentals, clef changes, what are the notes with many ledger lines)

When looking at the sheet, try to imagine how to finger / pluck / whatever appropriate for your instrument. Anything you prepare now, will work faster later.


Singular points of a set of matrices

Question: Let $k$ be an algebraically closed field. We identify the space $M_{2}(k)$ of $2 \times 2$ with $\mathbb{A}^{4}(k)$  with coordinates a,b,c,d. Let $X$ be the set of all matrices $A$  in $M_{2}(k)$ such that $A^{2}=0$.
Show that $X$ is isomorphic to the affine cone of the projective variety $W=V(x^{2}-yz) \subseteq \mathbb{P}^{2}$ and find the singular points of $X$. Finally compute the Zariski tangent space at such point.
My work:
Doing the computations shows that $X=V(ad-bc,a+d)$. Now note that the affine cone of $W$ is $V(x^{2}-yz) \subseteq \mathbb{A}^{3}$.
So let $f: X \rightarrow V(x^{2}-yz) \subseteq \mathbb{A}^{3}$ be given by $(x,y,z,w) \mapsto (x,-y,z)$ and let $g: V(x^{2}-yz) \subseteq \mathbb{A}^{3} \rightarrow X$ be given by $g(x,y,z)=(x,-y,z,-x)$.
(Unless I did something wrong) $g$ is the inverse of $f$ so $f$ is an isomorphism.
Now observe that $V(x^{2}-yz) \subseteq \mathbb{A}^{3}$ has only one singular point, namely the origin $(0,0,0)$ thus via the above isomorphism we see that $(0,0,0,0)$ is the only singular point of $X$.
The part I'm not sure is how to compute the Zariski tangent space we first need to find a set of generators for $I(X)$ no? or is there an easier way?
EDIT: Using software one can check that $I(X)=(xyz-x^{2}w+yzw-xw^{2})$ so the tangent space is $\mathbb{A}^{4}$ because all partials of $xyz-x^{2}w+yzw-xw^{2}$ vanish at $(0,0,0,0)$. However is it possible to solve this question without calculating $I(X)$?
Answer: a) The proof that $X$ is isomorphic to $V(x^2-yz)\subset \mathbb A^3$ is perfect: congratulations!
Let me call $V$ that variety $V(x^2-yz)\subset \mathbb A^3$
b) You haven't given a proof, but it is true that $V$ has $O=(0,0,0)$ as its only singularity.
A possible proof proof  is to use the Jacobian criterion:
Letting $F(x,y,z)=x^2-yz$ we have $Jac(F)=(2x,-z,-y)$ and the singularities of the hypersurface $V$ are given by the system $x^2-yz=2x=-z=-y=0$ so that the only singularity of $V$ is indeed $O$.
c) The Zariski tangent space $T_O(V)$ is the subspace of $k^3$ determined by the equation $Jac_O(F)(t)=0$, where $Jac_O(F)$ is seen as a linear form on $k^3$ and $t=(t_1,t_2,t_3)$ as a vector in $k^3$.
Since $Jac_O(F)=0$ is the zero linear form here, it follows that $T_O(V)=k^3$.
Translated back in terms of the original matrices, this means that the Zariski tangent space of your variety $X$ of nilpotent matrices is the hyperplane $a+d=0$ of $M_2(k)$.
Comment: Thanks! I can see that the tangent space of $V(x^{2}-yz) \subseteq \mathbb{A}^{3}$ is the whole $\mathbb{A}^{3}$. How did you translate this to $X$ to conclude that the tangent space consists of the hyperplane $a+d=0$?
Comment: is it simply because if $g: X \cong V$ is an isomorphism of varieties then the tangent spaces $T_{(0,0,0,0)}(X) \cong T_{g((0,0,0)}(V)$ are isomorphic as vector spaces? Now since the tangent space of $V$ is $\mathbb{A}^{3}$ then the points are of the form $(x,y,z) \in k^{3}$. Therefore the points of the tangent space of $X$ at the origin are of the form $g(x,y,z)$ where $g$ is the above isomorphism, so points of the form $(x,-y,z,-x)$ where $(x,y,z) \in k^{3}$ and since the first and last coordinate add $0$ then we characterize this set as a+d=0.
Comment: Dear user10, yes your argument in the comment is completely correct.In other words you have an isomorphism $F:V(a+d)\to k^3: (a,b,c,d)\mapsto (a,-b,c)$ restricting to your $f:X\to V$, so that the Zariski tangent space $k^3$ corresponds under $F$ to $F^{-1}(k^3)=V(a+d)$.

Singular points of a set of matrices


How to parse SLD 1.0.0 or 1.1.0 with geotools?

Question: Is there a build-in way to parse an SLD file with geotools, which works for SLD 1.0.0 and SLD 1.1.0?
Answer: I have not found a build-in way, but one possible solution is to retrieve the SLD version from the XML file.
Depending on the version it can be parsed with the suitable Configuration class.
public  Style createStyleFromSld(String uri) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document xmlDocument = db.parse(uri);

  XPath xPath = XPathFactory.newInstance().newXPath();
  String version = xPath.compile("/StyledLayerDescriptor/@version").evaluate(xmlDocument);
  Configuration sldConf;
  if (version != null && version.startsWith("1.1")) {
    sldConf = new org.geotools.sld.v1_1.SLDConfiguration();
  } else {
    sldConf = new org.geotools.sld.SLDConfiguration();
  }
  StyledLayerDescriptor sld = (StyledLayerDescriptor) new DOMParser(sldConf, xmlDocument).parse();
  NamedLayer l = (NamedLayer) sld.getStyledLayers()[0];
  Style style = l.getStyles()[0];
  return style;
}

Comment: In an ideal world you could look at the mime type of the file and use that to distinguish them, but failing that either your approach or trying one then the other is the best plan


How to find $E[X|X>Y]$

Question: Suppose $X$ and $Y$ are independent standard normal variable. I want to find $E[X|X>Y]$.
I calculated that
$$ f_{X>Y}(x) = 2\Phi(x)\phi(x)$$
However I couldn't find the expected value using this conditional probability. How can I evaluate the integral?
Comment: I found the answer here:
http://math.stackexchange.com/questions/327245/let-x-y-sim-mathcaln0-1-let-z-maxx-y-find-ez
Comment: https://math.stackexchange.com/q/2011019/321264
Answer: Here is one way to look at the problem. Let $\alpha = P(X > Y)$ (By symmetry, it should be clear what $\alpha$ is.), then
$$
0 = E[X] = \underbrace{E[X|X > Y]}_{=:x} \alpha + \underbrace{E[X| X < Y]}_{=:y} (1-\alpha)
$$
By symmetry $y:= E[X| X < Y] = E[Y | Y < X]$. Now, by linearity of expectation,
$$
E[X-Y|X > Y] = x - y
$$
But $X-Y \sim N(0,2)$ and if we let $Z \sim N(0,1)$, then $E[X-Y|X > Y] = \sqrt{2} E[Z | Z > 0]$. You should be able to easily compute $E[Z|Z>0]$, from which you get $x-y$, and then $x$ by examining the above equalities.

How to find $E[X|X>Y]$


Schedule Delivery Time and Date

Question: Is there a module from Drupal Commerce to schedule Delivery date and time ?
Customer is required to specify the date and time. This then will be displayed in the admin side.
thanks appreciate your help
Answer: Check it out Commerce Field Group Panes module. Using this you can able to add field Delivery Date & Time field to check out process.

This enables an easy way to collect information in the checkout
  process. For example customer comments, feedback about where the
  customer founds the shop or any other fieldable information.
Comment: This combined with [Date](http://www.drupal.org/project/date) would definitely do the job.

Schedule Delivery Time and Date


Tangent line to quarter circle inscribed in square ABCD intersects point X. Where to start?

Question: Disclaimer: The answer must be an integer, as all competition problems were designed to yield integral answers.
Hello! Yesterday I underwent a math tournament. There was one problem that was rather difficult in my eyes, and that is the question I am bringing up today.
Let ABCD be a square with side length 24, and suppose M is the midpoint of line AB. Construct a circle centered at C through B and D, and let the tangent line through M to this circle (other than AB) intersect AD again at X. What is the length of AX?
Of course I have drawn ABCD and the circle centered at C as described above (using GeoGebra for my first time :) ). In the image please disregard the values on the X and Y axes (as they clearly do not match up with the length of 24, as seen in the problem).

How would I go about starting this problem? Do we try to find the length of MX and use the Pythagorean Theorem to find AX?
-Many thanks
Answer: Produce CE to cut the y-axis at K.
$\angle BCE =2 \times \tan^{-1} (\dfrac {1}{2}) = 53.xxx^0$. This means $\triangle BCK$ is an 8 times 3-4-5 triangle in disguise.
[Added: An alternate approach in getting the above result is:-
$\triangle KME \sim \triangle KCB \rightarrow \dfrac {KM}{KC} = \dfrac{ME}{CB} = \dfrac {EK}{BK}$
$∴\dfrac {y + 12}{t + 24} = \dfrac{12}{24} = \dfrac {t}{y + 24}$
$(1): \dfrac {y + 12}{t + 24} = \dfrac{1}{2}$
$(2): \dfrac {t}{y + 24} = \dfrac{1}{2}$
$∴ y = 8$]
By exterior angle of cyclic quadrilateral (BCEM), $\triangle AMX$ is an 4 times 3-4-5 triangle in disguise.
Therefore, AX = 4(4).
Comment: How does CE cut the Y axis? My mistake that I forgot to include the use of no calculator. Your solution relies on some calculator work, How would I approach this problem without a calculator?
Comment: @MarDev Let KA = y and KE = t. From the fact that $\triangle KME \sim \triangle KBC$, setup the corresponding ratios. Two simultaneous equations in y and t are obtained and hence y can be found.
Comment: @MarDev Correction:- $\triangle KME \sim \triangle KCB$
Comment: Still don't understand where point K is being formed, could you elaborate on that?
Comment: @MarDev I have modified my post with more details in the added.
Answer: Note that because $AB$ and $AD$ are also tangents to the circle with center $C$, we observe that $$MB = ME, \quad XE = XD.$$  Since we know $MA = MB = 12$, and $XA + XD = 24$, this immediately suggests we let $XA = z$, and by the Pythagorean theorem, $$z^2 + 12^2 = XA^2 + MA^2 = MX^2 = (ME + XE)^2 = (12 + 24-z)^2 = (36-z)^2.$$ Solving this equation for $z$ easily yields $$72z = 36^2 - 12^2 = (36+12)(36-12) = (48)(24),$$ hence $z = 16.$
Comment: How can we determine that MB = ME and XE = XD? I do not see how the observation supports that.
Comment: @MarDev The two tangent segments drawn from any given point outside of a circle are of equal length.  In other words, draw a circle.  Pick a point outside of the circle.  Draw the two external tangent lines to the circle that pass through the point.  The distances from the points of tangency on the circle to the given point are equal.
Comment: Yes, but the tangent segments are not originating from the same point in the diagram above. X D and A are all different points.
Comment: @MarDev $MB = ME$ because $\overline{MB}$ and $\overline{ME}$ are tangent from the same point $M$ to the points of tangency $B$ and $E$, respectively.  $XE = XD$ because $\overline{XE}$ and $\overline{XD}$ are tangent from the same point $X$ to the points of tangency $E$ and $D$.
Comment: Ah, now I see. Thank you for your help, marking this answer as accepted. Sorry that it didn't come so obvious to me :P


What is the largest three-digit integer that when cubed, the result ends in itself

Question: Let $N =\overline{abc}$ be a three-digit integer with distinct digits $a$, $b$, and $c$. What is the largest possible integer $N$ such that, when $N$ is cubed, the resulting integer ends with the same three digits as $N$?
Here is what I did:
I know that $N^3\equiv N \pmod{1000}.$ That means that $N^3-N\equiv 0 \pmod{1000}$ or $N(N-1)(N+1)\equiv0 \pmod{1000}.$ However, I don't know how to quickly find numbers that fit the properties without brute force. What do I do?
Comment: surely either $N\equiv1($mod$ 1000)$ or $N\equiv999($mod$ 1000)$?
Comment: There are other solutions to $N^3\equiv N\pmod {1000}$ besides $0, 1, $ and $999$ (e.g., 125), but $999$ works for this problem
Comment: However, $N$ has distinct digits, so 999 is not an answer.
Comment: Oops, I missed that the digits are distinct.  Maybe $875?$
Comment: I think you meant $N^\mathbb 3-N$
Comment: $\!\bmod n\!:\ n\!-\!1\,$ is the largest residue, and $\,n\!-\!1\equiv -1\,$ is a root of $\,x^3 = x.\,$ OP is case $\, n = 10^3$ $\ \ $
Answer: As stated in the question, we are looking for a solution of $N^3\equiv N\pmod{1000}.$
This means $1000$ divides $N^3-N$, so $125$ and $8$ divide $N^3-N=N(N-1)(N+1).$
$5$ can divide only one of $N, N-1$, and $N+1$, so this means $125$ divides $N$, $N-1$, or $N+1$.
That means, if $N$ is a positive integer less than $1000,$
$ N \in \{0,1,124,125,126,249,250,251,374,375,376,499,500,501,624,625,626,749,750,751,874,875,876,999\}.$
If $8$ divides $N(N-1)(N+1)$ then $N$ is odd or $8$ divides $N.$
That means $N\in\{0,1,125,249,251,375,376,499,501,624,625,749,751,875,999\}.$
Now that we have found solutions of $N^3\equiv N\pmod{1000}$, the problem is easily solved.
Answer: OK, I got it. So, based on my initial trial, I know that $N(N-1)(N+1)\equiv0 \pmod{1000}.$ Now there are two cases. Why? Because $N+1$ and $N-1$ must have the same parity, meaning that they must both be even or they must both be odd. Note that $1000=2^3\times5^3$. Using this, we can rule out the case where $N$ is even. Why? Because if $N$ is even, $N+1$ and $N-1$ must be odd. $N$ must be divisible by 2, 4, or 8, but the two odd numbers should be divisible by 5, an impossibility (Note that $500$ is both divisible by 125 and 4, but not, 8, and since the other two numbers are odd. This means that $N$ must be odd, and if $N$ should be maximized, it should be a factor of 125. Note that there is at least one multiple of 4 next to a number ending in 25 or 75, so this assumption works. This gives us the largest three digit multiple of 125, $\boxed{875}$.
Comment: Why can't we have $N=376$ (even and $125$ divides $N-1$) as a solution to $N(N-1)(N+1)\equiv0\pmod{1000}$?


Python Multiplication Program Game, Try again option

Question: I was trying to do a multiplication program where after one wrong answer, it will get the chance to try again one more time.
that is my code:
from random import randint

wrong_answers = 0

for turn in range(100):

    # Choose two random integers for the question to the player
    factor_1 = randint(2,12)
    factor_2 = randint(2,12)

    # Precompute the correct answer to be able to check the player's answer
    correct_answer = factor_1*factor_2

    # As the question and get the player's response
    question = 'What is ' + str(factor_1) + ' times ' + str(factor_2) + ' times ' + '?'
    answer_string = raw_input(question)

    #Convert the player's response to a number (raw_input yields a string)
    answer_int = int(answer_string)

    # See if the player's answer is correct or not, and proceed accordingly
    if (answer_int == correct_answer):
        print 'Correct!'
    else:
        print 'Wrong! Try Again!'
        raw_input(question)
        answer_int = int(answer_string)
    if raw_input() == correct_answer:
            print 'Correct'
    else:
            wrong_answers = wrong_answers + 1
    if wrong_answers == 2:
            print 'Game Over Thanks for playing!!!'
            exit()

The problem is when ask the question again, it does not compute the right answer.. it will ignore it and count as wrong answer. After the second wrong answer the program ends.
Is there any way to make the question again, count the right answer and if the person puts the wrong answer again count as error and the program continues?
Answer: It is not necessary re-ask for the answer. In fact, you shouldn't do it because at this point the program hasn't processed the answer yet. I would increment the wrong_answers variable in the first "else", so the code would look like this:
# See if the player's answer is correct or not, and proceed accordingly
if (answer_int == correct_answer):
    print 'Correct!'
else:
    if wrong_answers < 1:
        print 'Wrong! Try Again!'
    else:
        print 'Wrong!'
    wrong_answers = wrong_answers + 1

Note that the output will be "Wrong! Try Again!" when the answer doesn't produce a game over. If the game has finished it will be "Wrong! Game Over Thanks for playing!!!".
I leave here the demo: https://repl.it/ByyD/0.
I hope it helps you.
Answer: When you re-ask for the answer, you don't assign what the user entered to answer_string, so it uses the original value to compute answer_int.  But I guess that doesn't matter, since you use raw_input() instead of answer_int to see if the entry was correct.
Comment: I modified this part, i think now it works:

else:
        print 'Wrong! Try Again!'
        answer_string = raw_input()
        answer_int = int(answer_string)
    if answer_int == correct_answer:
            print 'Correct'i modified this part:


Comparing the rate of admitting to not quitting smoking between two groups?

Question: One group of patients was interviewed by doctors and 2% patients admitted to smoking. Another group of patients was interviewed by nurses and their admittance rate to smoking was 10%.
How would I show that the difference in rates is statistically significant?
Comment: Doesn't seem like you are comparing the rates of quitting as much as the admittance of not quitting.
Comment: To expand on @RioRaider 's question, if it is paired, is the order doctor->nurse (or nurse->doctor) followed for all patients, or does it vary?
Comment: Thankyou so much zbicyclist. Let me clarify. I am comparing the admittance rate reported to doctor and then the nurse. After comparison and analysis we will try to analyses the reasons of differences between these two groups. Second thing we want to compare is the doctor offers patient nicotine replacement therapy and the nurse offers patient that same thing. We found out that patients accept nicotine replacement therapy more from the nurses. Now we want to compare that rate as well and analyse it, thanks
Comment: Is your sample paired? Another words, does a patient first answer the smoke question for the doctor then the nurse?
Answer: Assuming the patients are random, independent samples for each group, consider a 2-proportion z-test where:
$$z=(\hat{p}_1-\hat{p}_2)/SE$$
$$SE = \sqrt{\hat{p}(1-\hat{p})(1/n_1)+(1/n_2)}$$
$$\hat{p}=(\hat{p}_1*n_1+\hat{p}_2*n_2)/(n_1+n_2)$$
Or is your sample paired?
A potential solution for paired samples is McNemar's test.
Comment: Thankyou, It is the same 1200 patients. Doctor-> Nurse order
Comment: The other thing that we are looking at is, once a patient admits to smoking she (we are only considering pregnant mothers) is referred to quit smoking clinic. In the quit smoking clinic- 1-How many admit to second hand smoking, 2-For first hand smoking how many agree to intervention that is nicotine replacement therapy, 3-For second hand smoking how many agree to intervention that is nicotine replacement therapy, 4 What is the quit rate for first hand smokers?, 5-What is the quit rate for second hand smokers?
Comment: 6-In the women who use nicotine replacement therapy do their babies do better than ones who refuse nicotine replacement therapy? (subgroup analysis), thanks
Comment: @sairahsharif It is generally poor practice to put additional questions in comments. I recommend you formally ask your additional [questions](http://stats.stackexchange.com/questions/ask).  You can reference this question in new questions.
Comment: @sairahsharif Since it's the same 1200 patients, RioRaider's suggestion about McNemar's test seems right. If you have trouble with figuring out that reference, let us know. If you can fill in the 2x2 (i.e. how many people said yes to both doctor and nurse, yes to doctor no to nurse, no to doctor yes to nurse, and no to both) I'd be happy to check your calculations.  BUT not that since the order is always doctor-> nurse you are testing multiple things at the same time.  Still worth analyzing.
Answer: @sairahsharif  You have 6 more questions. I think what you have is the following design:
A: said yes to doctor, yes to nurse
B: said yes to doctor, no to nurse
C: said no to doctor, yes to nurse
D: said no to doctor, no to nurse
and for question 1 "1-How many admit to second hand smoking" the answers can be either "admit" or "don't admit".
I'd approach this as a 4x2 chi-square.  Depending on the size of the cells, you may not have enough (too many expected values less than 5 can be a problem). But let's not deal with that problem until we know we have it.
I think for questions 2-5 the same thing works. Question 6 (do babies do better) you probably have a continuous measure rather than a yes/no measurement so a dummy variable regression would seem appropriate.  That may also make sense if people get multiple interventions and comply with some, but not all of them -- but I'd start with the question by question analysis first since it will be easier to understand.
Isn't there also a question 0: of those referred, how many actuallly show up?
I also have a question unrelated to statistical issues, just curiosity: what do you mean by "quitting secondary smoking"?
Comment: I meant second hand smoking, it means that people around you are smoking. I am trying to get the data set. It may take a week. Then I will contact you again.You have been very helpful, thanks


Encaixar DIV de forma automatica com CSS

Question: Olá
Eu estou tentando fazer s div's se encaixarem de forma automatica um ao lado da outra e caso não haja espaço do lado vais e encaixando de forma automatica da esquerda para a direita, mas não esta funcionando.
OBS: Oque determina o formato da DIV é a imagem que vai dentro dela.
Segue meu codigo e a imagem de como eu quero fazer.

Codigo HTML

   <title></title>

1

2

3

4

5

Obrigado
Comment: Me pareceu simples o questionamento, mas posso ter entendido errado.
Neste caso um exemplo seria uma div.container com width: 600px; Height: Auto; padding: 10px(se necessário) - E as div's.box com float: left; width: auto; height: auto; padding: 2px; margin: 5px;

Se for realmente isso posso lhe responder pois as box teriam espaçamentos automáticos e ficaria flutuantes da esquerda para direita, se exceder o espaço do container pula pra baixo e aumenta o height do container.
Answer: Como descrito no comentário, precisa adicionar atributos certos no container. Pode ser assim também:
article {
    overflow-x: auto;
    max-width: 100%;
}

Answer: Você vai precisar de uma 'forçinha' do JS. Pode utilizar a biblioteca http://masonry.desandro.com/, te recomendo esta biblioteca por ser a mais utilizada e vai te garantir um correto funcionamento na sua aplicação e em todos os browsers modernos. Para fazer isso apenas com html e css de forma automática fica inviável.

Segue o github do criador com a documentação
  https://github.com/desandro/masonry

. É simples, também posso te ajudar se precisar...
Abraços.
Comment: Boa dica Adriano, Obrigado. Eu gostei de um exemplo que tem no site do desenvolvedor, mas pedi para exibir o codigo fonte, mas esta cheio de javascript solto dentro dele, não entendi nada, você poderia me ajudaria com um exemplo simples, parecido com esse exemplo: http://www.erikjohanssonphoto.com/work


Binding mousewheel returns undefined

Question: I am testing the following code:
<code>$(window).bind('mousewheel', function(e) {
  alert(e.wheelDelta);
});
</code>
Every time I move the mousehweel, I get "undefined".  Can anyone help with this as I am trying to capture the mousewheel and move a div based on it.
Comment: Try `console.log(e)` inside your bind function. That will show you what properties it holds.
Answer: I think you'll have to do a little bit more work to get it working in all browsers - or try the jquery-mousewheel extension
If the extension still does not work properly, you might try this modified version I created a while ago:
<code>/* jquery.mousewheel.min.js
 * Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 *
 * Requires: 1.2.2+
 */
(function(c) {
    var a = [ "DOMMouseScroll", "mousewheel" ];
    c.event.special.mousewheel = {
        setup : function() {
            if (this.addEventListener) {
                for ( var d = a.length; d;) {
                    this.addEventListener(a[--d], b, false)
                }
            } else {
                this.onmousewheel = b
            }
        },
        teardown : function() {
            if (this.removeEventListener) {
                for ( var d = a.length; d;) {
                    this.removeEventListener(a[--d], b, false)
                }
            } else {
                this.onmousewheel = null
            }
        }
    };
    c.fn.extend({
        mousewheel : function(d) {
            return d ? this.bind("mousewheel", d) : this.trigger("mousewheel")
        },
        unmousewheel : function(d) {
            return this.unbind("mousewheel", d)
        }
    });
    function b(f) {
        var d = [].slice.call(arguments, 1), g = 0, e = true;
        if (f.wheelDelta) {
            g = f.wheelDelta / 120
        }
        if (f.detail) {
            g = -f.detail / 3
        }
        // I had to move the following two lines down, probably because of jQuery update
        f = c.event.fix(f || window.event);
        f.type = "mousewheel";
        f.pageX = f.originalEvent.pageX;
        f.pageY = f.originalEvent.pageY;
        d.unshift(f, g);
        return c.event.handle.apply(this, d)
    }
})(jQuery);
</code>
I just tested it in Firefox and Chrome, but I don't know whether it works in other browsers. Usage:
<code>$('element').mousewheel(function(e, delta) { alert(delta); });
</code>
Comment: `$(window).bind('mousewheel', function(event, delta, deltaY, deltaX) {
 alert(delta);
});`
I've added this extension and tested the following code(in Chrome).  I get the same data.  Firefox doesn't seem to detect it at all.
Comment: `e.originalEvent.wheelDelta` seems to return the data I want in Chrome.  IE and Firefox seem unresponsive(dont even trigger the event).
Comment: Oh, I remember there was some bug I had to fix when I used it. See the code above, it works for me.
Answer: I ended up using the following snippet:
<code>jQuery(function($) {
$(document)
        .bind('mousewheel', function(event, delta) {
        if(delta > 0) {
                    // Scrolling down
        } else {
                    // Scrolling up
        }
    });
});
</code>
This requires the jquery mousewheel extention and works in IE, Firefox and Chrome.
Answer: I had the same problem, and the solution was to change jquery version from 1.7.x to 1.9.x

Binding mousewheel returns undefined


Some pages return "502 Bad Gateway" error

Question: I just realized that certain links of my website lead to "502 Bad Gateway" error. For example, https://v2a.10studio.tech/10studio/auth/google, https://v2a.10studio.tech/auth/google, https://v2a.10studio.tech/10studio/auth/microsoft, https://v2a.10studio.tech/auth/microsoft. I'm pretty sure that those links worked several weeks ago, I don't know what happened.
The website https://v2a.10studio.tech/ is still working. https://v2a.10studio.tech/#/sign?next=/ contains the buttons clicking on which lead to the broken links.
Here is docker-compose.yml:
version: "3"
services:
  frontend:
    restart: unless-stopped
    image: staticfloat/nginx-certbot
    ports:
      - 80:80/tcp
      - 443:443/tcp
    environment:
      CERTBOT_EMAIL: email@example.com
    volumes:
      - ./conf.d:/etc/nginx/user.conf.d:ro
      - letsencrypt:/etc/letsencrypt
  10studio:
    image: bitnami/nginx:1.16
    restart: always
    volumes:
      - ./build:/app
      - ./default.conf:/opt/bitnami/nginx/conf/server_blocks/default.conf:ro
      - ./configs/config.prod.js:/app/lib/config.js
    depends_on:
    - frontend

volumes:
  letsencrypt:

networks:
  default:
    external:
      name: 10studio

And conf.d/v2.conf:
gzip on;
gzip_proxied any;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/rss+xml text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/jpeg image/png image/svg+xml image/x-icon;

upstream funfun {
   server www.funfun.io:443;
}

server {
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/v2a.10studio.tech/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/v2a.10studio.tech/privkey.pem;
    server_name v2a.10studio.tech;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_session_timeout 1d;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;
    add_header X-Frame-Options "";

    location ~ /socialLoginSuccess {
        rewrite ^ '/#/socialLoginSuccess' redirect;
     }

    location ~ /auth/(.*) {
        proxy_pass  https://funfun/10studio/auth/$1?$query_string;
        proxy_set_header Host v2a.10studio.tech;
     }

    location / {
        proxy_set_header    Host                $host;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_set_header    Accept-Encoding     "";
        proxy_set_header    Proxy               "";
        proxy_pass          http://10studio:8080/;

        # These three lines added as per https://github.com/socketio/socket.io/issues/1942 to remove socketio error
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "upgrade";
    }
}

Could anyone help?
PS: I changed some setting (especially SSL certificates) for funfun.io in CloudFlare several weeks ago, i don't if it is related. I don't know if this Proxy status (DNS only or Proxied) has an impact.

Edit 1: here are some docker logs:
2020-08-18T20:19:15.667934708Z 2020/08/18 20:19:15 [error] 42#42: *310 SSL_do_handshake() failed (SSL: error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:SSL alert number 40) while SSL handshaking to upstream, client: 184.108.40.206, server: v2a.10studio.tech, request: "GET /auth/github HTTP/1.1", upstream: "https://126.96.36.199:443/10studio/auth/github?", host: "v2a.10studio.tech"
2020-08-18T20:19:15.667995550Z 2020/08/18 20:19:15 [warn] 42#42: *310 upstream server temporarily disabled while SSL handshaking to upstream, client: 220.127.116.11, server: v2a.10studio.tech, request: "GET /auth/github HTTP/1.1", upstream: "https://188.8.131.52:443/10studio/auth/github?", host: "v2a.10studio.tech"
2020-08-18T20:19:15.738088121Z 2020/08/18 20:19:15 [error] 42#42: *310 SSL_do_handshake() failed (SSL: error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:SSL alert number 40) while SSL handshaking to upstream, client: 126.96.36.199, server: v2a.10studio.tech, request: "GET /auth/github HTTP/1.1", upstream: "https://220.127.116.11:443/10studio/auth/github?", host: "v2a.10studio.tech"
2020-08-18T20:19:15.738135701Z 2020/08/18 20:19:15 [warn] 42#42: *310 upstream server temporarily disabled while SSL handshaking to upstream, client: 184.108.40.206, server: v2a.10studio.tech, request: "GET /auth/github HTTP/1.1", upstream: "https://184.108.40.206:443/10studio/auth/github?", host: "v2a.10studio.tech"
2020-08-18T20:19:15.803843403Z 2020/08/18 20:19:15 [error] 42#42: *310 SSL_do_handshake() failed (SSL: error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:SSL alert number 40) while SSL handshaking to upstream, client: 18.104.22.168, server: v2a.10studio.tech, request: "GET /auth/github HTTP/1.1", upstream: "https://188.8.131.52:443/10studio/auth/github?", host: "v2a.10studio.tech"
2020-08-18T20:19:15.803890220Z 2020/08/18 20:19:15 [warn] 42#42: *310 upstream server temporarily disabled while SSL handshaking to upstream, client: 220.127.116.11, server: v2a.10studio.tech, request: "GET /auth/github HTTP/1.1", upstream: "https://220.127.116.11:443/10studio/auth/github?", host: "v2a.10studio.tech"
2020-08-18T20:19:15.803908241Z 126.96.36.199 - - [18/Aug/2020:20:19:15 +0000] "GET /auth/github HTTP/1.1" 502 559 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36" "-"
2020-08-18T20:19:21.284333260Z 2020/08/18 20:19:21 [error] 42#42: *310 no live upstreams while connecting to upstream, client: 22.214.171.124, server: v2a.10studio.tech, request: "GET /10studio/auth/github HTTP/1.1", upstream: "https://funfun/10studio/auth/github?", host: "v2a.10studio.tech"
2020-08-18T20:19:21.285121395Z 220.127.116.11 - - [18/Aug/2020:20:19:21 +0000] "GET /10studio/auth/github HTTP/1.1" 502 559 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36" "-"

Comment: Check the nginx error logs.
Comment: just added some logs in the OP...
Answer: The error SSL alert number 40 means you tried to connect to an HTTPS site which requires SNI but did not send a SNI hostname.
You are trying to proxy_pass requests that start with /auth/ to an upstream server named www.funfun.io. But this site is hosted on CloudFlare and thus requires SNI to connect to it with HTTPS. Unfortunately nginx's SNI support for outgoing upstream HTTPS connections is disabled by default (I can't imagine why). You need to explicitly enable SNI for outgoing connections to upstream with proxy_ssl_server_name on;. This can be set in the http context so that it applies to every attempted proxy_pass in your entire configuration, or can be placed only in specific locations where it is needed.
Comment: So I put `proxy_ssl_server_name on;`  inside the block of `location ~ /auth/(.*)` of my `conf.d/v2.conf`?
Comment: @SoftTimur I already answered that. Is something unclear about the explanation?
Comment: Now, clicking on those links return `403 Forbidden cloudflare`...
Comment: @SoftTimur Well, you did override the hostname and send it one that it probably doesn't recognize. There's no indication of why you did that or what the purpose is. But at least the current problem with SSL is fixed. You might consider asking a new question, but you should think carefully about why are you doing this particular proxy pass in this way to begin with.
Comment: I set `upstream funfun { server 22.214.171.124:443; }` and add `proxy_ssl_name "www.funfun.io"; proxy_ssl_server_name on;` inside the server block and before `location`s. It is working now. Thank you.


Question on independent equivalent set

Question: On Page 28, A Mathematical Introduction to Logic, Herbert B. Enderton(2ed),

Say that a set $\Sigma_1$ of wffs(short for well-formed formulas) is equivalent to a set $\Sigma_2$ of wffs iff for any $\alpha$ wff, we have $\Sigma_1 \vDash \alpha$, iff $\Sigma_2 \vDash \alpha$. A set  is independent iff no
  member of $\Sigma$  is tautologically implied by the remaining members
  in $\Sigma$. Show that the following hold.
(b) An infinite set need not have an independent equivalent subset.
  (c) Let  $\Sigma = \{\sigma_0, \sigma_1, . . .\}$; show that there is an independent equivalent set $\Sigma'$. (By part (b), we cannot hope to have $\Sigma' \subseteq \Sigma $, in general.)

I don't know why an infinite set need not have an independent equivalent subset? Here's my attempt to find one with the help of axiom of choice.
$\Sigma$ is a set, so is its power set $P(\Sigma)$. Thus, $K =\{x \in P(\Sigma): \exists y,y \in x, y \text{ is tautologically implied by } x-\{y\}\}$ and $K'=\{x' \subseteq x \in K: \forall y,y \in x', y \text{ is tautologically implied by } x-\{y\}\}$are also sets. Let $g : K \to K'$ such that $g(x) \subseteq x$ By axiom of choice, there exists a choice function $h$, such that for any $x \in K'$, $h(x)\in x$. So we have $f = h \circ g$, such that $h(g(x)) \in x' \in K'$ and $x \subseteq x'$
Let $\sigma'_0 = f(\Sigma)$. Given all $\sigma'_j (j < k)$, $\sigma'_{k}=f(\Sigma - \{\sigma'_j: j < k\})$, provided that $g(\Sigma - \{\sigma'_j: j < q\}) \in K'$ for all $q \le k$.
Such process will stop at or before some ordinal $\lambda$, because $K'$ is a set.So we have $\Sigma - \{\sigma'_j: j \le \lambda \}$ or $\Sigma -\{\sigma'_j: j < \lambda \}$ as an independent equivalent subset of $\Sigma$.
EDIT:
Finally I realized that there is no guarantee that $\Sigma - \{\sigma'_j: j \le \lambda \}$ or $\Sigma -\{\sigma'_j: j < \lambda \}$ is non-empty.
Comment: I'm not sure I follow the definition of $K'$. What is $x$?
Answer: Consider the following case: $\Sigma$ is an infinite independent set, $\{\sigma_n\mid n\in\omega\}$. Let $\varphi_n=\bigwedge_{i\leq k}\sigma_i$, then $\Phi=\{\varphi_n\mid n\in\omega\}$ is an infinite set, and it is not hard to see that $\Phi$ and $\Sigma$ are equivalent.
But what happens? If $\varphi\in\Phi$ is any wff, then $\varphi=\varphi_n$ for some $n\in\omega$ and clearly $\varphi_{n+1}=\varphi_n\land\sigma_{n+1}$. Therefore $\varphi_n$ is implied by $\varphi_k$ whenever $k>n$. So there is no infinite independent subset which is equivalent to $\Phi$. In fact the only independent subsets of $\Phi$ are singletons.
Answer: What if $\sigma_n\to\sigma_{n+1}$ for each $n\in\omega$? For instance, what if $\sigma_n$ is the wff $\mathbf{A}_0\land\ldots\land\mathbf{A}_n$? No subset containing more than one of the $\sigma_n$'s is independent.
Comment: Seriously? 12 seconds? :-)
Comment: @Asaf: It would have been a good minute the other way if I hadn't done an Amazon Look Inside to see what notation Enderton was using!
Comment: Well, it would have been a good minute in my favour if I hadn't had to get up and tend the cat for a moment! :-)
Comment: @Asaf: Ah, but I didn't mention the trip out to the living room to see whether my old Enderton was close enough to the current edition to be useful! :-) (It wasn't.)
Comment: And I didn't mention my trip to the bar which I am going to take in a few minutes, because it hadn't occurred yet and has nothing to do with this question! :-)
Comment: @Asaf: Okay: you win! I'm only going out to the kitchen for more coffee.

Question on independent equivalent set


Como pegar dados de um objeto e fazer operação matemática com outro objeto em C++?

Question: Tenho que calcular a distância entre dois pontos em C++ (Orientada a Objetos)
Eis o código que tenho:
Ponto p1(2,-3);
Ponto p2(4,5);

class Ponto
{
public:
    Ponto(int x1, int y1) : x(x1), y(y1) {}

    CalculaDist ();

private:
    int x;
    int y;
};

Como fazer isso?
Answer: Se você tem dois pontos a = [x1, y1], e b = [x2, y2], ao introduzir o ponto c = [x1, y2], você terá um triângulo retângulo com o ângulo reto no vértice c. Esse triângulo tem como um dos catetos, o lado ac, que mede |y2-y1|. O outro cateto é o lado bc, que mede |x2-x1|. Calcular o tamanho desses dois catetos é fácil porque eles estão alinhados em relação a um dos eixos (um no x e o outro no y), e portanto o comprimento deles é a diferença das posições em relação ao outro eixo.
Com isso, a distância entre os pontos a e b pode ser calculada com o teorema de Pitágoras, pois o segmento ab é a hipotenusa desse triângulo retângulo.
Eis como fica o seu código:
#include <iostream>
#include <cmath>
using namespace std;

class Ponto {
public:
    Ponto(int x1, int y1) : x(x1), y(y1) {}

    double calcular_distancia(Ponto &outro) {
        int a = x - outro.x;
        int b = y - outro.y;
        return sqrt(a * a + b * b);
    }

    int inline get_x() {
        return x;
    }

    int inline get_y() {
        return y;
    }
private:
    int x;
    int y;
};

int main() {
    Ponto p1(2, -3);
    Ponto p2(4, 5);
    double distancia = p1.calcular_distancia(p2);
    cout << distancia;
}

Veja aqui funcionando no ideone.
Answer: Para calcular a distância entre dois pontos em um plano cartesiano aplica-se a seguinte fórmula:

Com base no exemplo da sua pergunta, segue uma possível solução para o seu problema:
#include <iostream>
#include <cmath>

class Ponto
{
    public:

        Ponto( int x, int y ) : x(x), y(y) { }

        virtual ~Ponto( void ) { }

        double CalculaDist( const Ponto& p )
        {
            int x1 = p.x - this->x;
            int y1 = p.y - this->y;

            double d = std::pow(x1, 2) + std::pow(y1, 2);
            return std::sqrt(d);
        }

    private:

        int x;
        int y;
};

int main(void)
{
    Ponto p1( 2, -3 );
    Ponto p2( 4, 5 );

    std::cout << "Distancia: " << p1.CalculaDist( p2 ) << std::endl;

    return 0;
}

Saída:
$ ./distancia
Distancia: 8.24621

Answer: Como eu suspeito que o próprio conceito de distância não ficou muito claro, deixo aqui o meu contributo, apenas como complemento às já bastante boas respostas do @VictorStafusa e do @Lacobus.
Apresento assim um diagrama que elaborei do cálculo que está a tentar efetuar e respetivas representações no plano cartesiano.

Repare que o calculo para a linha vermelha, a distância, segue o teorema de Pitágoras, como o @VictorStafusa já indicou.
Esse é formalmente apresentado como:

Para o exemplo:

h - hipotenusa que corresponde à distância, a linha vermelha
a - cateto que corresponde à linha azul
b - cateto que corresponde à linha amarela


Anyway to simplify this rats nest of foreach loops?

Question: This works but is uglier than hell, basically it's iterating through two separate portions of a sub array, seeing if there's a greatest common denominator besides 1 in the values of both sub arrays, and if there is, multiplying the base value by 1.5
Sorry for the sloppy code ahead of time.
error_reporting(E_ALL);
ini_set('display_errors', '1');

class CSVParser
{

    public $output = NULL;
    public $digits = NULL;

    public function __construct($file)
    {

        if (!file_exists($file)) {
            throw new Exception("$file does not exist");
        }

        $this->contents = file_get_contents($file);
        $this->output = array();
        $this->digits = array();
        $this->factor = array();
    }

    public function parse($separatorChar1 = ',', $separatorChar2 = ';', $enclosureChar = '"', $newlineChar = "\n")
    {

        $lines = explode($newlineChar, $this->contents);
        foreach ($lines as $line) {
            if (strlen($line) == 0) continue;
            $group = array();
            list($part1, $part2) = explode($separatorChar2, $line);
            $group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part1), array("$enclosureChar \t"));
            $group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part2), array("$enclosureChar \t"));
            $this->output[] = $group;
        }
    }

    private function trim_value($value, $chars)
    {
        return preg_replace("#^( |" . $chars . ")+#", '', $value);
    }

    private function gcd($x,$y)
    {
        do {
            $rest=$x%$y;
        $x=$y;
        $y=$rest;
        } while($rest!==0);
        return $x;
    }

    public function algorithm()
    {
        $alpha = array(
            'c' => str_split('bcdfghjklmnpqrstvwxz'),
            'v' => str_split('aeiouy')
        );
        $i=$k=0;
        foreach ($this->output as $item) {
            $cnt = 0;
            $this->digits[$i] = array();
            foreach ($item as $part) {
                $this->digits[$i][$cnt] = array();
                $new = array();
                foreach ($part as $str) {
                    $v = count(array_intersect(str_split($str), $alpha['v']));
                    $c = count(array_intersect(str_split($str), $alpha['c']));
                    $t = strlen(str_replace(' ', '', $str));

                    $new = ($cnt == 0)
                        ? array('v' => $v, 'c' => $c, 't' => $t, 'm' => ($t%2) ? $v * 1.5 : $c)
                        : array('v' => $v, 'c' => $c, 't' => $t);

                    $this->digits[$i][$cnt][] = $new;
                }
                $cnt++;
            }
            $i++;
        }
        $h=$cuml=0;
            foreach($this->digits as &$slice) {
            foreach($slice[0] as &$sliceName){

                foreach($slice[1] as $sliceProduct) {
                foreach($sliceProduct as $pKey=>$pVal) {

                    foreach($sliceName as $nKey=>$nVal) {
                        $tmp[$h] = ($this->gcd($pVal,$nVal) != 1) ? ++$cuml:'';
                    }
                }
                    $tmp[$h] = $sliceName['m']*$cuml*1.5;
                    $h++;
                    $cuml=0;
                }$h=0;

            $sliceName['f'] = $tmp;
            $tmp='';
            }

            }
        foreach($this->digits as &$u){unset($u[1]);}
    }

}

$parser = new CSVParser("file.csv");
$parser->parse();   //print_r($parser->output);
$parser->algorithm();   print_r($parser->digits);

Sample CSV per request
Jeff Goes, Mika Enrar;Triple Threat, Dogs on  Bikes
Sonny Ray, Lars McGarvitch, Jason McKinley;Kasabian, Lords of Acid, Hard-Fi

The Output
Array
(
    [0] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [v] => 3
                        [c] => 3
                        [t] => 8
                        [m] => 3
                        [f] => Array
                            (
                                [0] => 40.5
                                [1] => 4.5 // Remainder.. So 'Jeff Goes' => 'Dogs on Bikes'
                            )

                    )

                [1] => Array
                    (
                        [v] => 3
                        [c] => 4
                        [t] => 9
                        [m] => 4.5
                        [f] => Array
                            (
                                [0] => 67.5 // High Score! So 'Mika Enrar' => 'Triple Threat'
                                [1] => 13.5
                            )

                    )

            )

    )

    [1] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [v] => 4
                        [c] => 2
                        [t] => 8
                        [m] => 2
                        [f] => Array
                            (
                                [0] => 24
                                [1] => 12
                                [2] => 24 // Next Highest 'Sonny Ray' => 'Hard-Fi'
                            )

                    )

                [1] => Array
                    (
                        [v] => 3
                        [c] => 8
                        [t] => 14
                        [m] => 8
                        [f] => Array
                            (
                                [0] => 84 // High Score! (This is really a tie, but 'm' has the highest secondary value so...)
                                [1] => 60 // 'Lars McGarvitch => 'Kasabian'
                                [2] => 84
                            )

                    )

                [2] => Array
                    (
                        [v] => 5
                        [c] => 5
                        [t] => 13
                        [m] => 7.5
                        [f] => Array
                            (
                                [0] => 0
                                [1] => 0 // The only one left 'Jason McKinley' => 'Lords of Acid'
                                [2] => 11.25
                            )

                    )

            )

    )

)

What it does
What this class does so far is split the csv one array, split content prior to ; and after into two sub arrays. Count the consonants and vowels of both, find if there is a greatest common denominator between the two subsections for each C V or mixed letter pair, and create a value to assign a band to a product.
What really needs to do though
The highest value generated should be associated with the band that created that high value. So what I am trying to really do is associate a name to a band depending on how high of a score it ultimately generates. I'm about half way through =(
As you guys can see, this code is a mess, literally. All I really want is to assign a name to a band based on the numbers I'm generating.
Comment: I fixed up your code for you. Try to clean it up before posting, please. It's really hard for people to read and understand it when the indentation is wrong, the spacing is inconsistent, etc.
Comment: ehime, thanks for posting the rest of the relevant code, but I haven't the foggiest idea of what it accomplishes. Can you also include a sample csv input and the corresponding output and describe how the transformation is done?
Comment: Maybe `array_walk_recursive` might be an option. (Did not bother to read/understand your code though.)
Comment: Crap, Brian I pasted over what you fixed, would you mind editing it to show me what you did in a separate code block?
Comment: Absolutely, give me a second and I'll write an input csv and post it under the code block. I'll comment underneath how it works (so far)
Answer: I have to agree with everyone else here... but I'd like to add:
Instead searching for how to traverse $this->digits more simply, you should strongly consider rethinking the structure of the data in $this->digits.
Furthermore, lumping everything into a single array doesn't always make sense. But when it does, the structure can be thought out so that it is intuitive and can be traversed easily.
Without more information about what this is doing, there is no way for us to suggest how to restructure your data / class. A start would be giving us what a sample $this->digits array looks like. Also, some more information about your problem would be good (like how this method is used).
Comment: I pushed out the entire class so you can see it, and maybe how it works. I agree that I am doing this in a backwards sort of way, but unfortunetly since I am not really an OO programmer I'm really struggling with what I'm doing here. Maybe you can help me figure it out Brian
Answer: If it works why are you changing it?  Performance?  Refactor?  Business changed?  Requirements changed?  Clean code Samaritan?  Boy Scout rule?
When I come across "spaghetti code" I leave it alone unless I absolutely must change it.  That said, I would write a couple of unit tests verifying the output of the "spaghetti code" so that I know that I did not break anything or make things worse.
Comment: I'm trying to squeeze a bit of performance from the code as it sits, it is extremely hard to pass off to a junior without a lot of explanation on the what and how.


manipulating divs with media queries

Question: My HTML looks something like this:

BLAH BLAH BLAH BLAH

BLAH BLAH BLAH BLAH

BLAH BLAH BLAH BLAH

However, when my screen resizes to mobile I need the 2nd elements picture to still display underneath the text instead of on top.
Is this possible with any built-in Twitter Bootstrap Classes? Or some media query manipulation?
Answer: you can use these classes. to hide and show the element according to the device
https://v4-alpha.getbootstrap.com/layout/responsive-utilities/
also you can use col-xs- classes
eg:

Comment: using col-xs- wont move an element thats above to below when resizing to mobile width

manipulating divs with media queries


Prove by giving an example that completeness is significant in Banach-Steinhaus theorem.

Question: I need to give an example of space and family of operators to prove that completeness of space $X$ in Banach-Steinhaus (the uniform boundedness principle) is in fact needed.
I guess space $c_{00}$ would be one of proper places to look for the needed operators, but it's my intuition.
Comment: A good intuition. Look for a sequence such that $T_n(x) = 0$ for all large enough $n$, for every $x\in c_{00}$.
Answer: Yes, $c_{00}$ (the space of sequences with finitely many nonzero terms) is the prime candidate for counterexamples involving lack of completeness. The family of linear functionals $f_n(x) = nx_n$, $n\in\mathbb{N}$, provides such a counterexample: bounded pointwise but not bounded in the norm.