Como mostrar em while um array com varias coisas

Question: Bom, vou me tentar me explicar a minha dúvida da melhor forma:
    <?php
    $steamid = 76561198337627631;
        $prices = file_get_contents('prices.txt');
        $prices = json_decode($prices, true);
        $inv = curl('https://steamcommunity.com/profiles/'.$steamid.'/inventory/json/730/2/');
        $inv = json_decode($inv, true);
        $items = array();
        foreach ($inv['rgInventory'] as $key => $value) {
            $id = $value['classid'].'_'.$value['instanceid'];
            $trade = $inv['rgDescriptions'][$id]['tradable'];
            if(!$trade) continue;
            $name = $inv['rgDescriptions'][$id]['market_hash_name'];
            $price = $prices['response']['items'][$name]['value']*10;
            $img = 'http://steamcommunity-a.akamaihd.net/economy/image/'.$inv['rgDescriptions'][$id]['icon_url'];
            $items[] = array(
                'assetid' => $value['id'],
                'bt_price' => "0.00",
                'img' => $img,
                'name' => $name,
                'price' => $price,
                'reject' => $reject,
                'sa_price' => $price,
                'steamid' => $steamid);
        }

        // curl

function getTemplate($name, $in = null) {
    extract($in);
    ob_start();
    include "template/" . $name;
    $text = ob_get_clean();
    return $text;
}

function curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

 ?>

Tenho o seguinte código, e pretendo dar um echo da minha array items, mostrando todos os parametros da mesma, contudo tem que ser em while porque eu tenho vários itens, como poderei fazer isso?
Obrigado.
Comment: Mas o seu com vários items só vai estar composto no final desse while certo? Porque não `foreach` depois do while e aí já pode imprimir cada parametro de cada item
Comment: Poderia me dar um exemplo por gentileza?
Answer: Soponhamos que acaba (depois desse while estar terminado) com estes 2 items:
$items[] = array(
    'assetid' => 1,
    'bt_price' => "0.00",
    'img' => '123.jpg',
    'name' => 'item1',
    'price' => '12.00',
    'reject' => 'Sim',
    'sa_price' => '10.00',
    'steamid' => 'steam1'
);
$items[] = array(
    'assetid' => 2,
    'bt_price' => "0.00",
    'img' => '456.jpg',
    'name' => 'item2',
    'price' => '2.00',
    'reject' => 'Não',
    'sa_price' => '1.00',
    'steamid' => 'steam2'
);

Depois pode fazer:
Maneira 1:
foreach($items as $item) {
    echo 'Detalhes do item ' .$item['name']. ':
';
    echo implode(', ', $item). '

';
}

Maneira 2 (aqui associamos a chave com o valor):
foreach($items as $item) {
    echo '

Detalhes do item ' .$item['name']. ':
';
    echo implode(', ', array_map(
        function ($v, $k) { return $k. ':' .$v; }, $item, array_keys($item))
    );
}

Maneira 3 (aqui imprimimos só as chaves/valores que queremos):
foreach($items as $item) {
    echo '

imagem do item ' .$item['name']. ':
';
    echo 'img: ' .$item['img'];
}

Comment: É isso mesmo Miguel, mas no caso de eu querer mostrar apenas por exemplo a img, de cada item como faria? Como mencionaria na array?
Comment: Ha isso é mais simples, eu vou colocar a maneira 3 com esse exemplo
Comment: Certo Obrigado.
Comment: Como coloquei na maneira 3 para aceder à `img` basta `$item['img']`
Comment: Obrigado Miguel pela ajuda era isso mesmo que precisava!


Selected Checkbox value(s) to a different page

Question: Iam new to this stuff. But I want to send checked checkbox value(s) to different page. Iam illustrating what i desire with code below;
php_checkbox.php file
<!DOCTYPE html>

<title>Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css" />

PHP: Get Values of Multiple Checked Checkboxes

<form action="checkbox_value.php" method="post">
Select Your Technical Exposure:

<input type="checkbox" name="check_list[]"
value="C/C++">C/C++

<input type="checkbox" name="check_list[]" value="Java">
Java

<input type="checkbox" name="check_list[]" value="PHP">PHP

<input type="checkbox" name="check_list[]"
value="HTML/CSS">HTML/CSS

<input type="checkbox" name="check_list[]"
value="UNIX/LINUX">UNIX/LINUX

<input type="submit" name="submit" Value="Submit"/>

</form>

checkbox_value.php file
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);

foreach($_POST['check_list'] as $selected) {
echo "
".$selected ."
";}

for ($x = 1; $x <= $checked_count; $x++) {

?>

<!DOCTYPE html>

Cell that spans two columns

To make a cell span more than one column, use the colspan attribute.

Technology
<?php echo $selected; ?>

<?php
}
}
else{
}
}
?>

The above code work. The problem is when I select Java and PHP, I get PHP displayed in both tables. When I select 3 options, the last option get displayed in all tables. What I need is when I select e.g. PHP, JAVA, and UNIX/LINUX, the 3 options (PHP, JAVA, UNIX/LINUX) be displayed on the tables separately - PHP on the first table, Java  on the second table and UNIX/LINUX on the third table.
When I select only 2 (e.g. Java and PHP), I want Java on the first table and PHP on the second.
Please help.
Comment: Why are you keeing the complete HTML from  to  inside the loop? Just keep the table inside the loop if you want separate table for each selected option.
Comment: Iam keeping them inside the loop because I want the whole thing (html document) to repeat. I want when I select 2 options, say, the first passed value for first checkbox be applied through the whole html document and again repeat for the second value.
Comment: You don't repeat the whole html document. It will mess up the whole page.
Answer: You have to write the row logic inside the loop.
<!DOCTYPE html>

Cell that spans two columns

To make a cell span more than one column, use the colspan attribute.

<?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);

foreach($_POST['check_list'] as $selected) {
echo "
".$selected ."
";
?>

Technology
<?php echo $selected; ?>

<?php
}
}
else{
}
}
?>

Answer: Checkout the code below. You don't need to count the number of elements sepeartely as you are using foreach() loop already.
Also, just loop the table, not the complete HTML.
   <?php
     if(isset($_POST['submit'])){
     if(!empty($_POST['check_list'])) {
    //Counting number of checked checkboxes.
    //$checked_count = count($_POST['check_list']);
    ?>

    <!DOCTYPE html>

Cell that spans two columns

To make a cell span more than one column, use the colspan attribute.

    <?php

    foreach($_POST['check_list'] as $selected)
    {
    ?>

            Technology
            <?php echo $selected; ?>

    <?php
    }
 }
}

?>

Comment: Thank you very much. This worked. Iam going to implement the concept on my project and I hope it will work also. The project has many tables, and other text/ stuff. Thank you again


Need help in FQL query

Question: I tried the query on FQL using https://developers.facebook.com/tools/explorer
The command I entered was SELECT message FROM status WHERE uid = me()
But the data returned was limited to 100 entries only. Is there some kind of restriction on the amount of data entered? Is there a way to change this restriction?
Comment: Did you try using a larger limit?
Answer: You can specify limit to the number of results returned.
The default is 100 as you can see. You should consider using larger limits.
Example: SELECT message FROM status WHERE uid = me() limit 200;

Need help in FQL query


Can a variable become statistically significant after the addition of another variable?

Question: I am doing forward stepwise logistic regression. I have heard that its common for a previously statistically significant variable to become not statistically significant when one or more variables are introduced into the model. However, I have never heard of the opposite.
This is my case right now. The first variable in my model was $x_1$ (by lowest p-value), the second variable introduced was $x_2$.
What's interesting is that $x_2$ is not statistically significant when it is modelled with Y alone. I am using R to do this though, I think this more of statistics question.
Answer: Sure, this can happen in any regression setting.
Consider this simple example:
Think of a case were $y$ is a set of random real-numbers. Let $x_1$ contain the pre-coma digit (i.e. $x_1=floor(y)$) and $x_2$ the post-comma digits (i.e. $x_2=y-floor(y)$)
Then when you regress $y$ linearly on $x_2$ alone you will most likely not find a relationship. Once you control for the pre-comma digit however, it does. Together $x_1$ and $x_2$ predict $y$ perfectly.


Evaluating the $\int \frac{x+2}{x^2-4x+8}$ - a doubt

Question: I have to find the antiderivative of $f(x) = \dfrac{x+2}{x^2-4x+8}$
I rewrote it to the form $$ \dfrac{x-2}{x^2 -4x + 8} + \dfrac{1}{\frac{1}{4} (x-2)^2 +1}$$
The next step supposedly is $$F(x) = \dfrac{1}{2}\ln|x^2-4x+8| + 2 \arctan\left(\dfrac{1}{2}(x-2)\right) + c$$
But now there is a problem which I've always had: I don't know why the $\dfrac{1}{2}$ in front of the $\ln(x)$ is there, same for the $2$ and the $\dfrac{1}{2}$ for the $\arctan(x)$. For me simplifying the function to standard integrals is easy, however finding the right factors and such is hard.
Comment: Differentiate $\ln|x^2-4x+8|$, and you'll discover why the $1/2$ is needed.
Comment: To know how to deal with the factors it is useful to bear in mind that $\frac{d}{dx}\arctan(ax+b)=\frac{a}{(ax+b)^2+1}$ and $\frac{d}{dx}\ln(ax+b)=\frac{a}{ax+b}$.
Comment: In general, if you would like to integrate
$$
  \int\frac{dx}{\frac14(x-1)^2+1}
$$
you are going to use the formula for $\int \frac{dy}{1+y^2}$, so it is very natural to make a change of variables $y = \frac12(x-1)$
Comment: @DavidMitra The problem cuts both ways
Comment: Guess that the antiderivative is $\ln|x^2-4x+8|$. Now check. The derivative of our guess is $\color{maroon}{2x-4\over x^2-4x+8 }$.  Not the same as $x-2\over x^2-4x+8$. But things are easily rectified: ${x-2\over x^2-4x+8}={1\over 2}\color{maroon}{2x-4\over x^2-4x+8 }$. So the antiderivative is ${1\over 2}{\ln|x^2-4x+8|}$. (The "$u$-substitution method" formalizes this process.)
Comment: @AndréNicolas I didn't do that, the editor did
Answer: When we use substitution, we need to determine $u$ as a function of $x$, and so, as a sort of "reverse" chain rule, we need also two substitute $du$ as a function of $dx$:
$$\int \dfrac{x-2}{x^2 -4x + 8}\,dx$$
Here, $u = x^2 - 4x + 8 \implies \,du = 2x - 4 = 2(x-2)\,dx \iff \frac 12 du = x - 2 \,dx$
This gives our substituted integrand:
$$\begin{align} \int \dfrac{x-2}{x^2 -4x + 8}\,dx & = \int \frac{\frac 12 \,du}{u} \\ \\ & = \frac 12 \int \frac {du}{u} \\ \\ & = \frac 12 \ln|u| + C =\frac 12 \ln|x^2 - 4x + 8| + C\tag{1}\end{align}$$

For the second term:
$$\int\dfrac{1}{\frac{1}{4} (x-2)^2 +1}\,dx = \int \dfrac{1}{\left(\frac 12(x-2)\right)^2 + 1} \,dx$$
We let $$u = \frac 12(x - 2) \implies du = \frac 12 dx \implies 2 du = dx$$
Substituting we have $$\begin{align} \int\dfrac{1}{\left(\frac 12(x-2)\right)^2 + 1} \,dx & = \int \frac 1{u^2 + 1}\cdot(2\,du)  \\ \\ & = 2 \int \cdot \dfrac{1}{u^2 + 1} \,du \\ \\& = 2\arctan\left(u\right) + C \\ \\ & = 2 \arctan\left(\frac 12(x - 2)\right) + C \tag{2} \end{align}$$

Putting $(1)$ and $(2)$ together:
$$F(x) = \dfrac{1}{2}\ln|x^2-4x+8| + 2 \arctan\left(\dfrac{1}{2}(x-2)\right) + c$$
Comment: So if you substitute with $u$, you have to express everything as $u$?
Comment: And the $2$ in the second example comes from the fact that $1 = 2[\dfrac{1}{2}(x-2)]'$?
Comment: yes, if you substitute in terms of u, everything needs to be expressed in terms of u, du, etc. The $2$ in the first case comes from the fact that $du = (\frac 12(x-2))' = \frac 12 x dx$ so $dx = 2 du.$
Comment: So, in the simple case of $\int \dfrac{1}{x^2+1} dx$, it's $\arctan(x)$ because $1= d(u)$ where $u=x$? How would you give the notation correctly in this case? Also, why is $du$ equal to $1$?
Comment: Then you'd have it evaluating to $\artan x + C$. There wouldn't even be a need to substitute $u = x \implies du = dx$
Comment: @amWhy: Nice way to clarify! +1
Answer: $$ \dfrac{x+2}{x^2-4x+8}= \dfrac{x-2}{x^2-4x+8}+4\cdot\frac1{(x-2)^2+2^2}$$
Putting $x^2-4x+8=u,2(x-2)dx=du\implies (x-2)dx=\frac{du}2$
So, $$\int \dfrac{x-2}{x^2-4x+8}=\frac12\cdot\int \frac{du}u=\frac12\cdot\ln|u|+C=\frac12\cdot\ln|x^2-4x+8|+C$$
Putting $x-2=2\tan\theta\implies dx=2\sec^2\theta d\theta$ in $\frac1{(x-2)^2+2^2},$
$$\int \frac{dx}{(x-2)^2+2^2}=\int\frac{2\sec^2\theta d\theta}{4\sec^2\theta}=\frac12\cdot\theta+K=\frac12\cdot\arctan\left(\frac{x-2}2\right)+K$$
Comment: Oops, I was wondering why our results were off: you forgot to carry down /include the factor of $4$ when integrating the second term of the sum at the top. So the second integral should be multiplied by 4.
Comment: @amWhy, I decidedly, left the multiplier apart.
Answer: Hint: What happens if you calculate $F'(x)$? Where do the $2$'s come from?
Comment: To be honest, I wouldn't know. The problem cuts both ways
Comment: By now the other answers have all explained this so have a look at those.
Answer: $\int$$\frac{1}{\frac{1}{4} (x-2)^2 +1}$=$4$$\int$$\frac{1}{(x-2)^2+4}$=$\frac{4}{2}$$\int$$\frac{2}{(x-2)^2+4}$=$\frac{4}{2}$$\tan^{-1}\frac{x-2}{2}$=...
You can simplify further. I have used the basics for differentiation of inverse trig functions.


rails custom action in nested route

Question: I have a route that looks as so:
  resources :contacts do
    resources :leads do
      get :process, on: :member
    end
  end

It generates the following helper:
process_contact_lead_path   GET /contacts/:contact_id/leads/:id/process(.:format)   leads#process

Now when I try to use it like so:
link_to "Process", process_contact_lead_path(@contact, @lead)

The following happens:
Started GET "/contacts/2/leads/2/process" for 127.0.0.1 at 2015-01-10 13:57:05 -0500

ArgumentError - wrong number of arguments (1 for 0):

It is expecting my controller action to look like this:
  def process(arg)
    puts arg # => process
  end

So the Rails controller is expecting an argument which is the string "process". Obviously I am doing something wrong. Process is the action to be called and not an argument to pass to the controller action.
How can I address this issue?
Answer: I think the problem is caused by a method name conflict. process is an internal method of Rendering. The simplest thing to do is to just rename the action in routes or route it to a different action.
resources :contacts do
  resources :leads do
    get :process, on: :member, to: "leads#process_action"
  end
end

rails custom action in nested route


Asymptotic approximate solution of the parabolic cylinder differential equation

Question: In chapter 3 (example 4) of the book "Advanced Mathematical Methods for Scientists and Engineers", by Bender and Orszag, I want to get the approximate solution for $+\infty$ for the parabolic cylinder differential equation:
$$y'' + (\nu + 1/2 -x^2/4)y = 0.$$
First I get rid of the singularity at infinite using the following transformation:
$$y = \mathrm e^{S(x)}$$
yielding
$$S'' + S'^2 + \nu + 1/2 - x^2/4=0.$$
Then I assume the following approximations $S'' \ll S'^2$ and $\nu + 1/2 <\ll1/4 x^2$,
which gives,
$$S(x) \approx \pm x^2/4$$
when $x \to \infty$.
This is the controlling factor of the general differential equation. To get the leading behavior I assume that
$$S(x) \approx \pm x^2/4 + C(x)$$
where
$C(x) \ll \pm x^2/4 $.
I know that the answer to this problem is given by
$$y \approx C_1 x^{-(\nu+1)} \mathrm e^{x^2/4 }$$
and
$$y \approx C_2 x^{\nu} \mathrm e^{-x^2/4 }.$$
However I don't know how to reach such result. The differential equation for $C(x)$ is given as
$$(\pm 1/2 + C'') + (\pm x/2 + C')^2 + \nu + 1/2 - x^2/4 = 0,$$
Using the approximation for $C(x)$ I get that $C' \ll\pm x/2$ and $C'' \ll \pm 1/2$, hence, the differential equation would not depend on $C(x)$, which makes no sense.
I have tried to assume only one of these conditions at a time, however, even so, I do not get to the desired result.
Comment: Might [math.se] be better suited for this math question?
Answer: By taking
$y=e^{S(x)}$
you have already pulled out the exponential behaviour in the solution.
As a result another exponential correction
$y=e^{S(x)}e^{C(x)}$
will not further elucidate $y$'s behaviour. So no surprise that the differential equation for $C$ becomes independent of it.
Try the following correction instead
$y=e^{S(x)}p(x)=e^{S(x)}e^{ln(p(x))}$

For $S(x)=k \frac{x^2}{4}$

$k=1$ leads to $p''+x p'+(\nu+1)p=0$ which (ignoring $p''$ term) solves as $x^{-(\nu+1)}$
$k=-1$ leads to $p''-x p'+\nu p=0$ which (ignoring $p''$ term) solves as $x^{(\nu)}$
Comment: It is what I needed, thanks a lot.

Just another question, I see your argument that we cannot use another exponential approximation for the function $C(x)$, however that is exactly how the book does for the modified Bessel function (it is example 2, page 92, if you are interested). In this case, such substitution works. Would you be able to explain why?
Comment: can't seem to find the use of the second exponential. $w(x)$ is sub exponential(eqn 3.5.8a)


Raspberry pi with pygame.mixer audio produces only static

Question: I'm quite new with raspberry pi and am very new but I am trying to play an audio file through a python file on a pi B. I played the audio from the command line using omxplayer and it worked fine but when i run the following code it plays only static.
from pygame import mixer
mixer.init()
wow = mixer.Sound('Wow.mp3')
wow.play()
time.sleep(5)

I tried using mixer.load('Wow.mp3') and other variations but still only get static. I tried putting things in the init like mixer.init(4800, -16, 1, 1024) and using pre_init but to no avail. I also tried adding disable_audio_dither=1 to config.txt. Any and all help would be greatly appreciated thank you very much.
Comment: Have you tried other audio files and formats as well?
Answer: Sometimes if sound is supposed to be playing but isn't, and the speakers are turned all the way up, it will play static instead.  This is probably a computer problem, not a pygame problem.  Check whether audio plays in other locations.  If it does not, it is definitely a computer problem.
If using Linux (you probably are, Raspbian is a variant of Debian which is Linux), and you have identified that it is a computer problem, try initializing ALSA by typing alsactl init as root in the Linux Terminal.  If this does not work and the above is true, then you are having some audio problems that will take a bit of research to fix.
If audio does play in other locations, then it is probably a file format issue.  It's possible that the bitrate is different, the format is wrong, etc.  Also, here is a quote pulled directly from Pygame documentation:

Be aware that MP3 support is limited. On some systems an unsupported format can crash the program, e.g. Debian Linux. Consider using OGG instead.

https://www.pygame.org/docs/ref/music.html
Other than this, there isn't much we can do to help you.  A problem like this that isn't fixed by the above is usually a problem specific to very few computer setups.  You will probably have to do some personal research.
If you need any more help, please notify me in the comments.
Comment: I changed it to .ogg like you said and it worked! But there's static in the background that only occurs when it is played by the python file and not when from the command line
Comment: It also occurs when I use omxplayer from the command line but at a lower volume
Comment: It is most likely because your speakers are too loud.  See if turning the volume down helps.
Comment: The lower the volume the more obvious the static becomes unfortunately


OnClickListener won't work

Question: I got a problem with my OnClickListener and can't find my mistake!
I tried to use fragments, the view they come from fragment_app_launch.xml
I tried to use a Toast to test whether the OnClickListener is called, but it seems its not!
package com.pthuermer.juraquiz;

import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityAppLaunch extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app_launch);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

    ActionBar actionbar = getSupportActionBar();
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionbar.setTitle(R.string.app_name);

    ActionBar.Tab fragTab1 = actionbar.newTab().setText(R.string.tabBar_1);
    Fragment fragmentQuiz = new FragmentAppLaunch();
    fragTab1.setTabListener(new TabListener(fragmentQuiz));
    actionbar.addTab(fragTab1);

    ActionBar.Tab fragTab2 = actionbar.newTab().setText(R.string.tabBar_2);
    Fragment fragmentStatistics = new FragmentStatistics();
    fragTab2.setTabListener(new TabListener(fragmentStatistics));
    actionbar.addTab(fragTab2);

    ActionBar.Tab fragTab3 = actionbar.newTab().setText(R.string.tabBar_3);
    Fragment fragmentProVersion = new FragmentProVersion();
    fragTab3.setTabListener(new TabListener(fragmentProVersion));
    actionbar.addTab(fragTab3);

    ActionBar.Tab fragTab4 = actionbar.newTab().setText(R.string.tabBar_4);
    Fragment fragmentInfo = new FragmentInfo();
    fragTab4.setTabListener(new TabListener(fragmentInfo));
    actionbar.addTab(fragTab4);

    ActionBar.Tab fragTab5 = actionbar.newTab().setText(R.string.tabBar_5);
    Fragment fragmentSettings = new FragmentSettings();
    fragTab5.setTabListener(new TabListener(fragmentSettings));
    actionbar.addTab(fragTab5);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.app_launch, menu);
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    private Button btn_q_c_1;
    private Button btn_q_c_2;
    private Button btn_q_c_3;
    private Button btn_q_c_4;

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_app_launch, container, false);

        btn_q_c_1 = (Button)rootView.findViewById(R.id.btn_q_c_1);
        btn_q_c_1.setOnClickListener(btn_q_c_listener);
        btn_q_c_2 = (Button)rootView.findViewById(R.id.btn_q_c_2);
        btn_q_c_2.setOnClickListener(btn_q_c_listener);
        btn_q_c_3 = (Button)rootView.findViewById(R.id.btn_q_c_3);
        btn_q_c_3.setOnClickListener(btn_q_c_listener);
        btn_q_c_4 = (Button)rootView.findViewById(R.id.btn_q_c_4);
        btn_q_c_4.setOnClickListener(btn_q_c_listener);

        return rootView;

    }

    private OnClickListener btn_q_c_listener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(getActivity(), "TESTTOAST", Toast.LENGTH_LONG).show();

            if (v == btn_q_c_1) {
                Globals.setQUESTION_CAT(1);
                startActivity(new Intent(getActivity(), ActivityQuiz.class));
            }
            else if (v == btn_q_c_2) {
                Globals.setQUESTION_CAT(2);
                startActivity(new Intent(getActivity(), ActivityQuiz.class));

            }
            else if (v == btn_q_c_3) {
                Globals.setQUESTION_CAT(3);
                startActivity(new Intent(getActivity(), ActivityQuiz.class));

            }
            else if (v == btn_q_c_4) {
                Globals.setQUESTION_CAT(0);
                startActivity(new Intent(getActivity(), ActivityQuiz.class));
            }
            else {
                // Log
            }

        }

    };

}

class TabListener implements ActionBar.TabListener {

    private Fragment fragment;

    public TabListener(Fragment fragment) {
        this.fragment = fragment;
    }

    @Override
    public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {

        // TODO Auto-generated method stub
        ft.replace(R.id.container, this.fragment);

    }

    @Override
    public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

}

}

xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#edf8ff"
tools:context="com.pthuermer.juraquiz.AppLaunch$PlaceholderFragment" >

<TextView
    android:id="@+id/tv_heading_app_launch"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/heading_app_launch"
    android:textSize="20sp"
    android:gravity="center"
    android:background="#ffffff" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/tv_heading_app_launch"
    android:gravity="center_vertical"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_q_c_1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="@string/btn_q_c_1" />

    <Button
        android:id="@+id/btn_q_c_2"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="@string/btn_q_c_2" />

    <Button
        android:id="@+id/btn_q_c_3"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="@string/btn_q_c_3" />

    <Button
        android:id="@+id/btn_q_c_4"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="@string/btn_q_c_4" />

</LinearLayout>

Comment: Are there any errors in your logcat? Inside your onClick method, can you get the v.getId() and then use it to compare to see which item  was clicked?
Comment: no nothing in my logcat
Comment: switch wont bring me closer to the solution
Comment: i guess we will have to see the xml in use...
Comment: That was just a suggestion Philip;
Comment: i edited my question, the xml is now there.
Comment: it doesn't even show me the toast in my onclicklistener, so its not even called..
Answer: Try removing the static from your PlaceholderFragment.
Comment: Then try defining your `OnClickListener` within `onCreate()` before you assign it to the buttons. Maybe android is just putting a copy of the listener onto the button, but the listener that's copied doesn't have the `onClick()` method at that time, yet.
Comment: you mean onClick="btw_q_c_listener" in XML?
Answer: Try the following code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_app_launch, container, false);

    return rootView;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    OnClickListener btn_q_c_listener = new OnClickListener() {

    @Override
    public void onClick(View v) {

        Toast.makeText(getActivity(), "TESTTOAST", Toast.LENGTH_LONG).show();

        if (v == btn_q_c_1) {
            Globals.setQUESTION_CAT(1);
            startActivity(new Intent(getActivity(), ActivityQuiz.class));
        }
        else if (v == btn_q_c_2) {
            Globals.setQUESTION_CAT(2);
            startActivity(new Intent(getActivity(), ActivityQuiz.class));

        }
        else if (v == btn_q_c_3) {
            Globals.setQUESTION_CAT(3);
            startActivity(new Intent(getActivity(), ActivityQuiz.class));

        }
        else if (v == btn_q_c_4) {
            Globals.setQUESTION_CAT(0);
            startActivity(new Intent(getActivity(), ActivityQuiz.class));
        }
        else {
            // Log
        }
    };

    btn_q_c_1 = (Button)getView().findViewById(R.id.btn_q_c_1);
    btn_q_c_1.setOnClickListener(btn_q_c_listener);
    btn_q_c_2 = (Button)getView().findViewById(R.id.btn_q_c_2);
    btn_q_c_2.setOnClickListener(btn_q_c_listener);
    btn_q_c_3 = (Button)getView().findViewById(R.id.btn_q_c_3);
    btn_q_c_3.setOnClickListener(btn_q_c_listener);
    btn_q_c_4 = (Button)getView().findViewById(R.id.btn_q_c_4);
    btn_q_c_4.setOnClickListener(btn_q_c_listener);
}

Comment: Then could you please try get that fragment out of `ActivityAppLaunch`? Go and put it into a separate java file named `PlaceholderFragment.java`, remove `static` and try again.

**Hint:** You could try using only one instance of that Fragment by calling the constructor only once instead of calling it every time you want to display the fragment.
Call the constructor one time and store its instance. And then, when you're about to display it, just take that instance and don't call the constructor again.
Comment: right now I can't try nothing. Eclipse won't create R.java... I'm stuck
Comment: Have a look at [this](http://stackoverflow.com/questions/2757107/developing-for-android-in-eclipse-r-java-not-generating)

OnClickListener won't work


Ordered ring and mutiplicative ordinal

Question: If $(E,<)$ is a linear order, let $s(E)$ denote the supremum of the set of ordinals which (order-)embed in $(E,<)$.
$s(E)$ is also the set of ordinals which embed in $E$ with a non cofinal range.
If $(G,+,0,<)$ is an ordered group, then $s(G)$ is an additive ordinal because given $\alpha < s(G)$ and $f_{\alpha}: \alpha \rightarrow G$ a positive order embeding with strict upper bound $a$, $f_{\alpha.2}:= \{(\alpha.t + \beta,f_{\alpha}(\beta) + t.a) \ | \ (t,\beta) \in 2 \times \alpha\}$ is an order embedding $\alpha.2 \rightarrow G$ with $2.a$ as a strict upper bound.
If $(R,+, \ ,0,1,<)$ is a discrete ordered ring, then $s(A)$ is a multiplicative ordinal because given $\alpha < s(G)$ and $f_{\alpha}: \alpha \rightarrow R$ a positive order embeding with strict upper bound $a$, $f_{{\alpha}^2}:= \{(\alpha.\beta + \delta,af_{\alpha}(\beta) + f_{\alpha}(\delta)) \ | \ \beta,\delta \in \alpha\}$ is an order embedding ${\alpha}^2 \rightarrow R$ with $a^2 + a$ as a strict upper bound.
If $R$ is an ordered ring but $R$ is not discrete, $f_{{\alpha}^2}$ need not be an embedding because two distinct points in the range of $f_{\alpha}$ may be very close to each other.
Is $s(R)$ multiplicative nonetheless whenever $R$ is a ordered ring?
Answer: The question actually has an easy positive answer:
Let $\alpha$ be an element of $s(R)$.
$s(R)$ being additive, either $s(R) = \omega_0$, in which case it is also multiplicative, or $\forall \gamma \in s(R), \gamma + \omega_0 \in s(R)$, so one can assume that $\alpha$ is limit.
Let $f_{\alpha}: \alpha \rightarrow R$ be a positive order emdedding with strict upper bound $a \in R$. Let $\Delta(f_{\alpha}): \alpha \rightarrow R$ denote $\gamma \longmapsto f_{\alpha}(\gamma+1) - f_{\alpha}(\gamma)$.
We consider two cases:
1)$\Delta(f_{\alpha})$ takes some value $\varepsilon$ such that $a\varepsilon < 1$. In this case, define $f_{\alpha^2}: \alpha^2 \rightarrow R$ by $\forall \beta,\gamma < \alpha, f_{\alpha^2}(\alpha.\beta + \gamma) := f_{\alpha}(\beta) + \varepsilon\Delta(f_{\alpha})(\beta)f_{\alpha}(\gamma)$.
Then $f_{\alpha^2}$ is strictly increasing and has $2.a$ as a strict upper bound, so ${\alpha}^2 \in s(R)$.
2)Otherwise, define $f_{\alpha^2}(\alpha.\beta + \gamma) := a^2f_{\alpha}(\beta) + f_{\alpha}(\gamma)$. $f_{\alpha^2}$ is an order embedding, with $a^3 + a$ as a strict upper bound, and ${\alpha}^2 \in s(R)$.
So $s(R)$ is multiplicative.

Ordered ring and mutiplicative ordinal


Fragment of a bar before break when transitioning to staff group

Question: Here is a demonstration of what I want to achieve. A single staff for a few measures, then additional staves joining to form a staff group:

However, with a key signature, I get an additional fragment of a bar before the line break at the transition to the staff group:

How can I get rid of that?
Here is my sample code:
\version "2.22.1"

\score {
           <<
              \new ChordNames \chordmode { g1 c1 g1 c1 }
              \new StaffGroup {<<
                \new Staff {
                  a2 a a a \break
                  <<
                               { b2 b b b }
                    \new Staff { c'2 c' c' c' }
                    \new Staff { d'2 d' d' d' }
                  >>
                  }
              >>}
           >>
}

\score {
           <<
              \new ChordNames \chordmode { g1 c1 g1 c1 }
              \new StaffGroup {<<
                \new Staff {
                  \key g \major
                  a2 a a a \break
                  <<
                               {  b2 b b b }
                    \new Staff { \key g \major c'2 c' c' c' }
                    \new Staff { \key g \major d'2 d' d' d' }
                  >>
                  }
              >>}
           >>
}

Answer: That fragment of a bar is there because LilyPond is leaving room for cancelling an old key signature before instantiating the new key signature.
So, right after setting the key signature of both of the new staves, place:
\once \set Staff.explicitKeySignatureVisibility = ##(#f #t #t)
to stop the visibility of the key signature before the break.

You may also want to place:
\once \omit Score.TimeSignature
to get rid of the extra time signatures.

N.B.  Set the key sig. at the at staff level of each new staff, but set the time sig. only once at the score level.  This is much more practical, because the new staves could possibly be in different (written) key sig. (if you have transposing instruments), where as you are most likely to be using just one time sig. at a time (unless you're using a polymeter).

...
\new Staff {
    \key g \major
    a2 a a a \break
    \once \omit Score.TimeSignature % NEW
    <<
        {
            b2 b b b
        }
        \new Staff {
            \key g \major
            \once \set Staff.explicitKeySignatureVisibility = ##(#f #t #t) % NEW
            c'2 c' c' c'
        }
        \new Staff {
            \key g \major
            \once \set Staff.explicitKeySignatureVisibility = ##(#f #t #t) % NEW
            d'2 d' d' d'
        }
    >>
}
...

Answer: Add \RemoveAllEmptyStaves to the \StaffGroup \layout context. (See Hiding Staves in the LilyPond Manual.)
\layout {
  \context {
    \StaffGroup
    \RemoveAllEmptyStaves
  }
}

This will allow for some cleanup of your existing code, but with the addition of specifying rests for the staves to be hidden. For example:
\score {
    \new StaffGroup {<<
        \new ChordNames \chordmode { g1 c1 g1 c1 }
        \new Staff { a2 a a a \break b2 b b b }
        \new Staff { R1 R1 \break c'2 c' c' c' }
        \new Staff { R1 R1 \break d'2 d' d' d' }
    >>}
}


Lilypond inserting bars at wrong place

Question: I find that lilypond routinely inserts bars at wrong places and does not even warn about it. e.g. Consider this:
{
  \time 4/4
  \tempo 4 = 100
  \relative c' {
    e32 fis32 g32 a32 b8 c4 b32 c2 d32 e32 fis16
  }
}

Lilypond produces this:

There should not be a bar after C2. In fact the only way to insert a bar is to split the C2 note and use ties:
{
  \time 4/4
  \tempo 4 = 100
  \relative c' {
    e32 fis32 g32 a32 b8 c4 b32 c4..~ c32~ | c32 d32 e32 fis16
  }
}

The documentation is very sparse on this aspect. Is there a way to get lilypond to at least warn about the error? It would be awesome if lilypond could auto correct as well!
Comment: Is this what you need? https://lilypond.org/doc/v2.21/Documentation/notation/displaying-rhythms#automatic-note-splitting
Comment: That bar line isn't wrong. Your input is self-contradictory in a way that makes it impossible to render bar lines in a consistent way (and Lilypond will warn you about this if you use bar annotations in your source, which you should).
Comment: A life saver!! Please write it as an answer. I will accept. Lilypond documentation is a mess. Very difficult to figure out what is where.
Comment: @user1079505 For my example lilypond produced 3 dots. Is there any setting to limit the number of dots ?
Comment: But I don't have much idea about lilypond... I just figured that this first bar is too long, and realized you expected the half note to be split, and somehow found it. Perhaps someone with more lilypond expertise can explain it better.
Comment: Re "LilyPond documentation is a mess": have you tried the index? If you go to https://lilypond.org/doc/v2.24/Documentation/notation/lilypond-index.html and Control-F for "split", you find what you want instantly...
Answer: Lilypond is not a magic machine. It won't try to second-guess what you meant. Quite the opposite: it will do exactly what you tell it to do.
If you say \time 4/4, then it will put a barline every four quarter-notes, no matter what notes are used. In this case, that falls "in the middle" of the half-note, so there is a barline and some part of the note length overflows into the next bar. The placement of the barlines is purely automatic and it has nothing to do whatsoever with where you put the | symbols.
The | symbols fulfill another role: they're bar checks. If you use them, Lilypond will check whether the bars coincide with the bar checks exactly, and you get a warning for any that do not match.
For instance, in your first code snippet, I have no idea where you wanted the barline to occur, because your half note is 1/32 too long. But if you used the | symbol at that place, Lilypond would warn you.
In the second code snippet, everything works out, because you replaced a half-note with a double-dotted quarter note and a 1/32 note, which is only 7/4 × 1/4 + 1/32 = 15/32 in total, so it's exactly that 1/32 less than the half note. Lilypond will find that it is putting the barline exactly where you have put the |, and it doesn't complain.
Finally: I don't know what documentation you are reading, but I would suggest starting with the Learning manual. Coincidentally, this matter is the very first thing explained in the manual (if we don't take installation instructions into account).
Not sure if this gives the answer you wanted. If not, feel free to write a comment and I'll try to modify it to be more helpful.
Comment: Automatic note splitting is exactly what I was looking for. What' s the point of using a tool if I have to do these things manually?  I think putting the bar after c2 without any warning is not correct.
Comment: First, notes extending over bar lines are found in Renaissance music scores, and second, it is much more difficult than you'd think to guess how to do the splitting reliably.
Comment: @kargirwar I mean in that case it's a effect that you do want, but chances are also there that it isn't. Like suppose you added an extra note somewhere by accident hold a note for longer or shorter than expected and as Lilypond can't tell your intentions, it breaks apart a half note that should actually be a half note. You wouldn't get an error it's just all wrong and your focus might be on the split half note not realizing what caused it. While if everything remains as is and you get a warning that there are too many notes in a bar, you might have an easier time debugging that.
Comment: The automatic split thing is working wondefully well for me , so no issues really.
Comment: Uh, "works in the score I have tested it on" and "satisfies the needs of everyone without surprising anyone" are really different things.

Lilypond inserting bars at wrong place


Ordem crescente e decrescente angularjs

Question: Galera tenho um conjunto de dados que o organizo mediante a uma escolha, crescente ou decrescente, ou posso deixar na ordem que já se encontra.
O sistema funciona normalmente com a ordem dos elementos, o problema é que os elementos só estão sendo mostrados quando é selecionada a órdem de amostra, crescente ou decrescente, em um select.
Gostaria de solucionar a questão: como mostrar os elementos sem a necessidade de selecionar a órdem de amostra para que essa seleção seja de fato facultativa?

<select ng-model="selectedChoice">
  <option ng-repeat="choice in choices" value="{{choice.name}}" ng-init="Todos">{{choice.name}}</option>
</select>

{{organ.name}}

   quantidade de serviços : {{organ.services.length}}

{{organ.name}}

quantidade de serviços : {{organ.services.length}}

$scope.choices = [{
  name: "Crescente"
}, {
  name: "Decrescente"
}];
Answer: A primeira coisa é que você está forçando a ordenação no HTML. Quando você possuir uma ordenação dinâmica fica mais fácil de fazer e mais limpo realiza-lo no controller. Em segundo lugar você tem um ng-if e isso limita a visualização apenas para a opção "Crescente". Segue um exemplo de como você pode fazer dinamicamente.

(function() {
  'use strict';

  angular
    .module('appExemploOrdenacao', []);

  angular
    .module('appExemploOrdenacao')
    .controller('OrdenacaoController', OrdenacaoController);

  OrdenacaoController.$inject = ['$filter'];

  function OrdenacaoController($filter) {
    var ordenacao = this;
    var servicos = [];

    ordenacao.opcoes = [];

    ordenacao.organizar = organizar;

    iniciar();

    function iniciar() {
      servicos.push({nome: 'Serviço 1'});
      servicos.push({nome: 'Serviço 12'});
      servicos.push({nome: 'Serviço 123'});
      servicos.push({nome: 'Serviço 12345'});
      servicos.push({nome: 'Serviço 123457'});
      servicos.push({nome: 'Serviço 123456'});
      servicos.push({nome: 'Serviço 1234578'});
      servicos.push({nome: 'Serviço 1234'});

      ordenacao.opcoes = [{name: ''}, {name: 'Crescente'}, {name: 'Decrescente'}];
    }

    function organizar() {
      if (ordenacao.selecionado.name === 'Crescente') {
        return $filter('orderBy')(servicos, '+nome');
      } else if (ordenacao.selecionado.name === 'Decrescente') {
        return $filter('orderBy')(servicos, '-nome');
      } else {
        return servicos;
      }
    }
  }
})()

    <select ng-init="ordenacao.selecionado = ordenacao.opcoes[0]"
            ng-options="opcao.name for opcao in ordenacao.opcoes"
            ng-model="ordenacao.selecionado">
    </select>

      {{servico.nome}}

Ordem crescente e decrescente angularjs


Change video language in php

Question: I am working on a project, a web site for playing movies.
I'm having trouble setting the language of the video, in case some films are dual audio.
How can I do this procedure? I want to leave the video language in PT-BR.
I made the PHP script below, but it doesn't work, thank you to anyone who can help, thanks.

 <?php } ?>

Answer: Your JavaScript is breaking here: languages: {pt-br: {LIVE... The problem is the hyphen in the key. I can't test your exact code, but try this instead: languages: {"pt-br": {LIVE...
Comment: Without success, I made the change but the film is still in another language
Comment: Can you help me? i am willing to pay for it

Change video language in php


strftime() : bool(false) not showing nothing

Question: I want to display on my page the current date in this format: 22/02/2013 - 12:00 (day/month/year - hour)
I use strftime("%d/%b/%G - %R", time()) but shows nothing on the page. If  I do
echo var_dump(strftime("%d/%b/%G - %R", time()))

it shows bool(false). Any idea what I'm doing wrong??
Answer: From the strftime() documentation:

As the output is dependent upon the underlying C library, some conversion specifiers are not supported. On Windows, supplying unknown conversion specifiers will result in 5 E_WARNING messages and return FALSE. On other operating systems you may not get any E_WARNING messages and the output may contain the conversion specifiers unconverted.

So, you are probably using unsupported format parameters.
Note: by default time() is used for a timestamp, so you can use strftime() with it if you require this defaul tiemstamp.
Comment: not only those, on the same man page is written "This means that %e, %T, %R and, %D (and possibly others) - as well as dates prior to Jan 1, 1970 - will not work on Windows, some Linux distributions, and a few other operating systems"
Comment: @Jack It depends on the underlying C library, which is different for each OS. This information is not supplied, so I cannot go into more details...
Comment: " Windows only:

The %e modifier is not supported in the Windows implementation of this function. To achieve this value, the %#d modifier can be used instead. The example below illustrates how to write a cross platform compatible function.

The %z and %Z modifiers both return the time zone name instead of the offset or abbreviation. "

I don't get it. Only the parameters that says here are not supported in Windows or not???
Comment: Yes, but it is also stated that it depends on the underlying C library... You best shot is to try and find out which modifier is not working by removing one at the time until your code works...
Answer: Windows doesn't support %G or %R, you should use %Y and %H:%M respectively.
strftime("%d/%b/%Y - %H:%M")

Comment: @Lykos You mean [`date_default_timezone_set()`](http://php.net/manual/de/function.date-default-timezone-set.php)?
Comment: Is it also possible to set the time according to the localtime too?? how can i do this??
Comment: What do you mean? Whose local time?
Comment: I need some more help please . I have the strftime is inside a  and wht i'd like to do is to add some ajax. How can I apply the strftime function inside my jquery .load() function???
Comment: @Lyk that should be another question then.
Comment: Windows doesn't support %e either, use %d instead.
Comment: @user2019515 The question wasn't so much about what other things Windows doesn't support :)
Comment: @Jack The problem was Windows not supporting format date strings, noting which strings aren't supported seems appropriate.
Comment: @user2019515 Except that the use of `%e` is clearly mentioned in the manual for strftime() whereas `%G` and `%R` are somewhat harder to find.
Answer: Try this:
echo date('d/m/Y - H:s');

If you need to, you can set the timezone like this:
date_default_timezone_set('UTC');

Comment: `date()` is not locale sensitive.
Comment: @OgunAcik Please do not modify another users post by *adding additional details*, instead use a comment to point these additional details, so the OP can determine whether or not to update his post (if he agrees)
Comment: I agree and have added the changes myself, thanks @OgunAcik for the suggestion, best to suggest in comments first as Veger says though! :)


Como alterar a cor do menu ao passar o mouse em cima

Question: Implementei um CSS no meu sistema onde eu passo o mouse por cima do menu e exibe os submenus.
Esta é a CSS pra passar o mouse por cima dos menus
ul.nav li.dropdown:hover ul.dropdown-menu
{
    display: block;
}

só que é o seguinte, quando eu passo o mouse por cima destes menus eu gostaria que a cor alterasse como se fosse a do clica como mostra as fotos abaixo:
Clicando no Menu:

Sem clicar no menu:
Answer: É só definir a propriedade background-color usando o seletor ul.nav li.dropdown:hover.
ul.nav li.dropdown:hover
{
    background-color: algumTomDeAzulAqui;
}

ul.nav li.dropdown:hover ul.dropdown-menu
{
    display: block;
}

Comment: com o background-color o submenu que muda de cor
Comment: @LeonardoMacedo Esqueci de tirar o final do seletor, tenta dessa forma
Comment: retirando o  ul.dropdown-menu o menu fica com a cor correta porem o submenu não aparece
Comment: Não, @LeonardoMacedo Você tem que manter os dois CSS.
Comment: Funcionou! Muito obrigado! daqui 5 minutos eu coloco como positivo aqui!
Comment: eu ja coloquei como positivo mais como é relacionado a questão queria saber mais uma coisa. Eu achei uma coisa aqui também, não sei se isso pode ser feito por css também, quando eu clico no no menu e passo o mouse no outro, o menu que cliquei não some, e abre o que passei o mouse por css eu consigo arrumar isso ?
Comment: Conseguir consegue, mas, embora tenha relação com a pergunta atual, acho que é outra coisa. Seria melhor abrir uma nova pergunta, não acha? Até porque, vai ser necessário um exemplo mais detalhado do menu...
Comment: beleza eu vou abrir aqui
Comment: criei https://pt.stackoverflow.com/questions/211448/passar-mouse-no-menu-e-exibir-submenus


Degree of an antipodal map

Question: Let $f:S^n\to S^n$ a continuous map, $n>0$; we consider the induced homomorphism $f_* : H_n(S^n)\to H_n(S^n)$, and, recalling $H_n(S^n)\simeq\mathbb Z$, define $deg(f)\doteq f_*(1)$.
I'm asked to find the degree of the reflection map $f:(x_0,\dots,x_n)\mapsto (x_0,\dots,x_{n-1},-x_n)$; my main problem is that I should do it only using tools from singular homology theory: I have not dealt with the concept of orientation of a manifold, nor I know anything about reflections on an hyperplane (I've browsed previous questions, and these seems to be the suggested tools to address the quandary).
It looks like the only possible way to proceed is to track the way singular simplices $\sigma:\Delta_n\to S^n$ are influenced by the map $f$, and then try to see how their homology class changes: but it's quite an impervious path, and I don't see how to proceed.
Any hints?
Edit: I'm also having problem dealing with this (apparent) contradiction: consider the maps $f,\pi:S^1\to S^1$ with $f(x_1,x_2)=(-x_1,x_2)$ and $\pi(x_1,x_2) = (x_2,x_1)$; then $f\cdot \pi\cdot f\cdot\pi = -id$, thus apparently $deg(f\cdot\pi))^2=-1$...
Comment: As per your edit, on $S^1$, the map $-id$ has degree $1$, not $-1$.
Comment: The map you wrote down is a reflection, not the antipodal map.  By way of contrast, the antipodal map would send $(x_0,...,x_n)$ to $(-x_0, ..., -x_n)$ (every coordinate is negated).  If you want to go the simplices method, I suggest finding a nice triangulation so that your desired map sends simplices to simplices.  So, in the case of $S^1$, I'm thinking of a diamond shape, for $S^2$ I'm thinking of two triangular based pyramids (sans base), stuck base to base. Try to generalize this.
Comment: I don't think your definition of the antipodal map is right.  Usually it refers to the map $x \mapsto -x$.  $(x_0, \ldots, x_n) \mapsto (x_0, \ldots, x_{n-1}, -x_n)$ is just a reflection in the last variable.  Anyway, Hatcher computes the degree on p. 134 [here](http://www.math.cornell.edu/~hatcher/AT/AT.pdf).
Comment: Thank you both, I've edited the question: it was just a reflection. I'll try to think of possible triangulations - I've had a look at Hatcher's approach, but he uses simplicial homology theory, which I'm not familiar with...
Answer: If you know a few formal properties of homology, you might argue as follows:
Realize ${\mathbb S}^n$ as ${\mathbb D}^n / \partial{\mathbb D}^n$ with basepoint $\overline{\partial{\mathbb D}^n}$, you have a pinch map ${\mathbb S}^n \to {\mathbb S}^n\vee{\mathbb S^n}$ collapsing $\{x_n = \frac{1}{2}\}$ to a point, and which you can prove to induce the diagonal ${\mathbb Z}\to{\mathbb Z}\oplus{\mathbb Z}$ on $n$-th singular homology. Moreover, for any two pointed maps $f,g: {\mathbb S}^n\to{\mathbb S}^n$, the map $f\vee g: {\mathbb S}^n\vee{\mathbb S}^n\to{\mathbb S}^n$ induces the map $(\text{deg}(f),\text{deg}(g)): {\mathbb Z}\oplus {\mathbb Z}\to {\mathbb Z}$ on $n$-th homology. Putting both together, you get that the map $f+g:{\mathbb S}^n\to{\mathbb S}^n$ defined as the composition $$f+g:={\mathbb S}^n\to{\mathbb S}^n\vee{\mathbb S}^n\xrightarrow{f\vee g}{\mathbb S}^n$$ has degree $\text{deg}(f)+\text{deg}(g)$. Now, taking $f=\text{id}$ and $g$ the map flipping the $n$-th coordinate, you can check that $f+g$ is nullhomotopic, so ...?
Comment: I hoped that one could understand the answer both intuitively and formally without knowing anything about homotopy groups, because the definition of $f+g$ is simple to write down as the composition of the pinch map and $f\vee g$
Comment: What is $f+g$ exactly?
Comment: @MattSamuel: In general, you mean? On $\{x_n \leq \tfrac{1}{2}\}$, it maps $[x_1,...,x_n]$ to $f([x_1,...,x_{n-1},2x_n])$, while on $\{x_n \geq\tfrac{1}{2}\}$ it maps it to $g([x_1,...,x_{n-1},2x_n-1])$.
Comment: I see. You're talking about the composition operation in higher homotopy groups. This is quite a bit beyond singular homology in terms of educational progression, so I think you should probably include an explanation in your answer.
Comment: What was unclear was the notation $f+g$. I didn't see an explicit definition of it. What I see is "putting both together" then $f+g$.
Comment: @MattSamuel: Ah ok, I guess the formatting was unfortunate. I changed that.

Degree of an antipodal map


How to set in Angular 4 cookies, type number values

Question: I'm beginning to develop in angular 4 with typescript. I want to save info in cookies. I'm using "ngx-cookie". Put method, just accept for the value as type string and I want to save a number type var. What the best approach for that?
Explanation found
Javascript - Using cookies to store an integer
Cookies in browsers are strings, that seems the reason
Comment: welcome. Please read [**Asking Help**](http://stackoverflow.com/help/how-to-ask) before asking any question
Answer: In typescript you can use the 'any' type to store values to get around being specific with strong types.
var myInteger: any;
var myString: any;

myInteger = 1 //valid
myString = "helloWorld" //valid

As ngx-cookie put method takes a string you would need to pass a string. I would call JSON.stringify on your object and pass that to the put request.
saveSearchCritereaCookie = new myCookieObject();
var searchCookie: String = JSON.stringify(saveSearchCritereaCookie);

* @param {string} key Id for the `value`.
 * @param {string} value Raw value to be stored.
 * @param {CookieOptions} options (Optional) Options object.
 */

put(key, searchCookie, options?): void;

Please see the ngx-cookie documentation page for more examples: NGX-Cookie


Could anyone clarify this definition?

Question: In Michael Spivak's Calculus to explain limits, he uses such an example:
We're given a function $f(x) = \left\{0, \quad \quad \quad \quad x \,\,\, \text{irrational} \\ \quad\quad\quad\quad\frac{1}{q}, \quad \quad \quad x = \frac{p}{q} \,\,\,\text{in lowest terms},\,\, 0<x<1  \right\}$
And we are told that to prove that for any number $a$ with $0<a<1$ the function approaches a at $a$, we consider any number $\epsilon > 0$ and any natural number $n$ large enough, that $\frac{1}{n}\leq \epsilon$.
And here is the part I don't get:

that $1/n\le\varepsilon$. Notice that the only numbers $x$ for which $|f(x)-0|< \varepsilon$ could be false are: $$\frac{1}{2};\frac{1}{3};\frac{2}{3};\frac{1}{4};\frac{3}{4};\frac{1}{5};\frac{2}{5};\frac{3}{5};\frac{4}{5};\ldots;\frac{1}{n},\ldots,\frac{n-1}{n}.$$ (If $a$ is rational, then $a$ might be one of these numbers.) However many of these numbers there may be, there are, at any rate, only finitely many.

What does he mean by only finitely many?
Can't I just go on $\frac{1}{2}, \frac{1}{2},
\frac{1}{4}, \frac{1}{5}, \frac{1}{500}, \frac{1}{5000000000}, \frac{1}{500000000^{5000000000}}$ and so on?
Also then he says that if the distance between $x$ and $a$ is less than the distance between the difference between the closest rational number betewen $0$ and $1$, and $a$, then $x$ is not one of the rational numbers between $0$ and $1$ or in other words:
Set $A$ contains all rational numbers between $0$ and $1$
From all members of $A$, $\frac{p}{q}$ is closest to $a$
$|\frac{p}{q} - a| = \delta$
if $|x - a| < \delta$, then $x$ does not belong in $A$
I don't get it - why doesn't $x$ belong in $A$?It all seems like random assumptions coming out of nowhere, I'm not sure I'm following.Could someone clarify this here?
Answer: With regards to the first part he is saying that the only numbers for which that function can yield a number that is greater than $\epsilon$ are those whose denominator is $n$ or less, hence the numbers he listed. The number $n$ is fixed at the beginning if that's what's causing confusion. For a specifically chosen $n$ the numbers in the sequence you present eventually become less than $\frac{1}{n}$

Could anyone clarify this definition?


Ways to see if a function $f(z)$ is holomorphic

Question: Despite I'm going to use an example to illustrate what I'm referring to, this pretends to be a general question about the procedure to find where a function is holomorphic.
Suppose we have
$$f(z)=\begin{cases}e^{-1/z^2} \quad z\neq 0\\ 0 \qquad\ \ \ \ z=0\end{cases}$$
We want to see if this function is holomorphic.
As far as I'm concerned, we have 2 ways to, in practise, see it:

If this function has partial derivatives everywhere except on $0$, we can find if C-R equation holds for $f(z)$. Then, everywhere where $f(z)$ satisfies this equations, the function will be holomorphic.
If it's hard (like on this example) to separate $f(z)$ in its real and imaginary part to verify that, we can verify if the function is $C^1(\Omega)$, and then we know that $\partial f/ \partial \bar{z}=0$ iff the function is holomorphic.

Am I correct? Did I leave any case? Is there another (easier) way to see that $f(z)$ is (isn't) holomorphic?
Comment: Are you familiar with the term "essential singularity"?
Comment: No, we haven't did this yet.
Comment: Well once you've covered it, you can come back to this question and show $f$ has an essential singularity at 0. We can prove it's not holomorphic at 0 though, in fact it's not continuous there. It's holomorphic as a function in $\mathbb{R}$ since if $x \to 0$ in $\mathbb{R}$, $-\frac{1}{x^2}$ will go to $- \infty$ so $f(x) \to 0$. Why does this fail in the complex plane?
Answer: Your function is not even continuous at the origin, so of course it can't be holomorphic. A way to show this: try to take $z \to 0$ on the real axis, and then on the imaginary axis. You will get different limits, so the function is not continuous.
Answer: The first thing to check is whether your function is continuous or not. And it isn't: $\lim_{x\to0^+}f(x+xi)\neq0$.
Besides, you should be aware of the fact that a point of the domain of $f$ may well be a solution of the Cauchy-Riemann equations and, even so, $f$ may not be differentiable there.
Comment: So $f(z)$ is holomorphic everywhere except an open interval around $0$ right?
And if I check that the partial derivatives are continuous everywhere and that CR eq. holds for $f(z)$, isn't my function holomorphic?
Comment: First question: no. The function $f$ is holomorphic in $\mathbb{C}\setminus\{0\}$. Second question: yes.
Answer: It's easier to note $e^z$ is holomorphic everywhere, and $-1/z^2$ is holomorphic on $\mathbb C\setminus\{0\}.$ Therefore the composition, $e^{-1/z^2},$ is holomorphic on $\mathbb C\setminus\{0\}.$ What happens at $0?$ There $f$ is not differentiable, or even continuous. To see this, consider $f(z)$ as $z\to 0$ along the imaginary axis.


mogenerator doesn't generate any entities even though datamodel contains entities. Reports "No entities found in model. No files will be generated."

Question: I'm trying to get mogenerator (1.26 latest) to generate some boiler plate classes from a core data model (xcdatamodel) and it reports:
No entities found in model. No files will be generated.
(model description: (<NSManagedObjectModel: 0x10012e410>) isEditable 1, entities {
}, fetch request templates {
})

Even though the contents of the xcdatamodel clearly exist
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model name="" userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="1487" systemVersion="11E53" minimumToolsVersion="Xcode 4.3" macOSVersion="Automatic" iOSVersion="Automatic">
    <entity name="Chair" representedClassName="Chair" syncable="YES">
        <attribute name="name" attributeType="String" maxValueString="50" syncable="YES"/>
    </entity>
...

What am I doing wrong?
I am using Xcode 4.4.1 and mogenerator 1.26
Answer: This is a quote from http://raptureinvenice.com/getting-started-with-mogenerator/

When you create entities in your data model, be sure to populate the
  "Class" field with the same name as the entity.

So what you have to do is:

Open your data model
Select your entity
In the right panel, select the Data Model Inspector (3rd one)
Edit the "Class" field with the same name as the "Name" field
Comment: Nice one this just helped me end about 3 hours of frustration


Will this make sure a point does not lie along a line?

Question: If I have $2$ vector points and I wish to create a 3rd vector point to make a plane from.
I'd like to make sure the 3rd point I generate doesn't happen to have the same slope.
I can add either $1$ to $y$ or one to $x$ to create it but it might by chance be that this new point is one the line made by point $A$ and $B$ and so therefore not really a plane.
I think I can take the slope of $A \to B$  and normalize it.
I should be able to compare that to my slope of $A \to A + X$ which is of course a slope of $X$
and so if the slope of the two lines is equal, I just add the other direction instead.
Does that sound mathematically correct?
Answer: Use the fact that, if $(x, y)$ is a vector,
than $(-y, x)$ is orthogonal to it.
So, if your two points are
$(a, b)$ and $(c, d)$,
then their difference is
$(c-a, d-b)$,
and $(b-d, c-a)$ is orthogonal to
the line between them.
So, let the third point be
$(c+b-d, d+c-a)$
(or $(c+r(b-d), d+r(c-a))$
for a real r).


What does is mean when a composition of two functions is an isomorphism?

Question: Suppose that $T\colon V \to U$ and $S\colon U\to W$ are linear transformations and that $S\circ T:\colon V\to W$ is an isomorphism. What can we say about the functions $T$ and $S$ in terms of surjectivity, injectivity and bijectivity?
Comment: What did you try? Do you have some thoughts on this? You will find that questions showing some effort receive useful comments and answers.
Answer: Let $I = S\circ T$. You know that $I$ is linear and an isomorphism by hypothesis, so $\operatorname{ker}(I)= \{0_V\}$. But $\operatorname{ker}T \subset \operatorname{ker} I$ (try to prove this) $\implies T$ is injective. Note that the image of $T(V)$ has dimension $\operatorname{dim} V = \operatorname{dim} W$ since $I$ is an isomorphism. Also, $S$ restricted to $T(V)$ must be injective (otherwise the dimensions of $V$ and $W$ are different) and thus bijective. So $S$ is surjective (and bijective when restricted to $T(V)$).
Note that those are the only facts we can state about the 3 properties, since $T(x,y) = (x,y,0)$ and $S(x,y,z) = (x,y)$ would be counterexamples to other statements (first is injective but not surjective, second is surjective but not injective and their composition is an automorphism). And we're done.


Error: "Byte code in the repository is invalid. Java transformation is invalid"

Question: I got stuck with this error and in the a Java Transformation that has already compiled. What could be wrong, missing?
My transformation gets a data from a table (String FechaInicial) and generates a table calendar in the output (String CaleId).
Code follows:
Calendar calInici = Calendar.getInstance();
calInici.set(Calendar.YEAR, Integer.parseInt(FechaInicial.substring(0,4)));
calInici.set(Calendar.MONTH, Integer.parseInt(FechaInicial.substring(5,7)));
calInici.set(Calendar.DAY_OF_MONTH, Integer.parseInt(FechaInicial.substring(8,10)));

Calendar calFi = Calendar.getInstance();
calFi.set(Calendar.WEEK_OF_YEAR, 1);
calFi.set(Calendar.DAY_OF_WEEK, 1);
calFi.add(Calendar.MONTH, 1);

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for ( Calendar c = calInici; c.compareTo ( calFi ) <= 0; c.add(Calendar.DAY_OF_WEEK, 1 ) )
{
   CaleId = df.format(c.getTime());
   generateRow();
}

Note (15-Oct):
I have received this but does not make sense in this context because I have reduces my code to:
   CaleId = FechaInicial;
   generateRow();

I have received this reply from a colleague without any result:
Problem Description

Java Transformation fails with error TM_6279: The session instance encountered the following run-time validation error: Byte code in the repository is invalid. Java transformation is invalid.

The issue starts to happen after changing the repository codepage from Latin1 to UTF8. After that, a Java transformation that used to work, failed showing a wrong byte code error message.

By recompiling the code or validating the map, the same error occurs. Also, when reviewing the Java Code transformation involved, the following is showed in the Java Code tab:

--
FieldName = "test^©";
generateRow();
--

The field value showed is wrong and it should not be like that. This field value has special characters used by Portuguese Brazilian Language, but also happens with Japanese, Chinese, or any language that uses special characters.

Cause

This issue occurs due to embedding of string of specific character set in the Java code after converting a single byte to multi byte. PowerCenter store the byte code in the repository and the client machine (Designer client machine) code page is used during compilation of the Java code.

Other transformations would work fine in UTF8 and Latin or Asian Languages. However, Java Transformations wouldn't work fine when using UTF-8.
Solution

This is a known issue and CR 193867 has been raised to be addressed in future releases. However, an EBF is available on top of Informatica 9.0.1 HotFix 2. Contact Informatica Global Customer Support for the EBF.
The fix consists in a DLL enhancement that should be applied at Server and Client side, to allow the Java transformations to work with UTF8 Code Page + special characters.
It is important to recompile all the involved Java Transformation codes, from all the impacted mappings after EBF installation.

Answer: This occurs when compiled java code which is saved to repository does not match with what is being saved back to repository. In order to fix this.
1) Open java transformation --> go to Java Code --> settings --> Add the java class path from your local and re-compile the code.
Make sure you see the message like below
Java code compilation successful.
Remove the class path after code is saved.
Answer: My guess is that it may be caused by incompatible versions of Java installed on the on client machine and the Integration Service server.
http://blogs.hexaware.com/informatica-way/java-transformation/

Informatica PowerCenter client uses JDK to compile Java code and generates byte code. PowerCenter client stores the byte code in the PowerCenter repository. The Integration Service uses JRE to execute the generated byte code at run time.
Comment: I have downgraded to 1.6.0-35 but the same error. I have simplied the code to a assignment from FechaInicial to CaleId and the same error. Is it possible that Java could be not correctly configured in PWC server?
Comment: Well, I guess we cannot rule that out. Do you have access to the Integration Service server?


Do we have $\operatorname{Hom}(G,\mathbb{C}^\times)\cong\operatorname{Hom}(G,\mathbb{T})$ as groups for topological group $G$?

Question: Let $\mathbb{C}^\times$ and $\mathbb{T}$ be the multiplicative topological group whose elements are $\mathbb{C}\setminus\{0\}$ and $\{z\in\mathbb{C}:|z|=1\}$ respectively. For a topological group $G$, let $\operatorname{Hom}(G,\mathbb{C}^\times)$ (respectively $\operatorname{Hom}(G,\mathbb{T})$) be the multiplicative group of continuous groups homomorphisms $G\to\mathbb{C}^\times$ (respectively $G\to\mathbb{T}$).

Are $\operatorname{Hom}(G,\mathbb{C}^\times)$ and $\operatorname{Hom}(G,\mathbb{T})$ isomorphic as groups?

Note that we have $\operatorname{Hom}(G,\mathbb{C}^\times)\cong\operatorname{Hom}(G,\mathbb{T})$ if $\mathbb{C}^\times$, $\mathbb{T}$ and $G$ are merely groups, because $\mathbb{C}^\times$ and $\mathbb{T}$ are isomorphic as groups.
For the case of topological groups, we have $\rho\mapsto\left(\log|\rho|,\dfrac{\rho}{|\rho|}\right):\operatorname{Hom}(G,\mathbb{C}^\times)\to\operatorname{Hom}(G,\mathbb{R})\times\operatorname{Hom}(G,\mathbb{T})$ being an isomorphism, where $\mathbb{R}$ and $\operatorname{Hom}(G,\mathbb{R})$ are additive groups, but it is still possible that $\operatorname{Hom}(G,\mathbb{C}^\times)\cong\operatorname{Hom}(G,\mathbb{T})$ as groups, For example, for $G=\mathbb{R}$, we have $\operatorname{Hom}(\mathbb{R},\mathbb{R})=\{x\mapsto\lambda x:\lambda\in\mathbb{R}\}\cong\mathbb{R}$ (consider the Cauchy equation) and $\operatorname{Hom}(\mathbb{R},\mathbb{T})=\{x\mapsto{\rm e}^{{\rm i}\lambda x}:\lambda\in\mathbb{R}\}\cong\mathbb{R}$, and we know that $\mathbb{R}$ and $\mathbb{R}\times\mathbb{R}$ are isomorphic as additive groups (although not canonically).
Thank you in advance.
Comment: @MarianoSuárez-Álvarez To your first comment: That's why I said "isomorphic as groups", as here the topology is not relevant :)
Comment: @MarianoSuárez-Álvarez if there is a non-trivial homomorphism to $\mathbb{R}$ then there is also a non-trivial map to $\mathbb{T}$ - the composition with complex $x\mapsto exp(rx)$ for some $r$.
Answer: I don't know the answer for an arbitrary topological group, but if the group $G$ is a locally compact abelian group,
it seems that indeed the groups $\operatorname{Hom}(G,\mathbb{C}^*)$ and $\operatorname{Hom}(G,\mathbb{T})$
are isomorphic as abstract groups.
If $G$ is a locally compact abelian group, then $\operatorname{Hom}(G,\mathbb{T})$ is
the Pontryagin dual group and we will denote it by the symbol $\widehat{G}$.
Next, $\operatorname{Hom}(G,\mathbb{C}^*)$ and $\widehat{G}\times\operatorname{Hom}(G,\mathbb{R})$ are isomorphic as topological groups (actually, that's what you noted, too).
If $G$ is a locally compact abelian group, then $\operatorname{Hom}(G,\mathbb{R})$ is
a torsion-free divisible groups.
Let us consider two cases:

Let $\widehat{G}$ contain the nontrivial connected component of $e$.
We denote it $C$. So, $\widehat{G}\cong H\times C$ as abstract groups
(where $H$ is some subgroup of $G$ not necessarily closed)
and if $F=\operatorname{Hom}(G,\mathbb{R})$ then
$$
\operatorname{Hom}(G,\mathbb{C}^*)\cong
\widehat{G}\times\operatorname{Hom}(G,\mathbb{R})\cong
H\times C\times F\cong
H\times C\cong\widehat{G}
$$
as abstract groups.

If $\widehat{G}$ is a totally disconnected group, then the group $G$
has a compact subgroup $H$ such that $G/H$ is a discrete torsion group.
In this case, $\operatorname{Hom}(G,\mathbb{R})=0$ and
$\operatorname{Hom}(G,\mathbb{C}^*)=\widehat{G}$.
Comment: Thanks! That's very interesting :)


C++ having cin read a return character

Question: I was wondering how to use cin so that if the user does not enter in any value and just pushes ENTER that cin will recognize this as valid input.
Comment: "The C++ Programming Language" by Bjarne Stroustrup certainly thinks that cin will return '\n' but I cant get it to work.  I will just try the getline route.
Answer: You will probably want to try std::getline:
#include <iostream>
#include <string>

std::string line;
std::getline( std::cin, line );
if( line.empty() ) ...

Answer: I find that for user input std::getline works very well.
You can use it to read a line and just discard what it reads.
The problem with doing things like this,
// Read a number:
std::cout << "Enter a number:";
std::cin >> my_double;

std::count << "Hit enter to continue:";
std::cin >> throwaway_char;
// Hmmmm, does this work?

is that if the user enters other garbage e.g. "4.5 - about" it is all too easy to get out of sync and to read what the user wrote the last time before printing the prompt that he needs to see the next time.
If you read every complete line with std::getline( std::cin, a_string ) and then parse the returned string (e.g. using an istringstream or other technique) it is much easier to keep the printed prompts in sync with reading from std::cin, even in the face of garbled input.
Answer: Does cin.getline solve your problem?
Answer: To detect the user pressing the Enter Key rather than entering an integer:
char c;
int num;

cin.get(c);               // get a single character
if (c == 10) return 0;    // 10 = ascii linefeed (Enter Key) so exit
else cin.putback(c);      // else put the character back
cin >> num;               // get user input as expected

Alternatively:
char c;
int num;
c = cin.peek();           // read next character without extracting it
if (c == '\n') return 0;  // linefeed (Enter Key) so exit
cin >> num;               // get user input as expected

Answer: Try unbuffering cin (it's buffered by default).

C++ having cin read a return character


Class to simplify background thread creation and UI thread synchronization

Question: What class does Android use to simplify background thread creation and UI thread synchronization?
Comment: To be fair, the Udacity course instructions specifically suggest using StackExchange to find the answer to the question.
Comment: [Udacity course page from which this question is copy-pasted](https://www.udacity.com/course/viewer#!/c-ud853/l-1469948762/e-1530568562/m-1484928604)
Comment: ..which if this question wasn't already on here verbatim I was about to do it- since Udacity does specifically encourage students to use SO.. which I agree with wholeheartedly
Comment: That question is part of an online Udacity Android training class. People asking that question are looking for that exact answer and nothing more.
Comment: @alcfeoh I have got to disagree. Some people are looking for the exact answer, the majority are looking for insights on the AsyncTask class
Answer: AsyncTask is the class you are looking for.
You can find more information about it within the official Android Documentations.
Comment: For this to be a valuable answer, you will need to expand on why AsyncTask is useful in solving OP's problem.
Comment: Well, since we now know the class name can't someone simply go to the Android docs and get that info? Make sure you flame Kshitij as well for not providing an essay on why AsyncTask is useful. You want to be fair right?
Answer: AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.)
Answer:
AsyncTask is the class when you have some simple tasks to run in background. But it is not good is there are too many tasks.
Service is the component that android provided for the developer to use to do background task. And you could use binder or Messenger to communicate with Activity or UI thread.
And you Surly could create new thread from your Activity or Application. It depends on your demand or situation.
Answer: For the answer to the Udacity course question, the class would be AsyncTask
i.e. this class
Comment: Why the need for this answer, when the question already has already had a much better answer since May 2015?
Comment: Identical to alcfeoh's answer.
Answer: to simplify background thread creation and ui thread sync android uses AsyncTask class
Answer: AsyncTask is deprecated. Kotlin concurrency utility classes are the recommended way to handle Threads.


Is Maxima/Minima of Lagrange function same as Maxima/Minima of function under consideration?

Question: Given:
To find critical points of function f(x) subject to constraints:
g(x) = 0
We create a Lagrange function:
L(x, λ) = f(x) - λg(x)
Now, are the critical points and max/min of Lagrange function same as critical points of f(x)?
If yes, why?
Answer: This is a good question that has a lot of depth to the answer, but the essence is no, this is not true in general for even what you're asking, which is a pretty specific case of the KKT theorem. Essentially this answer gets more complicated when dealing with the KKT theorem, which is a more generalized form of Lagrange multipliers. But the method of Lagrange multipliers is only a necessary condition, meaning that not all the points are guaranteed to be optimal. In fact, part of the exercise of working with Lagrange multipliers in problems is checking the solutions from what you get from the Lagrangian and seeing which is the optimal solution. However, in the case you're specifying, we do have that the Lagrangian will find any point that is optimal in our original problem.
Edit: for further reading, page 7 of this lecture may help solidify some of this.
Comment: Thank you. Will surely go through that article.


Questions regarding solvability $Ax=w$ in $\mathbb{Z}/(p-1)\mathbb{Z}$

Question: Dear mathstack exchange,
Currently I`m working on my bachelor thesis. I want to answer the following:

$Ax=w$ is solveable in $\mathbb{Z}/(p-1)\mathbb{Z}$ if and only if
$\mbox{det}(A) \bmod (p-1) \in (\mathbb{Z}/(p-1)\mathbb{Z})^{\times}$

(already answered thanks to aRaRa)

How to deal with zero divisors in $\mathbb{Z}/(p-1)\mathbb{Z}$ for $Ax=w$

I hope you can help me!
Answer: But "if and only if" is wrong.
Let $p=13$, so $q:=p-1=12$.
Look at the following linear equation in $\mathbb{Z}/q\mathbb{Z}$:
$$\pmatrix{5 & 5\\11 & 1}\, x=\pmatrix{1\\11}\,, $$
it has the solution
$$w=\pmatrix{3\\2} \, ,$$
but
$$\det \pmatrix{5 & 5\\11 & 1} = 10\not\in (\mathbb{Z}/q\mathbb{Z})^\times=\{1,5,7,11\} \, .$$
The "if" part (see here):
\begin{align}
A\, x & = w\\
\mathrm{adj}(A) A \, x &= \mathrm{adj}(A) \,w \\
\det(A)\cdot E\, x &= \mathrm{adj}(A) \, w\\
x &= \det(A)^{-1}\mathrm{adj}(A) \, w\, .
\end{align}
$E$ is simply the identity matrix here. I could divide the equation by $\det(A)$ because we stipulated that $\det(A)$ is in the unit group of the ring.
Answer: Regarding how to deal with zero divisors:
Do all the steps as in my first answer till you get to this:
$$\det(A)\cdot E\, x = \mathrm{adj}(A) \, w$$
Now since you can't simply divide by $\det(A)$, what can we do?
This equation is just a system of many simple equations with one variable ($N=\dim(A)$):
\begin{align}
\mathrm{1.} \quad \det(A) \, x_1 & \equiv \bigl(\mathrm{adj}(A)\, w\bigr)_1 \bmod{(p-1)} \\
\mathrm{2.} \quad \det(A) \, x_2 & \equiv \bigl(\mathrm{adj}(A)\, w\bigr)_2 \bmod{(p-1)} \\
&\vdots \\
\mathrm{N.} \quad \det(A) \, x_N & \equiv \bigl(\mathrm{adj}(A)\, w\bigr)_N \bmod{(p-1)} \\
\end{align}
How can we solve them?
You can use the following theorem:

The equation $$  a x \equiv b \bmod{n} \; \quad a, b \in \mathbb{Z}\, , n \in \mathbb{N}
$$ with $d:= \gcd(a,n)$ has no solution if $d \nmid b$. But if $d \mid b$, it is equivalent to $$
  x \equiv y \frac{b}{d} \bmod{\frac{n}{d}}
$$ with $y\in \mathbb{Z}$ chosen so, that $y a + z n = d$ for a $z \in \mathbb{Z}$.

You get $y$ (and $z$) by the extended Euclidean algorithm.
Just solve them one after another with this theorem and you're done!
Of course the equation doesn't need to have a solution, which happens if there is a $k \in \{1, \ldots, N\}$ for which the greatest common divisor of $\det(A)$ and $p-1$ doesn't divide $\bigl(\mathrm{adj}(A)\, w\bigr)_k$.
Comment: Getting that $\det A$ to appear there may introduce extra solutions (IOW your system is not always equivalent to the original one). To drive this point home consider the toy case of $p=5$, $$A=\pmatrix{1&0&0\cr0&2&0\cr0&0&2\cr}.$$ We have that $\det A=4\equiv0\pmod{p-1}$. But modulo $4$ the first variable is uniquely determined and the other two have two possibilities (or none).
Comment: I love you! Great comment!
Comment: Or in other words, multiplying both sides by $\mathrm{adj} A$ does not result in an equivalent system.
Comment: I think that going via Smith normal form (first on the integer side to make sure it exists) should work. Thinking it through :-)
Comment: Yeah. It does pan out. I decided to reuse the example from your 1st answer (+1 was there). Another solution also came out. Together with the conclusion that the pair of congruences has exactly two solutions.
Answer: This is only about the additional case, when we don't know that $\det A$ is invertible modulo $p-1$. I am addressing the problem in aRaRa's second answer, where multiplying the system by $\mathrm{adj}\, A$ occasionally introduces unwanted solutions. Possibly many of them.
We can think of $A$ as having integer entries (for a little while - bear with me). I intend to use the so called Smith normal form. It says that there exists square matrices
with integer entries $P$ and $Q$ such that
$$
A=PDQ,
$$
where

$D$ is a diagonal matrix with entries $d_1,d_2,\ldots$ such that $d_i\mid d_{i+1}$ for all applicable $i$, and
the matrices $P$ and $Q$ are unimodular, i.e. they have inverses with integer entries as well (in other words their determinants are $\pm1$).

The system $Ax=w$ is thus equivalent to the system $PDQx=w$. Because of unimodularity $P^{-1}$ and $Q^{-1}$ also make sense over the ring $\Bbb{Z}_n, n=p-1$. Therefore the original system is equivalent to the system of congruences
$$
DQx\equiv P^{-1}w\pmod n.\qquad(*)
$$
How can we all the solutions of the system of linear congruences $(*)$? We need to introduce a helper set of new variable $y$ defined by $y=Qx$. Because $Q$ is unimodular as well the correspondence $y=Qx$ is bijective (Sorry about playing Capt'n Bbvious here - $Q$ is invertible modulo $n$). So if we can find all the vectors $y$, we can find all the solution vectors $x$ as well.
But the remaining system
$$
Dy=P^{-1}w
$$
has a diagonal matrix of coefficients! There we can find all the solutions of all the components $y$ with the method in aRaRa's 2nd answer. It is possible that there are none, but them's the breaks.

As an example consider the congruence from aRaRa's 1st answer
$$
\left(\begin{array}{rr}5&5\\-1&1\end{array}\right)
\left(\begin{array}{r}x_1\\x_2\end{array}\right)\equiv\left(\begin{array}{r}1\\11\end{array}\right)\pmod{12}.
$$
Here
$$
A=\left(\begin{array}{rr}5&5\\-1&1\end{array}\right)
=P\left(\begin{array}{rr}1&0\\0&10\end{array}\right)Q
$$
with the unimodular matrices
$$
P=\left(\begin{array}{rr}5&1\\1&0\end{array}\right),\qquad
Q=\left(\begin{array}{rr}-1&1\\1&0\end{array}\right).
$$
Let's write
$$
\left(\begin{array}{r}y_1\\y_2\end{array}\right)=
Q\left(\begin{array}{r}x_1\\x_2\end{array}\right)=\left(\begin{array}{c}x_2-x_1\\x_1\end{array}\right).
$$
We have
$$
P^{-1}\left(\begin{array}{r}1\\11\end{array}\right)\equiv\left(\begin{array}{r}11\\6\end{array}\right)\pmod{12},
$$
so we want to solve the pair of congruences
$$
\left\{\begin{array}{rcr}y_1&\equiv& 11\\10y_2&\equiv& 6\end{array}\right.$$
both modulo $12$. Clearly we must have $y_1\equiv 11\equiv-1$, but for $y_2$ we get two possibilities $y_2\equiv3$ and $y_2\equiv -3\equiv9$. Given that $x_1\equiv y_2$ and $x_2\equiv y_1+y_2$ this leads to the two solutions $(x_1,x_2)\equiv(3,2)$ and $(x_1,x_2)\equiv(9,8)$.
Comment: Note that we don't need to get to the proper Smith normal form. Namely we did not need the divisibility property $d_\mid d_{i+1}$ of the diagonal entries. As long as $D$ is diagonal and $P$ and $Q$ are unimodular, the logic of the method checks out.


Android app crashes after SDK-tools update version (NoClassDefFound, tool version 22)

Question: I have just updated my android SDK tools to the newly released version (tools version 22, platform tools version 17)
java.lang.NoClassDefFoundError

The .classpath file was modified. The update in added a line :
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>

Before the SDK tools update, all my projects worked well !!
I corrected my problem in this way :

In the project properties (eclipse) -> java build path -> order and export make sure that all your jars in the libs folder are checked.
And "Android Tools -> Fix Project Properties"
And "Project -> Clean"

But I don't understand why! Would anybody have an explanation ?
Comment: answer your own question with the solution, you helped me fixing the annoying problem
Comment: I'm having the exact same issue, exact same error. I've tried what @lopez.mikhael suggested and it didn't resolve my problem.

I asked my question on the androiddev subreddit....http://redd.it/1egrgr
Comment: are you using any support library
Comment: Samle problem!! Even my files are generated by AndroidAnnotations. It seems like they are not added to the build path.
Comment: Do not forget to do a "Android Tools -> Fix Project Properties" then "Project -> Clean".
Comment: @lopez.mikhael didnt fix the issue. What did you check in the Oder and Export tab?
Comment: +1. It works for me. I have tried many other solutions this morning.
Answer: I fixed it by going into Java Build Path > Order and Export tab.
Click everything in the list "Android Private Libraries".
Then "Project -> Clean". That fixed my issue.
Just over 1.5 days on this issue, solved my problem by reading Google+.
Comment: I've just checked it carefully and we only need to check the new dependency "Android Private Libraries" (not all) and then do the "Project > Clean". Thanks @acedanger.
Comment: Awesome! Was struggling with this for a while... Why android, why?
Comment: You're welcome:-) ("Fix Project Properties" isn't needed either!)
Answer: Had the same issue as StylezSoft. To clarify even further, below is my Java Build Path from Eclipse after that I solved the issue (by ticking the android-support-v4.jar library)

Then I cleaned the Project (Project > Clean... > OK) and everything worked fine.
Answer: I had a similar issue after the upgrade. The problem in my case was that the android-support-v4.jar library had become unchecked in the Order and Export- list. Check + rebuild solved it for me.
The error manifested itself by crashing the app when opening a dialog with a Facebook LoginButton widget on it.
Answer: I had similar issue, following two steps fixed it:-

Java Build Path -> Order and Export tab.
Then "Project -> Clean".
Answer: Also need to make sure the Android Dependencies is checked in the Order & Export tab. Both are needed when using other library projects.
Answer: I solve this with Android Tools->Add support Library
Answer: I had similar issue. But the problem was jar mismatch of "android-support-v4.jar" between Facebook SDK and my application. When I copied the same jar file from Facebook SDK to my application lib folder, the issue was resolved.
Answer: I ran into this on Android Studio. Since most of the answers here are for Eclipse, here's how to add the supportv4 library on Android Studio:

Build -> Edit Libraries and Dependencies
Click the + button
Select the support-v4 library
Click OK.

That's it.
Answer: Solutions:

Check Exports Order
Enable Multi Dex
Check api level of views in layout. I faced same problem with searchView. I have check api level while adding searchview but added implements SearchView.OnQueryTextListener to class file.
Check support Libraries v4,v7 etc
Comment: This is the mvp answer, multi dex fixed it for us


Null model in likelihood ratio test

Question: I are analyzing time to event using a Cox model. There is a continuous variable C, and I are conducting a likelihood ratio test comparing the following two models to see if the variable C should be added.
model_a ~ A + B
model_b ~ A + B + C
anova(model_a, model_b, test = "LRT")
In this case, can we call model_a a null model, or is the null model an intercept-only model. There is no intercept-only model in Cox model, so there is no null model?
Comment: Whether "variable C should be added" to your model shouldn't just be based on this type of statistical significance test. See Frank Harrell's [online notes](https://hbiostat.org/rmsc/multivar.html). Particularly with Cox models it's a good idea to include all predictors that are expected to be associated with outcome, based on your understanding of the subject matter, provided that you aren't overfitting the data. That's even if some predictors don't pass a test of statistical significance in your particular data sample.
Comment: Thank you for your comment.
Answer: A standard likelihood ratio test compares two nested models, i.e., one model is more complex than the other, and the simpler model is actually a submodel of the more complex model (e.g., by having one or more parameters equal to zero). In such a test the null hypothesis (null model) is always the simpler one of the two models. If the test rejects, the likelihood of the more complex model looks so much better than that of the simpler model that this would be very unlikely to happen if the simpler model actually were true.
In your case the simpler model and therefore the null model is indeed model_a.
Comment: Thank you for your comment, I understand that model_a will be the null model in this case. Your other comments were also helpful.

Null model in likelihood ratio test


Drupal 8 Accessing Menu Tree in a Block's JS

Question: How can I pass the menu into a block's javascript?
I am trying to build a block for a custom mobile menu (client wants specific logic/animations/etc) and use that in Structure > Block layout > Main Navigation.
They want me to do it via jQuery for reasons, but I cannot find how to get access to the menu tree in the javascript of the block. I feel like this should be simple enough with the API but the documentation seems to be all focused on PHP.
Any help is appreciated, thanks!
NOTE
I did find this post but I'm honestly not sure what it is trying to do, it is from about 4 years ago, and making/bundling libraries to just access the menu seems like it is probably not the ideal way to do this. Also I am using Bootstrap's theme and I do not see a template.php.
Thanks again!
Answer: The documentation is inevitably focused on PHP, since Drupal is written in PHP and server-side renders.  And the answer to getting info from PHP/server side to JS/client side is not really Drupal specific.  Like any other situation of this ilk in web development, you have two basic choices.  Either annotate your HTML with enough elements, IDs and classes that you can pull the necessary info out of the DOM, or expose an endpoint containing the info in a convenient-for-JS-consumption format like JSON for your javascript to fetch.
As for the latter, if you don't feel like rolling your own endpoint, there seem to be one, two three and maybe more modules, although I cannot vouch for any of them.


How are optional stopping rules based on e.g. sample confidence (width of confidence interval) biased?

Question: Inspired by this: http://pss.sagepub.com/content/22/11/1359
In the context of open-ended data collection where the necessary sample size cannot be properly estimated, for the purpose of a frequentists test;
I understand that a stopping condition based on the main outcome is circular. For example, if I stop sampling once my p value happens to be below .05, my p value is biased (so much as to be mostly worthless). However, say I choose another stopping rule, such as the width of my 95% confidence interval (without regard for other aspects of the test, such as e.g. if the CI includes 0), am I introducing any bias (but for, of course, CI width and related statistics)?
As far as I understand it, this is not a problem in a Bayesian analysis, but I am wondering about the options for conditional stopping precluding frequentist tests.
Comment: I have seen this approach (aim for a given CI width, assessing it as you go) recommended by various authors (sorry no reference at hand). It seems related to the [accuracy in parameter estimation](http://stats.stackexchange.com/questions/16985/how-to-report-general-precision-in-estimating-correlations-within-a-context-of-j#30287) approach.
Comment: Thank you for the link to AIPE @GaëlLaurans and if you happen to remember any of these "various authors", I'd love to look them up!
Comment: This is certainly an interesting question, which I do not have an answer at the moment.  But I did find this blog entry worthy of a read, even though it concerns the width bayesian credible intervals, rather than frequentist confidence intervals: http://doingbayesiandataanalysis.blogspot.com/2013/11/optional-stopping-in-data-collection-p.html
Answer: Jan Vanhove presented simulations showing that optional stopping based on the width of a confidence interval does not introduce biases. He simulated a situation where the null hypothesis was true, and simulated thousands of experiments that continued adding n until the confidence interval was narrower than a prespecified limit. Since the null hypothesis is known to be true, the p-values ought to be evenly spaced between 0 and 1, and this is exactly what he saw (figure below). Optional stopping did not bias the p-value.

In those simulations, each p-value at each sample size was computed as if the study was planned to use the sample size at that point. Kruschke points out the problem that each calculated p-value, in this case, depends on assumptions that aren't correct when the data are reanalyzed repeatedly as new data are added. But the simulations seem to show this method works fine. I am not sure how to tackle this discrepancy.


deck of cards probability question conditional

Question: Consider a deck of 52 playing cards. We draw 2 cards without replacement and let A be the event that the first card is ace and B be the event that both cards are an ace. Find B given A.
Why is the probablility of B given A not 3/51? This should be the probability of the second card you draw being an ace given the first one is an ace. I thought these probabilities would be equal but they are not the answer is 1/51.
Thanks for your help
Comment: I agree with the answer $\frac 3{51}$.
Comment: I think it is $3/51$, since you are drawing without replacement. Once the first ace is taken out of the deck, there are $3$ aces remaining out of a total of $51$ cards.
Comment: ii meant 3/51, is it 3/52?
Comment: @CarlosBacca In that case could you please edit your question so that it reads "$3/51$" rather than "$3/51$"?
Comment: Yes, $\frac 3{51}$ is correct.
Answer: It should be $\frac{3}{51}$.
$$P(B|A) = \frac{P(A\cap B)}{P(A)}= \frac{\frac{4}{52}\cdot \frac{3}{51}}{\frac{4}{52}}$$
Answer: Here Bayes formula gives better explanation in my opinion.
$$P(B/A)=\frac{P(A/B)P(B)}{P(A)}=\frac{1\cdot \frac{\binom{4}{2}\cdot \binom{48}{0}}{\binom{52}{2}}}{\frac{\binom{4}{1}\cdot \binom{48}{0}}{\binom{52}{1}}}$$
Is this right? If this is not ok I will delete it.


Combining two Active Directories when one directory uses a subdomain of the other

Question: I'm combining two active directory forests for consolidation purposes. The first step is by creating a forest trust between subdomain2.subdomain1.rootdomain.com and subdomain1.rootdomain.com.
A colleague is telling me this is tricky or impossible because of poor planning. subdomain1 will think/assume subdomain2.subdomain1 should already belong to it.
Is this the mountain I'm being told it is or is it a molehill?
Comment: It isn't clear to me what you're trying to accomplish. If subdomain2 is a child domain of subdomain1 then there already exists a Parent-Child trust between them. Can you explain in more detail what you're trying to do?
Comment: I believe it's not technically a child subdomain. I believe it's a seperate fqn for that domain. They were setup independently and unaware of the others existance.

I am try to absorb all the resources/users from subdomain2.subdomain1.rootdomain.com and manage them with admins from subdomain1.rootdomain.com
Comment: I'm confused. subdomain2 is either in the same Forest as subdomain1 and is a child domain of subdomain1 or it isn't. Can you tell us exactly what you're dealing with? Are subdomain1 and subdomain2 in the same Forest?
Comment: Excuse my ignonorance. They are two separate forests.
Comment: OK. I was coming to that conclusion after reading your comments. Can you explain exactly what it is you're trying to do? You can't combine two AD Forests so what is it you're trying to accomplish? Are you trying to create a Forest Trust between the two?
Comment: yes a bidirectional forest trust.
Comment: Just make sure DNS is configured properly, shouldn't be an issue.
Answer: A dns sub domain doesn't automatically mean trust. Should work.
Comment: Thankyou, I was aware that subdomain doesn't imply trust. But I'm told since it is technically external but with a domain that is a subdomain name of the first that there will be a giant issue.
Comment: OK, so it's sounds like you're talking about two different Forests and there are identically named domains in each forest. In that case then you're likely to have issues with Name Suffix routing across the Forest Trust (if you create a Forest Trust).