NullReferenceException was unhandled in event triggering

Question: Here is the problem:
I'm trying to trigger an event in a curtain method of a class.
For instance I got a class named clMage that inherits from clUnits and it got public method attMagicMissle(clUnit aU).
Well here is the code for the clUnits declaration:
    public class clUnits
    {
        public int iHitPoints { get; set; }
        public int iDamage { get; set; }
        public ArmorType unitArmor { get; set; }
    }

And here is the clMage with it's troublesome method:
    public class clMage : clUnits
    {
        public event evtDamageDone damageDealtToSoldier;
        public event evtDamageDone damageDealtToArcher;
        public event evtDamageDone damageDealtToMage;

        public clUnits currentTarget { get; set; }

        public AttackType mageAttack { get; set; }
        public clMage(int iHP, int iDamage, AttackType atType, ArmorType arType)
        {
            this.iHitPoints = iHP;
            this.iDamage = iDamage;
            this.mageAttack = atType;
            this.unitArmor = arType;
        }

        public int attMagicMissle(clUnits aU)
        {
            int iDamageDeals = 0;
            currentTarget = aU;

            switch (currentTarget.unitArmor)
            {
                case ArmorType.None:
                    {
                        iDamageDeals = iDamage * 2;
                    }

          break;
            case ArmorType.Heavy:
                {
                    iDamageDeals = Convert.ToInt32(iDamage * 1.5);
                    this.damageDealtToSoldier(currentTarget); // Here is the NullReferenceExeption problem starts
                }
                break;
            case ArmorType.Medium:
                {
                    iDamageDeals = Convert.ToInt32(iDamage * 0.5);
                    this.damageDealtToArcher(currentTarget);
                } break;
            case ArmorType.Light:
                {
                    iDamageDeals = iDamage;
                    this.damageDealtToMage(currentTarget);
                } break;
        }

        return iDamageDeals;
    }
}

And here goes the Main():
    public delegate int Attack(clUnits aUnit);
    public delegate void evtDamageDone(object aUnit);
    public enum AttackType { None, Melee, Range, Mage }
    public enum ArmorType { None, Heavy, Medium, Light}
    class Program
    {
        static void Main(string[] args)
        {
            Attack Strikes;
            clWarrior theSoldier = new clWarrior(750, 75, AttackType.Melee, ArmorType.Heavy);
            clArcher theArcher = new clArcher(500, 100, AttackType.Range, ArmorType.Medium);
            clMage theMage = new clMage(250, 150, AttackType.Mage, ArmorType.Light);

            // Mage actions
            Console.WriteLine("The mage: ");
            Strikes = theMage.attMagicMissle;
            Console.WriteLine("Attack hase damage = {0} attacks the soldier for {1} damage!", theMage.iDamage, Strikes(theSoldier));
            Console.WriteLine("Attack hase damage = {0} attacks the archer for {1} damage!", theMage.iDamage, Strikes(theArcher));
            Console.WriteLine("Attack hase damage = {0} attacks the mage for {1} damage!", theMage.iDamage, Strikes(theMage));

            // Archer actions
            Console.WriteLine("The archer: ");
            Strikes = theArcher.attArrowShot;
            Console.WriteLine("Attack hase damage = {0} attacks the soldier for {1} damage!", theArcher.iDamage, Strikes(theSoldier));
            Console.WriteLine("Attack hase damage = {0} attacks the archer for {1} damage!", theArcher.iDamage, Strikes(theArcher));

            Console.WriteLine("Attack hase damage = {0} attacks the mage for {1} damage!", theArcher.iDamage, Strikes(theMage));

            // Soldier actions
            Console.WriteLine("The soldier: ");
            Strikes = theSoldier.attSwordSlash;
            Console.WriteLine("Attack hase damage = {0} attacks the soldier for {1} damage!", theSoldier.iDamage, Strikes(theSoldier));
            Console.WriteLine("Attack hase damage = {0} attacks the archer for {1} damage!", theSoldier.iDamage, Strikes(theArcher));
            Console.WriteLine("Attack hase damage = {0} attacks the mage for {1} damage!", theSoldier.iDamage, Strikes(theMage));
        }
    }

Well yeah...
I'm sitting with it for quite some time already(9 hours) surfing the web and stackoverflow mainly, but I just can't get why on the commented line for the clMage it gives me that error and therefore can't understand how to fix it!
Comment: Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints.
Comment: Suggestion: you don't have to prefix all your classes with `cl`. There's nothing so special about classes that they need a special prefix. It just makes your code a lot less readable.
Comment: Thx for link reading...
Comment: John Saunders, thank you for the link that explained in such a detail NullReferenceException.
Answer: If no one subscribed to it, then damageDealtToSoldier is null, so invoking it causes a NullReferenceException. You need to check whether it's null:
if (this.damageDealtToSoldier != null)
    this.damageDealtToSoldier(currentTarget);

Typically, people create a method like this to raise the event:
protected virtual void OnDamageDealtToSoldier(object aUnit)
{
    var handler = this.damageDealtToSoldier;
    if (handler != null)
        handler(aUnit);
}

Comment: At some I've point lost the importance of the listening thing for event, - the source I used to learn the events didn't point it out that if a "listener" doesn't exist then the handler is going to return null. In addition to this another thing that I think must be pointed out is that: a listener must be declared before the lines that are triggering the event otherwise the handlers are to return null. Hope this topic I rised is going to be helpful to other lost in the "labyrinths of events". And big thanks to Thomas Levesque for giving me the leading point for solving my problem.


Differentiate $y=\frac{e^{\sinh ax}}{\sinh bx-\cosh bx}$

Question:
Differentiate $$y=\frac{e^{\sinh ax}}{\sinh bx-\cosh bx}$$

I tried the quotient rule and got this :
$$y'=\frac{a\cosh ax(\sinh bx - \cosh bx)e^{\sinh ax}-e^{\sinh ax}(b\cosh bx + sinh bx)}{\sinh bx - \cosh bx}$$
I don't find a way to simplify this into the answer given in the book :
$$e^{\sinh ax}e^{bx(acosh ax + b)}$$
Where am I doing wrong ?
Comment: Are you sure that that's  the answer given in your book?
Comment: @H G Sur yes that's certainly a mistake. It looks like the author wanted to type $e^{\sinh ax}e^{bx}(a\cosh ax + b)$ as per my answer instead.
Comment: @ZainPatel Let me check.
Comment: Just made sure, that was the answer given in the book.  You can find it here on question 2.2.8(e) : https://archive.org/stream/ProblemsInCalculusOfOneVariableI.A.Maron/Problems%20in%20Calculus%20of%20One%20Variable%20-%20I.%20A.%20Maron#page/n427/mode/2up
Comment: @ZainPatel Thanks.
Answer: Note that $\displaystyle \sinh bx - \cosh bx = \frac{e^{bx} - e^{-bx}}{2} - \frac{e^{bx} + e^{-bx}}{2} = -e^{-bx}$.
Now: $$\frac{d}{dx}{e^{bx + \sinh ax}} = (b +a\cosh ax)e^{bx+\sinh ax}.$$
So your derivative is simply $-(b+a\cosh ax)e^{bx+\sinh ax}$. The 'form' you're looking for seems to be incorrect.
Answer: By applying the quotient rule:
$$
\begin{aligned}
\frac{d}{dx}\left(\frac{e^{\sinh \left(ax\right)}}{\sinh \left(bx\right)-\cosh \left(bx\right)}\right)
& =\frac{\frac{d}{dx}\left(e^{\sinh \left(ax\right)}\right)\left(\sinh \left(bx\right)-\cosh \left(bx\right)\right)-\frac{d}{dx}\left(\sinh \left(bx\right)-\cosh \left(bx\right)\right)e^{\sinh \left(ax\right)}}{\left(\sinh \left(bx\right)-\cosh \left(bx\right)\right)^2}
\\ & = \color{red}{\frac{e^{\sinh \left(ax\right)}\left(b+a\cosh \left(ax\right)\right)}{\sinh \left(bx\right)-\cosh \left(bx\right)}}
\end{aligned}$$
NOTE:
$$\frac{e^{\sinh \left(ax\right)}\left(b+a\cosh \left(ax\right)\right)}{\sinh \left(bx\right)-\cosh \left(bx\right)} \color{red}{\ne} \:e^{\sinh \left(ax\right)}e^{bx\left(acosh(ax)+b\right)}$$
Comment: Thank you. I got this answer too but how to simplify it to the form I mentioned in the question ?
Comment: @HGSur i updated my answer
Answer: Remember that
$$
\sinh x = \frac{e^x - e^{-x}}{2},\quad \cosh x = \frac{e^x + e^{-x}}{2}.
$$
Then
$$
\sinh bx -\cosh bx =-e^{-bx}.
$$
Then from your result(correcting typos):
\begin{align}
y'&=\frac{a\cosh ax(\sinh bx - \cosh bx)e^{\sinh ax}-e^{\sinh ax}(b\cosh bx -b\sinh bx)}{(\sinh bx - \cosh bx)^2}\\
&=(a\cosh ax \cdot (-e^{-bx})e^{\sinh ax} - be^{\sinh ax}\cdot (e^{-bx}))(e^{2bx})\\
&=e^{\sinh ax}\left(-a\cdot \cosh ax\cdot e^{bx} -be^{bx}\right)\\
&=e^{\sinh ax}e^{bx}\left(-a\cdot \cosh ax -b\right)\\
&=-e^{\sinh ax}e^{bx}(a\cosh ax+b),
\end{align}
which is different from the "answer".


Universal app using way less memory on iPad vs iPhone

Question: I have written a universal app that's working fine on both iPhone (iPod Touch) and the iPad. The only difference for either platform are the nib files and the launch page graphics. Both iPad and iPhone nib files have the same functionality, just the graphics, buttons and text are bigger on the iPad.
When I run Instruments on both apps to check for memory leaks I was surprised to see that the iPad was using way less memory compared to the iPhone. And I'm trying to figure out why that's the case...? If anything, it should be the other way around, with bigger image files used for the iPad.
I'm comparing the Live Bytes figure for All Allocations in the Object Summary in Instruments.
iPad reports max around 600 KB
iPhone reports max around 3.6 MB
In both cases I'm using the real devices, not the simulator.
The higher iPhone figure is fine, doesn't cause problems, but I'm just wondering why the iPad is reporting such low figures...?
Comment: You're not using the camera, are you?
Comment: No, not using the camera. Actually, I just wrote iPhone as shorthand for the actual iPod Touch hardware that I'm using, which has no camera.
Answer: Your first step is probably going to be to determine what objects exactly are taking up so much memory when running on your iPod Touch, and then to compare that to the objects present when running on your iPad.
Instruments, thankfully, makes this very easy. Use the Allocations template and you'll see a list of all the different types of allocations. From there you can click and do some data mining. If you want to learn more about Instruments, I recommend checking out the WWDC2010 videos, available for free if you're a member of the iPhone Developer Program.


set sleep time in iphone app

Question: Can anyone suggest me how to set sleep time in iphone application? so that after that time iphone goes in sleep mode.
Thanks in advance.
Answer: I don't think you can do this in the current OS without getting into private API's (which will get your app rejected).
You might be able to turn off auto-lock and fake your own "unlock" swipe screen though
<code>// turn off auto-lock
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
</code>
and then create a XIB to fake an unlock screen.  Not sure how apple feels about you doing that though, I'm just speculating.

set sleep time in iphone app


Is there any way to get broadcast status for an Icecast stream?

Question: I am using Icecast 2 for live streaming and broadcasting.
I want that when broadcasting is off instead of player show something else like next broadcast time and when broadcast is on then show player for streaming.
Answer: If you are using Icecast 2.4.2 you can use the status-json.xsl, to check if any stream is currently up on the server.
<code><?php

/* Checks if any stream is running on the Icecast server at the
 * specified URL.
 * Returns TRUE if running, FALSE if not.
 *
 * It uses the status-json.xsl which is available since Icecast 2.4,
 * although it was sometimes invalid before Icecast 2.4.1
 * If connecting to the Icecast server fails, GETing the JSON fails or
 * JSON decoding fails, this function will report FALSE.
 */
function is_stream_running($icecast_host, $icecast_port) {
  $status_url = "http://{$icecast_host}:{$icecast_port}/status-json.xsl";
  $status_dat = @file_get_contents($status_url);
  if ($status_dat === FALSE) {
    return FALSE;
  }
  $status_arr = json_decode($status_dat, true);
  if ($status_arr === NULL || !isset($status_arr["icestats"])) {
    return FALSE;
  }
  return ($status_arr["icestats"]["source"]) ? true : false;
}

var_dump(is_stream_running("localhost", 8000));

?>
</code>


Parts of a biconditional

Question: When you have an implication $P\implies Q$, $P$ is called antecedent and $Q$ consequent, if I have a biconditional $P\iff Q$, how is called $P$ and $Q$ there?
Comment: I just call them the left side and right side of the biconditional.
Comment: See [Logical biconditional](https://en.wikipedia.org/wiki/Logical_biconditional)
Answer: First see my post on the distinction between logical and material equivalence.
There are no similarly specific terms; usually, P is said to be equivalent, or rarely, materially equivalent, to Q.
'Q is necessary and sufficient for P' is not incorrect, however, it is laden with extra-logical interpretation, so I do not prefer it in purely logical context.

Parts of a biconditional


Quick filter tabs on top of content listing page

Question: I've downloaded and installed the Content Management Filter, but I think that the interface is a bit ugly still with all the drop downs, and it doesn't actually achieve what I had hoped.
Basically, I'm looking for a way to put a row of tabs at the top of admin/content/node so that a managing user can easily select to display just one type of node (or all nodes).
Is there a module for this?
If not, what's the best strategy? How do I tie in with the filtering already in place on this page?
Answer: View Bulk Operations (VBO) is a module that, through Views, allows you to create a page similar to the page visible in /admin/content/node. As the module allows to replace the content of that page with the content of a view, you can filter the list of the nodes following all the criteria that Views allows you to set.
The features of the module are not just those; the module allows you to select all the nodes listed in the view, and apply to them the action that is selected under "Update." The module is very useful for administrators, and it allows also to change the page that lists all the user registered in a Drupal site with a view with similar functionalities.
Answer: I would just use Views to override it to get the fields I need as exposed filters that are required.
Comment: I get the filterable list of nodes, but lose the management options from the original admin page... @kiamlaluno's answer helps a long way to fixing that


Is every positive definite matrix also positive semidefinite?

Question: I am in trouble with the definitions of positive definite and positive  semidefinite matrices. By definition, does the following implication hold?
$$\mbox{positive definite} \implies \mbox{positive semidefinite}$$
I guess yes. Look at the following example. Let
$$A = \begin{vmatrix}
4 &-2& 0\\
-2& 4& -2\\
0&-2&4
\end{vmatrix}$$
It is a diagonally dominant matrix $(|a_{ii}|\geq \sum_{j\neq i}|a_{ij}|$ for all $i$), so it is semidefinite positive. But, if I compute the eigenvalues, they are all strictly positive which implies actually that it is definite positive.
My question is: everytime I find that a matrix is semidefinite positive, thus I have to use another criterion in order to try to understand if it is "less" that semidefinite positive (i.e. definite positive)? Or am I wrong with something?
Thank you in advance!
Comment: @J.W.Tanner If positive definite implies positive semidefinite, I think that it should be the contrary.
Comment: like every positive number is non-negative
Comment: I would say it's "more" than semidefinite positive (the set of semidefinite positive matrices is strictly contained in the set of definite positive matrices)
Comment: Yes, every positive definite matrix is also positive semidefinite.
Comment: Thank you. So, everytime I find that a matrix is semidefinite positive, thus I have to use another criterion in order to try to understand if it is "less" that semidefinite positive (i.e. definite positive)?
Answer: Positive definite means "All eigenvalues are greater than zero."
Positive semi-definite means "All eigenvalues are greater than or equal to zero."
The first of these implies the second.
The second does not imply the first, as the all-zero matrix shows.
Comment: Clear, thank you. So, everytime I find that a matrix is semidefinite positive, thus I have to use another criterion in order to try to understand if it is "less" that semidefinite positive (i.e. definite positive)?
Comment: Actually, it's **more** than semi-definite -- it's all the way to **definite**. But yes, if you know only that a matrix is positive semi-definite, you need to do MORE to show that it's positive definite. (AFter all, sometimes it's NOT actually positive definite, e.g., my example of the zero-matrix.


Unable to move UIWebView to a specified section in iOS11 (iPad)

Question: We have used the below lines of code to move to the web view:
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.location.hash=\'#-1\';"]];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.location.hash=\'#%@\';", index]];

but somehow this code doesn't work only in iPad. Here is how I initialised the web view:
webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[webView setDelegate:self];
[webView.scrollView setDelegate:self];
[webView setBackgroundColor:WHITECOLOR];
[webView setScalesPageToFit:YES];
[webView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview: webView];

Could someone please guide me how to debug it.
Comment: In iOS11 `location.hash` seems to be broken, but it's a simple solution to this.
Insted using usual combination
Answer: In iOS11 location.hash seems to be broken, but it's a simple solution to this.
Instead using an usual combination:
location.hash = "";
location.hash = _some_hash_string_

use javascript below:
var hashElement=document.getElementsByName(_some_hash_string_)[0];
if(hashElement) {
    hashElement.scrollIntoView();
} else {
    // if the element is not found - scroll to top
    document.documentElement.scrollIntoView();
}

Comment: Having javascript code is great, but I don't think this helps the querent: They can't simply write a chunk of js code into their objective-c.
Comment: Of course this can help, original question applied to UIWebView, and it has the `stringByEvaluatingJavaScriptFromString:` method, WKWebView has the `evaluateJavaScript:completionHandler:`
Comment: Works for me in iPad. +1


Verificar se existe produtos em promoção no WordPress com WooCoomerce

Question: Estou construindo um site WordPress com o WooCommerce e quero fazer a verificação de que se existe produtos em promoção com o shortcode, se existir me retorna o titulo  + produtos, se não existir nenhum produto em promoção o bloco some. Tive algumas ideias e uma delas foi a seguinte:
<?php
    //Produtos em promoção
    //Armazena o shortcode ( mas acredito estar errado )
    $produto_promocao = do_shortcode('[sale_products limit="4" columns="4" orderby="popularity" class="quick-sale" on_sale="true" ]');
    //Verifica se existe os produtos, se existir, exibe o titulo e os produtos por
    //meio do shortcode, caso ao contrario, retorna vazio
    if($produto_promocao != false){
        _e( 'Promotional Products', 'wordpress' ); //Exibe titulo
        echo $produto_promocao; //Exibe produtos
    } else {
    return ''; //Retorna vazio
    }

?>

Mas não funcionou e imagino N motivos pra isso. Imagino que eu precise de algum identificador pros produtos em promoção, ou fazer alguma outra lógica.. Aceito criticas construtivas, estou treinando ! Peço desculpas de antemão já se eu não formatei aqui direito, sou iniciante. Abraços
Answer: Fala amigo, tudo bem?
Então cara, se eu entendi bem, você poderá exibir seus produtos em promoção dessa maneira abaixo:
<?php if( woo_have_onsale_products() ) { ?>
<?php echo do_shortcode('[products limit="4"  class="teste" columns="4" orderby="popularity" on_sale="true" ]'); ?>
<?php } else { ?>

Nenhum produto em promoção no momento.

<?php } ?>

Se não achar necessário fazer a comparação com o else, basta retirar e deixar apenas o if.
Depois para que a sua lógica funcione perfeitamente, insira esse código abaixo na functions.php do seu tema:
function woo_have_onsale_products() {

global $woocommerce;
// Get products on sale
$product_ids_on_sale = array_filter( wc_get_product_ids_on_sale() ); // woocommerce_get_product_ids_on_sale() if WC < 2.1
if( !empty( $product_ids_on_sale ) ) {
    return true;
} else {
    return false;
}

}

Faz um teste aí e me dá um retorno.
Dá uma olhada também na página de documentação do woocommerce. Lá você terá várias outras opções de exibição para aplicar em seu tema.
https://docs.woocommerce.com/document/woocommerce-shortcodes/
Valeu!
Comment: Cara, muito obrigado ! Super funcionou, eu apenas acrescentei o titulo logo acima do echo do shortcode. Por gentileza, você poderia explicar sua linha de pensamento ? Gostaria de entender como você pensou para chegar a essa solução ! Abraços
Comment: Cara, basicamente eu criei uma função definindo uma variável e filtrando os ids dos produtos em promoção através do evento "wc_get_product_ids_on_sale", que vem do woocommerce, para poder fazer a comparação logo abaixo. Dá uma acessada nessa página ( https://docs.woocommerce.com/wc-apidocs/package-WooCommerce.Functions.html ), e veja os métodos disponíveis.
Answer: Exatamente, e de uma forma um pouco mais simplificada acho que poderia ficar assim:
if(woo_have_onsale_products()) {
  echo do_shortcode('[products limit="4"  class="teste" columns="4" orderby="popularity" on_sale="true" ]');
} else {
  echo '
Nenhum produto em promoção no momento.
';
}

e a função pra verificar se existem produtos on-sale ficaria:
function woo_have_onsale_products() {
  return !empty(wc_get_product_ids_on_sale());
}


Should I convert integer variables with very few unique values to factors for predictive modelling?

Question: My data set has 13 variables. The dependent variable is Boolean, and all the independent variables are either integer or numeric (i.e., continuous).
<code>data.frame':    20000 obs. of  13 variables:

$ PassFlag : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 2 1 1
 $ var1        : int  6 14 4 14 9 17 6 5 13 7 ...
 $ var2        : int  34 34 35 34 34 34 35 34 34 34 ...
 $ var3        : int  -1 0 6 0 0 -1 0 0 0 0 ...
 $ var4        : num  1096.6 403.4 162754.8 20.1 59874.1 ...
 $ var5        : num  0 0.03 0.02 0.04 0.8 0.02 0.3 0.1 0.36 0.05 ...
 $ var6        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ var7        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ var8        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ var9        : num  0.368 0.368 0.368 0.368 6.457 ...
 $ var10       : int  110 116 112 116 114 112 109 115 112 111 ...
 $ var11       : int  6 6 6 6 6 6 5 5 6 6 ...
 $ var12       : int  0 1 1 1 1 1 1 1 1 1 ...
</code>
There are not many unique values in them.
<code>[1] "Unique values in  PassFlag : 2"
[1] "Unique values in  var1 : 23"
[1] "Unique values in  var2 : 3"
[1] "Unique values in  var3 : 9"
[1] "Unique values in  var4 : 14"
[1] "Unique values in  var5 : 68"
[1] "Unique values in  var6 : 2"
[1] "Unique values in  var7 : 2"
[1] "Unique values in  var8 : 2"
[1] "Unique values in  var9 : 3486"
[1] "Unique values in  var10 : 13"
[1] "Unique values in  var11 : 12"
[1] "Unique values in  var12 : 3"
</code>
I am trying to predict whether a student will pass or not. I want to try Logistic Regression, Decision Trees, Random Forest, SVM and xgBoost .
Should I work with the independent variables the way they are, or convert them into factors, since some of them have very few unique values? Or should I one hot encode them? Or does it depends on the model I am choosing, and if yes, what kind of data should I use for each model mentioned?
Comment: Thanks Stephen for making it more readable. I would be obliged if you could answer the question.
Comment: It looks, from what you've shown, like vars 6,7 and 8 are boolean.  Var12 might also be, if there is some data entry error.
Comment: okay , but what about others , what shall i consider them for my modeling purpose ?
Answer: As Peter Flom notes, your variables 6, 7 and 8 are essentially Boolean. For these, whether you treat them as numeric, as Boolean or as factors will make literally no difference.
Variable 12 has three different values, but the first few are all 0 or 1. This might also be a Boolean variable with a data problem.
For everything else, it depends. If your variables are not interval scaled, but only ordinal, then treating them as continuous variables is, strictly speaking, wrong. (It often works well enough.) You should really use models and methods that are appropriate for ordinal independent variables.
However, if the variables are interval scaled and just happen to only have a few values, I would argue that you should typically not treat them as factors. First, treating them as factors implicitly bins them into a set of discrete bins, and binning continuous variables is usually a bad idea. For instance, if your variable has $k$ different values, then treating it as a factor uses up $k-1$ degrees of freedom. Some estimates might be very noisy, if you have observed the corresponding value rarely. This also allows the response to each "factor level" to be whatever the noise in your data suggests - your response won't be constrained to be monotonic in the independent variable.
Even worse, you lose information about unobserved intermediate values. If you have ever only observed values 1, 5 and 9 and fit a model to these as factor data, then what do you do if you ever have to predict for a value of 7? If you treat the variable as continuous, this will not be a problem.
Bottom line: better not to convert continuous data with few values into factors. Better to leave them as they are, possibly transform them using splines.


Can a categorical variable be divided by a numerical variable?

Question: I am reading P.R. Rosenbaum, Model-based direct adjustment, Journal of the American Statistical Association, 1987 (82), pp. 387-394. However, there is one equation, which I can't understand.
$$
d = \frac{1}{N}\{\sum_{s=1}^{S}\sum_{i=1}^{N_s}\frac{z_{si}r_{si}}{\hat{e}_s} - \sum_{s=1}^{S}\sum_{i=1}^{N_s}\frac{(1-z_{si})r_{si}}{1-\hat{e}_s}\},
$$
where $d$ represents the difference, $\hat{e}_s$ is the probability, $z_{si}$ is the indicator function and $r_{si}$ is a binary response such as yes/no. My question is that How can a binary categorical variable $r_{si}$ be divided by a continuous variable $\hat{e}_s$? For example, how can a categorical variable (sex) male = 1 & female = 0 be divided by 0.23?
It does not make any sense to me at all.  many thanks in advance.
Comment: Your comment, Maxim, perceptively suggests that the difficulty here is due to confusing an outcome with a random variable.  An answer to a question (the outcome) is not the same thing as the number used to code that answer (the random variable).  That's precisely why the random variable is created: so that one can do arithmetic with it!  One might then wonder about the apparent arbitrariness of the random variable: what happens when a different encoding is used (such as male=1, female=-1).  The answer is that the *formula* for $d$ may change but the *statistical inference* will not.
Comment: Although the question has already been answered mathematics-wise, I think a philosophical answer would appear to be more relevant in this case.

I agree with the question author - in reliance to the reality, such division makes no sense. In general, a binary categorical variable represents an answer to the question "Does it exist?" Whereas a continuous variable represents an answer to the question "What it's measure is in comparison to...". Those are different fundamental concepts.
Answer: I can't access the article, so I'm guessing, but the answer to your general question is that yes a binary categorical variable can be divided by a continuous variable. I'm assuming the binary variable takes the form 0/1. It will then be setting the distance to 0 when the response is 0 (no), otherwise it reduces to $\frac{z_{si}}{\hat{e_{s}}}$ (and $\frac{1-z_{si}}{1-\hat{e_{s}}}$). So you can only get a distance other than 0 when the response is 1 (yes).
Thanks to Andy W for the TeX link. :)
Comment: A reference I have found helpful for Tex is this [online latex equation editor](http://www.codecogs.com/latex/eqneditor.php).
Answer: Without reading the paper in detail, I'd assume it is using the common convention of coding a binary variable as 0/1 (e.g. 0=No, 1=Yes ; or 0=Incorrect, 1=Correct).
Comment: Onestop, thanks for answering my question but 0/1 or no/yes does not change the characteristic of the variable. The variable $r_{si}$ is still a binary "categorical" variable. Am I right? Thus, how can a binary categorical variable be divided by a numerical number?
Comment: You can divide 0 or 1 by a numerical number, can't you?
Comment: Yes from a mathematical point of view I understand it. But I still can't image. Such as (female = 1)/ 0.3 = 3.3333. What does 3.333 mean for sex variable?
Answer: One way of thinking of this, when the variable is coded 0/1, is thinking of it as a logical variable rather than numerical.  In the equation you are worried about, we don't just have a binary variable divided by something else - it is part of a bigger expression with various other products.  Including the binary variable means "include this set of products and divisions if the binary variable is 1; make it zero otherwise so this particular term doesn't add to my overall result".


Cannot access field from static context when passing value to superconstructor

Question: I got a very weird compile-time error:
class Super {
    Super(int[] array) {

    }
}

class Sub extends Super {
    private final int number = 1;

    Sub() {
        super(new int[] { number }); //error
    }
}

The error I get is

Cannot access field from static context

My question
Where is the static context? It doesn't seem as if static would even play a role here.
I stumbled across this attempting to answer someone else's question; found the error I got baffling. Can someone explain where the static context is?
Comment: Which compiler are you using? I get `cannot reference number before supertype constructor has been called`. See also the JLS 220.127.116.11. _Explicit Constructor Invocations_ which states: _"An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs."_
Comment: @ZouZou I first encountered it on my phone's ide AIDE, which I'm pretty sure uses the Dalvik compiler. Then I hopped on my computer to try it on Eclipse Luna, using their JDK 8u25 compiler and got the same error message. I'm not sure why it's giving me the static context error, so I think I should reinstall Eclipse. As for AIDE, I'm not too surprised it gave me a funky error
Answer: Your field number should be static, so that you can use it in constructor call. Otherwise you'll get cannot reference number before supertype constructor has been called because the field is not accessible before you call the constructor of the parent class.
So your code should look like:
class Super {
    Super(int[] array) {

    }
}

class Sub extends Super {
    private static final int number = 1;
    Sub() {
        super(new int[] { number }); //error
    }
}

Comment: This was not the error I received, however it is the proper error that should have been displayed. This was the problem. It was a few years ago, but looking back, this seems to be the best answer. Thank you for the contribution, sorry it took so long to accept. Although the other answers mentions a JLS query, it doesn't suggest a fault of notification, nor specify what the *proper* notification would be.
Answer: From  JLS 8.8.7

An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

At the time of the super call an instance of Sub will not yet exist
Comment: + 1. I think your last sentence is the key point. Since there is no instance available there, it actually makes sense for the compiler to consider this a "static context", just like inside a static method, or static initialization block, or the initializing expression of a static field. (Personally, I think the compiler would do better to use a separate error-message for this context, just for clarity and to avoid confusion. But the constraints are the same as in normal static contexts, so the compiler-writers were probably too tempted to Not Repeat Themselves.)
Answer: The thing is, super must be called before anything else is done in the subclass. It means, that number is not initialized at the time of the call, so you can't pass it to super.
As to what it has to do with the "static context", I am not sure.
Answer: Try running the following program.
public class Main {

    public static class Super
    {
        Super(int number) {
            System.out.println("A");
        }
    }

    public static class Sub extends Super {

        private final Thing thing = new Thing();

        Sub() {
            super(3);
            System.out.println("B");
        }
    }

    public static final class Thing {
        Thing() {
            System.out.println("C");
        }
    }

    public static void main(String[] args) {
        new Sub();
    }
}

The output is A, C, B. First the constructor of Super runs, then the instance field thing of Sub is initialised. Finally the lines of the Sub constructor following super are executed.
When you try to reference number, the field number has not been initialised yet and there is no Sub instance. The error message could be more helpful. On IntelliJ I'm getting "Cannot reference Sub.number before supertype constructor has been called".
Answer: Loading of classes is done from child class(if its having main method or caused by other class to load) to base class but initialization is happening in reverse order(Base class will initialized first). base class initialization is done before, at that time your number field will not be in existence as it is instance variable.
You can make it static(class variable) to load earlier and if its final then compiler will make an entry in constant pool at compile time only.so that JVM will able to get its value.


Escaping Lucene Characters using Javascript Regex

Question: I'm using elasticsearch in a NodeJS project, which is breaking upon entering one of the Lucene keywords into the search box. I'm looking for a simple implementation to escape their special characters. Is regex the best way? I've been fiddling with the regex for a bit now, and felt as if there were probably others that have already gone through this process.
Answer: Just needed to fiddle more.
var escaped = query.replace(/([\!\*\+\&\|\(\)\[\]\{\}\^\~\?\:\"])/g, "\\$1");

Globally replace all instances of the chars lucene would yell about with their escaped version.
Comment: Note that this regex will not catch backslash (\\), front slash (/), or minus (-)
Comment: Does it handle  && and || by \& and \|
Comment: @sunitj you can check full reserved characters from https://www.elastic.co/guide/en/elasticsearch/reference/1.6/query-dsl-query-string-query.html#_reserved_characters
Comment: The above answer escapes Lucene special chars, but Elastic has some more which are not included here. See below answer
Answer: I updated this to include all elasticsearch & Lucene reserved characters:
var pattern = /([\!\*\+\-\=\<\>\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g;

var str = "}the+S+entence you want]]to e*scape"

str = str.replace(pattern, "\\$1");


Help solving the improper integral $\int_1^\infty \frac{2}{4{x^2}-1}\,\mathrm dx$

Question: I need to solve an improper integral which is:
$$ \int_1^\infty \frac{2}{4{x^2}-1}\,\mathrm dx $$
i was trying to solve it using simple substitution but cannot seem to figure it out, i tried a website to solve the integral and it leads to the result being
$$ \frac{i\pi}2 - (-\operatorname{arctanh}(2)) $$
and then it says simplify and it gets $ \frac{\ln(3)}2 $ which is the result i need but i don't get how to get there, also i have never used hyperbolic functions nor imaginary numbers so i was wondering if there's another way to integrate this function without using them (hyperbolic functions and imaginary numbers), if there's no other way could you explain to me the steps?.
This is the link to the site solving the integral : solution
Answer: $$ \int_{1}^{\infty}\frac{2}{4x^2-1}dx=\int_{1}^{\infty}\left(\frac{1}{2x-1}-\frac{1}{2x+1}\right)dx=\frac{1}{2}\ln\left| \frac{2x-1}{2x+1}\right|_{1}^{\infty}=\frac{1}{2}\bigl(\lim_{x\to \infty}\ln\left| \frac{2x-1}{2x+1}\right|-\ln\frac{1}{3}\bigr)=\frac{\ln 3}{2}. $$
Comment: thank you very much, really helpful.
Answer: By setting $x=\frac{1}{y}$,
$$\int_{1}^{+\infty}\frac{2}{4x^2-1}\,dx = \int_{0}^{1}\frac{2\,dy}{4-y^2}=\frac{1}{2}\left(\int_{0}^{1}\frac{dy}{2-y}+\frac{dy}{2+y}\right)=\frac{1}{2}\int_{1}^{3}\frac{dz}{z}=\color{red}{\frac{\log 3}{2}}.$$
Answer: SMALL HINT
factor out $\frac{1}{2}$ and use this method to make the appropriate sub.
Comment: Or take Janko's method...which is very good lol


Can you customize the User Edit page without editing the theme?

Question: Is there a way to customize what appears on the user profile edit page without editing the theme? I'd much rather use blocks or hooks to accomplish this task.
Is this possible?
Answer: You can use panels. It has a panel page for the 'user edit page' that you can edit, put blocks, views, etc.


How strongly does $\int_1^X \frac{\exp(B/\sqrt x)}{\sqrt x} dx$ depend on $B$?

Question: As part of analysing an algorithm I stumbled upon the integral $\displaystyle \int_1^X \frac{\exp(B/\sqrt x)}{\sqrt x} dx$ as an approximation for the corresponding sum. Wolfram alpha gives the antiderivative in terms of non-elementary functions. This seems more trouble than it's worth since I'm only interested in a readable bound for the integral.
One very poor bound  comes from rounding the exponential up to $e^B$ and get $\displaystyle e^B \int_1^X \frac{dx}{\sqrt x}  = 2e^B(\sqrt X - 1) = O(e^B \sqrt X) $.
One better bound comes from breaking the intgral into two parts like this:
$$\displaystyle \int_1^X \frac{\exp(B/\sqrt x)}{\sqrt x} dx= \int_1^{B^2}\frac{\exp(B/\sqrt x)}{\sqrt x} dx + \int_{B^2}^X \frac{\exp(B/\sqrt x)}{\sqrt x} dx$$
For the first part do the same rounding up to get
$$  \int_1^{B^2}\frac{\exp(B/\sqrt x)}{\sqrt x}\le e^B \int_1^{B^2}\frac{dx}{\sqrt x} \le 2e^B \sqrt {B^2} = 2B e^B.$$
For the second part the denominator is small and we get
$$ \int_{B^2}^X \frac{\exp(B/\sqrt x)}{\sqrt x} dx \le \int_{B^2}^X \frac{e}{\sqrt x} dx = 2 e (\sqrt X - \sqrt {B^2}) \le 2e \sqrt X.$$
Putting it back together we can bound the original integral by $2Be^B + 2e \sqrt X$. We still have the exponential term but not it is a constant and not multiplied by the $\sqrt X$.
I wonder can we do any better than this? Can we replace the dependence on $B$ with something weaker?
Comment: I think the following might help. Consider the u sub $u = 1/sqrt(x)$. Then the integral is $2\int_{1/\sqrt{X}}^1 \exp(Bu)u^2 \ du$. Now the whole integral from $0$ to $1$ can be found explicitly and then the error term is $2\int_0^{1/\sqrt{X}}$. For this, a taylor series around $0$ gives you a good bound.
Answer: I do not know if this will answer your question.
Effectively, after one integration by parts, we end with
$$I=\int_1^X\frac{e^{\frac{B}{\sqrt{x}}}}{\sqrt{x}}\, dx=-2 \left(B \,\text{Ei}\left(\frac{B}{\sqrt{X}}\right)-B\, \text{Ei}(B)-\sqrt{X}
  \, e^{\frac{B}{\sqrt{X}}}+e^B\right)$$
What is doable is to expand as a series around $B=0$; this would give
$$I=2\left( \sqrt{X}-1\right)+B\, \log (X)+
   \left(1-\frac{1}{\sqrt{X}}\right)B^2+O\left(B^3\right)$$
Answer: You can easily find
$$
\int\frac{\exp(B/\sqrt{x})}{\sqrt{x}}dx=2\sqrt{x}\exp\left(\frac{B}{\sqrt{x}}\right)-2B\cdot\textrm{Ei}\left(\frac{B}{\sqrt{x}}\right),
$$
where
$$
\textrm{Ei}(z)=-\int^{\infty}_{-z}\frac{e^{-t}}{t}dt
$$
and then see at Wikipedia Ei


dc.js: Setting Categorical Bar Chart X Axis with a Wide Domain

Question: I have a csv with a column that is a category variable that I want to set on the x Axis of a dashboard using dc.js
I know that I can set the set the x-axis as this (copied from this post)
.x(d3.scale.ordinal().domain(["", "a", "b", "c"])) // Need empty val to offset first value
.xUnits(dc.units.ordinal) // Tell Dc.js that we're using an ordinal x axis

However, is there any way I can replace the a,b, and c with a variable that captures all of this? My column has 20 different categories and I don't want to type them out by hand. My code is below (the column is d.geo)
var geoValue = ndx.dimension(function (d) {
    return d.geo;
});
var geoGroup = geoValue.group();

geoChart
    .width(960)
    .height(150)
    .margins({top: 10, right: 10, bottom: 20, left: 40})
    .dimension(geoValue)
    .group(geoGroup)
    .transitionDuration(500)
    .gap(10)
    .x(d3.scale.ordinal().domain(SOLUTION GOES HERE))
    .xUnits(dc.units.ordinal)
    .elasticY(true)
    .xAxis().tickFormat();

Comment: As of dc.js 2.0, ordinal domains are calculated automatically.
Comment: You do not need to call `.domain()` at all.
Answer: I think the following should work
.x(d3.scale.ordinal().domain(geoValue))

the following worked for me. I was also struggling with a similar scenario
var carTypeDim = ndx.dimension(function(d) { return d["car-type"]; });
carTypeGroup = carTypeDim.group()

carTypeChartBar
  .x(d3.scale.ordinal().domain(carTypeDim))
  .xUnits(dc.units.ordinal)
  .dimension(carTypeDim)
  .group(carTypeGroup);


Access sharepoint folders in R

Question: I'm currently trying to access sharepoint folders in R. I read multiple articles addressing that issue but all the proposed solutions don't seem to work in my case.
I first tried to upload a single .txt file using the httr package, as follows:
URL <- "<domain>/<file>/<subfile>/document.txt"
r <- httr::GET(URL, httr::authenticate("username","password",type="any"))

I get the following error:
Error in curl::curl_fetch_memory(url, handle = handle) :
  URL using bad/illegal format or missing URL

I then tried another package that use a similar syntax (RCurl):
URL <- "<domain>/<file>/<subfile>/document.txt"
r <- getURL(URL, userpwd = "username:password")

I get the following error:
Error in function (type, msg, asError = TRUE)  :

I tried many other ways of linking R to sharepoint, but these two seemed the most straightforward. (also, my URL doesn't seem to be the problem since it works when I run it in my web browser).
Ultimately, I want to be able to upload a whole sharepoint folder to R (not only a single document). Something that would really help is to set my sharepoint folder as my working directory and use the base::list.files() function to list files in my folder, but I doubt thats possible.
Does anyone have a clue how I can do that?
Answer: I created an R library called sharepointr for doing just that.
What I basically did was:

Create App Registration

Add permissions

Get credentials

Make REST calls

The Readme.md for the repository has a full description, and here is an example:
# Install
install.packages("devtools")
devtools::install_github("esbeneickhardt/sharepointr")

# Parameters
client_id <- "insert_from_first_step"
client_secret <- "insert_from_first_step"
tenant_id <- "insert_from_fourth_step"
resource_id <- "insert_from_fourth_step"
site_domain <- "yourorganisation.sharepoint.com"
sharepoint_url <- "https://yourorganisation.sharepoint.com/sites/MyTestSite"

# Get Token
sharepoint_token <- get_sharepoint_token(client_id, client_secret, tenant_id, resource_id, site_domain)

# Get digest value
sharepoint_digest_value <- get_sharepoint_digest_value(sharepoint_token, sharepoint_url)

# List folders
sharepoint_path <- "Shared Documents/test"
get_sharepoint_folder_names(sharepoint_token, sharepoint_url, sharepoint_digest_value, sharepoint_path)

Access sharepoint folders in R


Are Table Tennis Bats Supposed to Be Pimpled or Even?

Question: I searched prior to posting this question and I found this one Red and black side of table tennis raquet that didn't quite answer my question.
I want to buy a cheap pair of bats and I saw these ones that are second hand. The owner has no idea if they're as they should be, but from what I remember from my brother's bats years ago, they used to have an extra rubber layer on the pimpled layer (which was flat and even on the outer side and pimpled inwards that would be glued to the pimpled surface of the bat).
Now are these bats ready to use just for hobbyish playing or do I need extra rubbers on top?
Answer:
Are Table Tennis Bats Supposed to Be Pimpled or Even?

This is your choice. This depends on your style of play (speed/spin vs. control, etc). As a hobbyist, this will not matter much.
This provides descriptions for different kinds of rubber. If I had to guess, the "extra rubber layer on the pimpled layer" is inverted rubber.
In my experience, I played with "pimpled" table tennis rackets mostly, but prefer rackets with inverted rubber as I like to provide speed/spin to my shots. As a hobbyist myself who may or may not have a choice in what rackets may be available, I settle for "pimpled" rackets.

Now are these bats ready to use just for hobbyish playing or do I need extra rubbers on top?

As-is, they're ready to use for play as a hobby. If you would like to protect your racket and if you decide to become competitive, then I suggest the extra rubbers. There are many tutorials available in regards to assembling/choosing a table tennis racket.


NoneType object has no attribute to get (Tkinter)

Question: I don't know why this is not working and it is really annoying,
from tkinter import *

root = Tk()
def do(r, a):
    s = r.get()
    p = a.get()
Button(root, text="DEL3TE", fg="red", command=lambda: do(r, a)).grid(row=0, column=0)
r = Entry(root, width=15, bg="white").grid(row=0, column=1)
a = Entry(root, width=15, bg="white").grid(row=1, column=1)
Label(text="text1").grid(row=1, column=2)
Label(text="text2").grid(row=0, column=2)
Label(text="You have obtained the death note", fg="red").grid(row=2, column=0)
mainloop()

The error code is as follows:
Traceback (most recent call last):
  File "C:\Users\anglc\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/anglc/Desktop/test.py", line 7, in <lambda>
    Button(root, text="DEL3TE", fg="red", command=lambda: do(r, a)).grid(row=0, column=0)
  File "C:/Users/anglc/Desktop/test.py", line 5, in do
    s = r.get()
AttributeError: 'NoneType' object has no attribute 'get'

I can't figure out how to fix it, please help, thank you!
Answer: If you are making an entry, be sure that it is not formatted like this:
r = Entry(root, width=15, bg="white").grid(row=0, column=1)

It should be like this to remove an AttributeError:
r = Entry(root, width=15, bg="white")
r.grid(row=0, column=1)

Answer: In this line :
Button(root, text="DEL3TE", fg="red", command=lambda: do(r, a)).grid(row=0, column=0)
After lambda you need to give :
Button(root, text="DEL3TE", fg="red", command=lambda r,a: do(r, a)).grid(row=0, column=0)
As you the do function only get the None value that you have need to pass real value you the do function.
Comment: This gives me a new error, () missing 2 required positional arguments: 'r' and 'a' its a TypeError btw
Comment: you have to first assign values to r and a and then call the function do.
Comment: still doesn't work
Comment: from tkinter import *

root = Tk()
def do(r, a):
    s = r.get()
    p = a.get()
r = Entry(root, width=15, bg="white").grid(row=0, column=1)
a = Entry(root, width=15, bg="white").grid(row=1, column=1)
Button(root, text="DEL3TE", fg="red", command=lambda r,a: do(r, a)).grid(row=0, column=0)
Label(text="text1").grid(row=1, column=2)
Label(text="text2").grid(row=0, column=2)
Label(text="You have obtained the death note", fg="red").grid(row=2, column=0)
mainloop()
Comment: whats the error
Comment: That doesnt work for me and it defines r and a before
Comment: Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\anglc\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: () missing 2 required positional arguments: 'r' and 'a'
Comment: I was able to fix it on my own, thanks though!


Detectar erros e problemas potenciais (lint ou code quality tool)

Question: É possível fazer uma analise (checagem) de um código PHP para determinar a "qualidade" da organização e detectar problemas potenciais?
http://en.wikipedia.org/wiki/Lint_(software)
Comment: Antes de dar um voto negativo entenda o modelo da comunidade, leia: pt.stackoverflow.com/help/self-answer e blog.stackoverflow.com/2012/05/encyclopedia-stack-exchange e se tiver algum outro motivo pro downvote justifique.
Answer: O PHP já fornece este tipo de ferramenta por linha de comando, pode-se testar a "qualidade do código" por linha de comando:
php -l <fileName>

Um exemplo no Windows seria:
D:\wamp\php\php.exe -l "D:\wamp\www\arquivo.php"

Além desta ferramenta existem outras maneiras de fazer isto conforme está resposta no SOen:

PHP Metrics - Apresenta uma visão geral e gráficos de qualidade geral, de acordo com diferentes métricas como mantenabilidade Index, métricas de Halstead, Coupling ou complexidade Cyclomatic.
PHP Code Sniffer - Basicamente garante que o código PHP está em conformidade com a norma. Você pode escrever o seu próprio "padrão".
PHP Unit ou atoum - Teste Unit (testes unitários/unit são testes para pequenas partes de código).
PHP Project Mess Detector - O N-Path e outras analises complexas para determinar a complexidade de partes do código.
PHP Depend - Faz análise estática de código em uma determinada a estrutura base (está estrutura é normalmente chamada de um AST (Abstract Syntax Tree)).
ScrutinizerCi (https://github.com/scrutinizer-ci) - Lista das ferramentas descritas acima

Também existe uma ferramenta simples chamada PHPLint e pode ser testada online, o problema é que para versões mais recentes do PHP e phpDocumentor ele se demonstrou desatualizado, porém ainda sim é útil para testes mais simples.


OutOfRangeError logged at each epoch after upgrade from Tensorflow 1.8.0 to 1.11.0

Question: I have a TfRecordsDataset:
...
dataset = dataset.batch(batch_size)
dataset = dataset.prefetch(buffer_size=tf.contrib.data.AUTOTUNE)
dataset_iterator = dataset.make_initializable_iterator()
(...) = dataset_iterator.get_next()

And then the standard:
test_session.run(dataset_iterator.initializer)
while not done:
    try:
        ... = test_session.run([...])
        batch_count += 1
    except tf.errors.OutOfRangeError:
        done = True

This worked perfectly with Tensorflow 1.8.0. Today I upgraded Tensorflow to TF 11.1.0, and I now have an error:
 OutOfRangeError: End of sequence [[{{node dataset/IteratorGetNext}} = IteratorGetNext
at each end of an epoch. The error itself is actually caught, but the error is printed on the console. Can someone point out what is actually happening ?
Comment: if you get a solution, please update here, I am facing exact same issue.
Comment: well, I think this is related to this [thread](https://github.com/tensorflow/tensorflow/issues/12414) which points to this
 [commit](https://github.com/tensorflow/tensorflow/commit/2c97ee31b0cb584b255232d46d4e42db4cbcb1c2). It seems to happen only within unit tests framework. I just mute the logging with `tf.logging.set_verbosity(tf.logging.FATAL)` if needed.  I haven't seen the spurious log in production though, so I live with it for now.
Answer: Problem was solved in TF 1.12.0.


What are the intermediate fields of $\mathbb{Q}(\sqrt[4]{2},i)/\mathbb{Q}$ of order $4$ over $\mathbb{Q}$?

Question: Let $K = \mathbb{Q}(\sqrt[4]{2},i)$.
Am I correct to say that $K$ has a 8-th primitive root: $\zeta_8 = \frac{1}{\sqrt{2}} + \frac{1}{\sqrt{2}}i$?
The 8-th cyclotomic polynomial is $\Omega_8 = X^4+1$ (is irreducible over $\mathbb{Q}$). The number of primitive 8-th roots of unity is given by the Euler $\varphi$ function: $\varphi(8) = \varphi(2^3) = 2^{3-1}(2-1) = 4$.
I found that $\text{Gal}(K/\mathbb{Q}) = \text{D}_4$, and $D_4$ has 5 subgroups of order 2 (by the Galois correspondence these give intermediate fields of order 4).
Two generators for the intermediate fields of order 4 are: $\sqrt[4]{2}$ and $\zeta_8$ but I'm having trouble to find the other 3.
Comment: How about $\Bbb Q(\zeta_8\sqrt[4]2)\supset\Bbb Q$ ? And how about some compositums of quadratic extensions of $\Bbb Q$ ?
Comment: My answer [here](https://math.stackexchange.com/questions/2773834/how-to-draw-subgroup-lattice-for-extension-field-mathbbq-sqrt42-i/2773973#2773973) might be helpful
Answer: I think the most systematic way to approach this is to write down the automorphisms generating each of these order-five subgroups, and find the intermediate fields fixed by each of these subgroups. That way, you can be absolutely certain that the intermediate fields you find will be distinct, and cover all the possibilities.
So let's establish some notation. ${\rm Gal}(K/ \mathbb Q) \cong D_4$ is generated by the automorphisms:
$$ \sigma: \sqrt[4]{2}\mapsto i\sqrt[4]{2}, \ i\mapsto i$$
$$ \iota : \sqrt[4]{2}\mapsto \sqrt[4]{2}, \ i\mapsto -i.$$
It's also helpful to work out how $\zeta_8$ transforms under $\sigma$ and $\iota$, and I'll leave that to you.
The order two subgroups are $\left< e, \sigma^2 \right> $,  $\left< e, \iota\right>$, $\left< e, \iota \sigma \right>$, $\left< e, \iota \sigma^2 \right>$ and $\left< e, \iota \sigma^3 \right>$, and you need to find the subfields fixed by each.
Can you see which order-two subgroup fixes $\mathbb Q(\zeta_8)$? What about $\mathbb Q(\sqrt[4]{2})$? And what about $\mathbb Q(\zeta_8 \sqrt[4]{2}$) (Lubin's example)? Can you identify and extend the pattern in the last two examples to come up with generators for the fixed fields for the remaining two subgroups?
Finally, it's good to appreciate that a subfield can be written in more than one way, and this can be confusing. For example, $\mathbb Q(i, \sqrt{2})$ is an extension of order four over $\mathbb Q$, so it must correspond to one of the five items in the list. Which one is it?


Volume of solids of revoution

Question: Let $R$ be the region bounded by the line $x = 6$ and the curve $9x^2 - y^2 = 9$ . Find $h(y)$ so that integral from $a$ to $b$ is $h(y)dy$ represents the volume of the solid resulting from revolving about the line $x=-9$.
I already found $a$ and $b$ which are
$a = - \sqrt {315}$
$b = \sqrt {315}$
I need help setting up the problem to find $h(y)$ which is like $a(y)$.
Can anyone help? Thanks
Answer: Hint: If you use the "washer" method, the outer radius should be $R = 6-(-9)=15$ and the inner radius should be $r = \sqrt{1 + (y/3)^2} - (-9) = 9 + \sqrt{1+(y/3)^2}$.
Comment: Thanks for the hint. I was able to get the answer :)

Volume of solids of revoution


(JavaFX)(SceneBuilder) How can I automatically resize the scene when the window is resized if everything is set into a AnchorPane?

Question: All of my code in the fxml file is set inside an anchor pane and I was wondering if there was a simple way to allow the entire scene to auto-resize when the Window is resized?
FXML File:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>

<fx:root maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" type="AnchorPane" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="csgocaseopener.InventoryController">
   <children>
      <ImageView fitHeight="400.0" fitWidth="600.0" pickOnBounds="true">
         <image>
            <Image url="@back.png" />
         </image>
      </ImageView>
      <AnchorPane layoutX="38.0" layoutY="65.0" prefHeight="270.0" prefWidth="525.0" />
      <ImageView fx:id="backbtn" fitHeight="45.0" fitWidth="45.0" layoutY="-1.0" onMouseClicked="#handleInventoryBack" pickOnBounds="true" preserveRatio="true" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="-1.0">
         <image>
            <Image url="@backbtn.png" />
         </image>
      </ImageView>
   </children>
</fx:root>

Comment: Your `AnchorPane` is resizing when you resize Window. In given code you fill the whole `Scene` with image, so I assume that you want to resize image to fill window.
Comment: Yea I just want everything to fill the size of the window
Answer: Bind ImaveView fit to width/height property to Stage width/height property. This solution will not keep image ratio so it will be deformed.
ImageView imageView = new ImageView(new Image(getClass().getResourceAsStream("test.png")));
//imageView.setPreserveRatio(true);  //uncomment to keep image ratio.
imageView.fitHeightProperty().bind(stage.heightProperty());
imageView.fitWidthProperty().bind(stage.widthProperty());


Migrate node with paragraph

Question: I'm trying to figure out how migrating content from a Drupal 7 site to a Drupal 8 site works. I managed to understand how to create a custom module to migrate nodes with regular fields to my new D8 site.
But I also have one content type where I use paragraphs. And I can't seem to find a well documented example on how to do this. I found some examples but they all seem to use different methods. This one seems like the most up to date. But how to make the code from #9 work?
field_paragraphs:
plugin: sub_process
source: field_source_paragraphs
process:
  target_id:
    -
      plugin: migration_lookup
      migration:
        - paragraph_box
        - paragraph_grid
        - paragraph_text_embedded
      source: value
    -
      plugin: extract
      index:
        - 0
  target_revision_id:
    -
      plugin: migration_lookup
      migration:
        - paragraph_box
        - paragraph_grid
        - paragraph_text_embedded
      source: value
    -
      plugin: extract
      index:
        - 0

So the field_paragraphs and field_source_paragraphs I understand. But what are these paragraph_ items under migration? Is this where I set the paragraph bundles? And if not where do I set the paragraph bundles and there fields? So where do I begin? What are the right steps to take?
Thanks in advance
Comment: Have you seen this? https://softescu.com/blog/knowledge-centre/how-migrate-paragraphs-paragraphs-drupal-7-drupal-8 I found it very helpful for migrating my own nodes with paragraphs 7 to 8.
Comment: That link has changed: https://softescu.com/blog/how-migrate-paragraphs-drupal-7-drupal-8
Answer: You'll need to create a plugin within your custom module in order to migrate paragraph fields properly. I just finished this process on a large site. I'm paring down the module to make it a bit easier to understand and making it available in a public repository, along with an explanatory video:
https://www.arsnova.cc/drupal-7-drupal-8-paragraph-migration

Migrate node with paragraph


Show that if $X$ is path connected then every path $f:I\to X$ is homotopic to a constant path $g(t)=x$

Question: Show that if $X$ is path connected then every path $f:I\to X$ is homotopic to a constant path $g(t)=x$. Does this mean show that there is an $x$ (or even for all $x$) such that this is true for all paths $f$, or to show for each $f$, there is an $x$ such that this is true? I know that two paths are homotopic if there exists a continuous map $H(s,t):I\times I\to X$ with $H(s,0)=f(s)$ and $H(s,1)=g(s)$. I think I'm just misunderstanding the question. If we take an annulus, which is path connected, and consider a loop around the inner circle, then how is this loop, which is a path, homotopic to any constant loop? Could somebody explain what the question is asking since I can't make any progress with it until I understand. I thought googling this question would tell me something and nothing came up. Is the claim false or am I misunderstanding something?
Comment: We have a tough time addressing "what is this Question asking" Questions.   You are obviously right that a loop in a path connected space need not be null-homotopic, so the problem likely assumes a path is not self-intersecting, unlike a loop. Where did you encounter the problem?
Comment: @hardmath Almost the same problem ("Show that if X is path-connected, then any two paths are freely homotopic") is an Exercise 4.11 in "Modern Classical Homotopy Theory" by Jeffrey Storm. By 'free homotopy' he means homotopy as a continuous map $X \times I \rightarrow Y$.
Answer: This can work (to assuage your doubts) as the homotopy is a "free" one, where the homotopy does not have to preserve any fixed point, as in the fundamental group, which is why the torus or circle don't work as counterexamples..
If $f$ is a path, we can define $H: [0,1] \times [0,1] \to X$ by $H(s,t) = f(s(1-t))$ which is clearly continuous, and for $t=0$ we just have the path $f$ and for $t=1$ a constant map with constant value $f(0)$. We could have an arbitary $x$ for the constant because in path connected space $X$ any two constant maps are homotopic (and homotopy is an equivalence relation).
Comment: To show that any two constant paths $f(t)=x$ and $g(t)=y$ are homotopic in a path connected space, could I use the homotopy $H(s,t)=h(t)$ where $h$ is a path from $x$ to $y$?
Comment: @Loobear23 Yes, quite.
Comment: How is this a path homotopy if $H(1,t) = f(1-t)$? I know that $H(0,t) = f(0) =x$, but doesn't $H(1,t)$ need to be equal to the endpoint $x$ as well?
Answer: Well, I think that the quastion could be wrong, because "path connected" is not enough to ensure that any path is homotopic to a point. As a counterexample, a loop in the circle $\mathbb{S}^1$ (with its usual topology) is not homotopic to a point.
The question that arises then is: What is the definition of "path connected"? Linking it with the one in your question, I would write:
Definition:
Let $(X,\tau_X)$ be a topological space. Then $X$ is path connected if $\forall x,y\in X$ two points in $X$, $\exists f\in Mor_{Top}(I,(X,\tau_X))$ such that $f(0)=x$ and $f(1)=y$.
Conversely, both $x$ and $y$ can be understood as constant paths. In that case, $f$ won't be a path, but a homotopy.
Let $x\in Mor_{Top}(I,(X,\tau_X))$, $y\in Mor_{Top}(I,(X,\tau_X))$, such that $x(t)=x, y(t)=y\; \forall t\in I$. If $(X,\tau_X)$ is path connected, there must exist $H\in Mor_{Top}(I\times I,(X,\tau_X))$ such that $H(0,t)=x(t)=x$ and $H(1,t)=y(t)=y$. Essentially, $H(s,t)$ is the same thing as $f(t)$, but defined as a different object.
Note that the topologies are necessary to check if the given morphisms are continuous, as they have to be, because they are morphisms of Top category.


Limitar valor R$ em campo input com HTML5 e CSS3 com Javascript

Question: Preciso limitar o valor em R$ de campo input de um formulário. O formulário está assim:

            <form>

                    Desejo doar em R$:
                    <input name="campo1" onkeypress="mascara(this,mreais)" size="7" min="10,00" max="1.064,00" />

                    Conforme resolução do TSE, as doações são limitadas a R$ 1.064,10 por dia e a 10% dos rendimentos brutos em 2017 para cada pré-candidato.

                    <button type="submit" class="btn-doar-form">Doar com Pagseguro</button>

            </form>

E fiz um script para atribuir R$ no campo assim:

Como posso limitar o valor máximo em R$ 1.064,00?
Comment: O max, se vc colocar apenas "1064" nao funciona?
Comment: Não. Ai permite 1064 caracteres...
Comment: Testei aqui e deu certo, em 1065 ele reclamou: "Please enter a value less than or equal to 1064."
Answer: Fazendo um teste simples aqui, com o input abaixo:
<input type = "number" min= '10' max = '1064'>

Automáticamente, ao digitar 1065 tive o retorno abaixo:

Please enter a value less than or equal to 1064

Note que o min e max tem que ser inteiros (não se referem ao número de caracteres mas sim ao tamanho do número permitido). Caso precise que seja quebrado o número, use a opção step = 0.01
Answer: Pode também restringir os valores usando este código no final da função mreais(v):
function mreais(v) {
    v = v.replace(/\D/g, "") //Remove tudo o que não é dígito
    v = v.replace(/(\d{2})$/, ",$1") //Coloca a virgula
    v = v.replace(/(\d+)(\d{3},\d{2})$/g, "$1.$2") //Coloca o primeiro ponto

   if(v.length >= 5){
      var maximo = v.replace(/\./g,'').replace(',','.') > 1064;
      var minimo = v.replace(/\./g,'').replace(',','.') < 10;

      if(maximo){
         return '1.064,00';
      }else if(minimo){
         return '10,00';
      }else{
         return v;
      }
   }else{
      return v;
   }
}

Você pode remover os atributos min e max do input porque só funcionam em type="number". A propósito, a sua máscara não irá funcionar em input type="number".
Exemplo:

function mascara(o, f) {
    v_obj = o
    v_fun = f
    setTimeout("execmascara()", 1)
}

function execmascara() {
    v_obj.value = v_fun(v_obj.value)
}

function mreais(v) {
    v = v.replace(/\D/g, "") //Remove tudo o que não é dígito
    v = v.replace(/(\d{2})$/, ",$1") //Coloca a virgula
    v = v.replace(/(\d+)(\d{3},\d{2})$/g, "$1.$2") //Coloca o primeiro ponto

   if(v.length >= 5){
      var maximo = v.replace(/\./g,'').replace(',','.') > 1064;
      var minimo = v.replace(/\./g,'').replace(',','.') < 10;

      if(maximo){
         return '1.064,00';
      }else if(minimo){
         return '10,00';
      }else{
         return v;
      }
   }else{
      return v;
   }
}

   <form>

           Desejo doar em R$:
           <input name="campo1" onkeypress="mascara(this,mreais)" size="7" />

           Conforme resolução do TSE, as doações são limitadas a R$ 1.064,10 por dia e a 10% dos rendimentos brutos em 2017 para cada pré-candidato.

           <button type="submit" class="btn-doar-form">Doar com Pagseguro</button>

   </form>


What types of feels are there for drumming?

Question: Playing as strictly a metal or hard rock drummer, I am only aware of a swing feel (accenting every other hi-hat note), or a straight feel (this would be more of a flat, driving beat.  More monotonous).
What other feels are there?  I imagine these might be like presets you can find on cheaper keyboards, like samba, etc.  Am I way off in this?
Comment: Swing is a lot more than merely what you portray. Are you asking for a list?
Comment: A list would be great.
Comment: I see that a list could not be reasonably comprehensive.  Maybe some popular ones?
Comment: I have a feeling that expecting a list is asking for this to be closed.
Comment: If not a list, then maybe some advice where to find this information. e.g. is it on the web, in a book?
Comment: Seems you're asking more about different *rhythms* rather than *feels*.
Comment: Swing in my mind is a feel, not a particular rhythm.
Answer: To me, samba is a specific rhythm, which is not the same as a feel. There are hundreds of popular rhythms and there are probably thousands of feels. Even in the metal world, you might play the same rhythm with a dragging, somber feel or with an aggressive, angry feel.
To me, a feel is created by micro adjustments in timing and note emphasis (dynamics), sometimes combined with other elements like ghost notes and exactly how the kit pieces are played.
So you could play with a samba feel without playing a samba rhythm, which might mean taking the subtle timing and emphasis used when playing samba and mashing it together with a non-samba beat.


What does this wavy downward arrow preceding a piano chord mean?

Question: I started to play this piece today, & I came across this symbol (wavy arrow pointing downwards in treble clef). I have never seen it before in any piece, nor did I read about it in music theory so far. What does it mean?

I am assuming it could mean to play the notes of the chord like an arpeggio, but instead of starting from the lowest note, you start from the highest note (i.e. G in the 5th space), then play D & G (2nd line). Is my guess correct?
Comment: That's right, it's a reverse arpeggio. The mark is more common in music for guitar and string instruments.
Comment: @ Kilian Foth: If one will poste your comment as an  answer this question this would  be a "Grace note" ;)
Comment: Hahahaha good one @AlbrechtHügli!
Comment: Oh wow, I didn't know that @KilianFoth. Something new to learn!
Answer: The symbol indicates the chord should be played as a descending arpeggio. Standard convention is to go from low to high, so when the composer wants to go the opposite way, it needs to be clarified.
Comment: There's also the similar upward wavy arrow for an arpeggio that must go up. I remember transcribing a video game theme that had arpeggiated piano chords and not all of them were arpeggiated the same way, so I put arrows on all the arpeggio markings.
Comment: @Dekkadeci  I think (not 100% sure) that the default, if no arrowhead, is to arpeggiate upwards.
Comment: Sure, you can go the other way as well, and would actually be especially helpful / clear if the music is constantly changing directions.


Show that solution of a Cauchy problem is not globally defined

Question: Hi everyone: I need a check on the following exercise

\begin{cases} u'(t)=\sin(t)^2 - u(t)^2 \\ u(0)=-1\end{cases}
Show that the maximal solution $u:[\alpha,\beta] \rightarrow \mathbb{R}$ is such that $\beta < \infty$

First of all, the problem is well posed: the r.h.s. of the ODE is smooth and therefore we can infer there exists a unique local solution. Then, I note immediately that $$\sin(t)^2-u^2(t) > - u^2(t)$$ for all the $t$'s for which the solution is defined
Hence $$u'>-u^2$$ and integrating from $0$ to $t$ I obtain $$\frac{1}{u(t)} + 1 < t$$ and then $$u(t) > \frac{1}{t-1}$$ again for all $t$'s such that the solution is defined. But the r.h.s explodes as $t \rightarrow 1^{-}$ and therefore we can say that the $$\beta<1$$ is necessary for the solution norm not to explode

This seems to be confirmed also numerically. Is everything okay?
Comment: No, it doesn't work.  As $t \to 1-$, $1/(t-1) \to -\infty$.  So all you have shown is that $\lim_{t\to 1-} u(t) > -\infty$.
Comment: Find an $\epsilon$ such that $v(\epsilon) > 1$.  Then use $v' > v^2 - 1$.
Comment: I think you need to step away from stack exchange, and think long and hard about this prolem.
Comment: @StephenMontgomery-Smith But if I take the modulus, I have shown that the norm explodes, right?
Comment: No.  $u(t)$ will be negative.  You cannot say $xv^2$, integrate from $0$ to $t$ and see that $|v(t)|> \frac{1}{1-t}$ and therefore it has to be $\beta <1$, right? @StephenMontgomery-Smith
Comment: No.  Because the $-\sin^2(t)$ goes the wrong way.
Comment: @StephenMontgomery-Smith right, so what I have to analyze is  $v'\frac{1}{t+1}$ Now I know that $v(t)=-u(t)$, but this doesn't seem to help @StephenMontgomery-Smith
Comment: How did you get that?  You should have got $v(t) < \frac1{1-t}$ for $0 \le t < 1$.
Comment: Anyway, the problem is much more subtle than the work you showed here.  You need to go back to the drawing board.
Comment: Yes sure, it was a typo. Btw, I don't know honestly how to move now. Could you give me a hint? @StephenMontgomery-Smith
Comment: @StephenMontgomery-Smith from $v'>v^2 -1 $ I obtain  $v(t)>1$, which implies $u(t)>-1$
Comment: First, if $v > 1$, this implies $u < -1$.  Secondly, try integrating $\int \frac{dv}{1-v^2}$.
Comment: @andereBen : You already know $u(0) = -1$ and $u'(0) = -1$, so "$u(t) > -1$" is utterly hopeless...
Comment: @StephenMontgomery-Smith by integration, I find $\frac{1}{2} \Bigl( \log(1+v) - \log(1-v) \Bigr)$, but the sign in the denominator seems changed
Comment: I think you meant $\tfrac12(\log(v+1)-\log(v-1))$.
Comment: @StephenMontgomery-Smith So, summarizing, I have $$\frac{1}{2} \Bigl( \log(1+v(t)) - \log(v(t)-1) \Bigr) > 1 $$ I see that for $v=1$ I have problems, but as you wrote,I need to think about this for a while
Answer: At $t=0$ the right side is negative. It is easy to observe, perhaps harder to formulate, that this implies that at no point the right side can become positive, $u$ is continuously falling and thus always smaller than $-1$. Then for $t\in[0,1]$
$$
u'(t)=\sin^2t-u(t)^2\le t^2-1\implies u(t)\le -1-t+\frac{t^3}3=v(t).
$$
so the solution moves decidedly away from the level $-1$ downward and
$$
u(1)\le-\frac53.
$$
Now use $\sin^2t\le 1\le -u(t)$, $u(t)^{-1}+1\ge0$ to derive a simple upper bound for the solution for $t\ge 1$,
$$
u'\le -u-u^2\implies (u^{-1}+1)'=-u^{-2}u'\ge u^{-1}+1
\\~\\
\implies
u(t)^{-1}+1\ge (u(h)^{-1}+1)e^{t-h}
$$
So in the numerically simple case $h=1$ one gets for $t\ge1$
$$
u(t)^{-1}+1\ge\frac25e^{t-1}
\iff
u(t)\le-\frac{5}{5-2e^{t-1}}
$$
This upper bound diverges to $-\infty$ at $t=1+\ln\frac52$, thus forces the solution to diverge in this direction at some time before that.
This is a rather large bound, as the numerical solution diverges shortly after $t=1$, closely following the lower bound $-\frac1{1-t}$ discussed in the question.


I am having problems reassigning a variable in python

Question: I am trying to create a text adventure game in python. I am using randint to create a number between 0 and 2 and when I use an if statement to take the random number and assign the biome variable to a biome type it instead takes the original version of the variable and uses that as the biome.
#Defines game()
print ('''You are in a %s biome.'''%(biome))
biome='placeholder'
import random
trees=random.randint(0,50)
biomes=random.randint(0,2)
animals=random.randint(0,3)
wolves=random.randint(0,5)
if biomes == "0":
    biome='Forest'

if biomes == "1":
    biome='Taiga'

if biomes == "2":
    biome='Mountain'

print ('''You are in a %s biome.'''%(biome))

Comment: The answers to your question are correct, but Python makes this even easier with [`random.choice`](http://docs.python.org/2/library/random.html#random.choice): `biome = random.choice(['Forest', 'Taiga', 'Mountain'])`
Answer: biomes is int value. "0" is string value.
Both values never can be equal.
>>> 0 == "0"
False

Use int literal.
if biomes == 0:
    biome = 'Forest'
elif biomes == 1:
    biome = 'Taiga'
elif biomes == 2: # else
    biome = 'Mountain'

I recommed you to use random.choice as other suggested. Simple, eaiser to read.
>>> random.choice(['Forest', 'Taiga', 'Mountain'])
'Mountain'
>>> random.choice(['Forest', 'Taiga', 'Mountain'])
'Mountain'
>>> random.choice(['Forest', 'Taiga', 'Mountain'])
'Taiga'

Comment: You don't need three seperate `if` conditions here. :)
Comment: it's even better as a dict. . . biome_map = {0: 'forest', 1: 'taiga', : 'mountain'} then it's just biome = biome_map.get(biomes)
Comment: @GoingTharn, `random.choice(..)` is more pythoic as other suggest.
Comment: @GoingTharn, And list/tuple is enough. (`['Forest', 'Tiaga', 'Mountain']`) Because index is continuous (0, 1, 2 only).
Answer: random.randint(...) returns an integer. You are comparing the value to a string here.
>>> type(randint(0, 2))
<type 'int'>

Your if statements should be rewritten as -
if biomes == 0:
    biome='Forest'
elif biomes == 1:
    biome='Taiga'
else:
    biome='Mountain'

P.S-- You don't need three if statements, since, if the value is 0, it can never be 1 or 2, so no need to check the conditions. You can use an if-elif-else construct instead.
Answer: Here's a more understandable way:
from random import choice
biomes = ['Forest', 'Tiaga', 'Mountain']
biome = choice(biomes)

Then if the number of biomes increases, or decreases, you don't have to worry about updating the range for the random number, and not quite getting your if statements right...
Answer: You need to compare to 0 rather than the string value"0"  as in if biome == 0:
However, this can be simplified with random.choice to select a biome randomly from a list.
biome = random.choice(['Forest', 'Taiga', 'Mountain'])

and eliminate your ifs altogether.
Answer: I think you should try in the if statement biome == 1 instead of biome == "1" and the same for  biome == 2 and biome == 3.
Answer: That's because you are comparing an integer value to a string (which will never equal).  This will work:
import random
trees=random.randint(0,50)
biomes=random.randint(0,2)
animals=random.randint(0,3)
wolves=random.randint(0,5)

# Compare biomes (which is an integer) to another integer
if biomes == 0:
    biome='Forest'

# Use elif for multiple comparisons like that
elif biomes == 1:
    biome='Taiga'

# Use an else here because the only other option is 2
else:
    biome='Mountain'

print ('''You are in a %s biome.'''%(biome))

Note also I removed the first and second lines of your script.  The first would have blown up because biome isn't defined yet and the second does nothing.


Help with hit test function

Question: I'm making a Gui where Widgets have children, and children are both clipped in the hit test, and in rendering, to the parent's rectangle. However it is not always like this. A widget can choose not to clip its children. In this case, the children are bound to the parent's parent rectangle. My rendering currently reflects this, but my hit test does not.
Here is my hit test:
<code>AguiWidget* AguiEventManager::GetWidgetUnderMouse( AguiWidget* root,
                                            const AguiMouseEventArgs &mouse )
{
    /* sets the current node to the root node
    while a widget passes the hit test
    and the current node has children,
    iterate through the current node's
    children and set the current node
    to the child who passes the hit test */

    AguiWidget* currentNode = root;

        bool foundsomething = true;
        while(foundsomething)
        {
            foundsomething = false;
            if(currentNode->getChildWidgetCount() > 0)
            for (std::vector<AguiWidget*>::const_reverse_iterator rit =
                currentNode->getChildRBeginIterator();
                rit < currentNode->getChildREndIterator(); ++rit)
            {
                if (((*rit)->intersectionWithPoint(mouse.getPosition())
                    )
                    && (*rit)->isEnabled() && (*rit)->isVisible())
                {
                     foundsomething = true;
                     currentNode = *rit;
                     break;
                }

            }

        }
        return currentNode;

}
</code>
How could I modify this to deal with (*rit)->isClippingChildren(); ?
Basically at the moment, what it does is, it finds the first widget that passes a hit test, it then digs through its children because only they can then be eligible. And it continues to do this until there are no more children to dig into, and therefore the last widget found is the correct one. This needs to change to something more like this:
If the widget is not clipping its children, then if its parent passed the hit test, we check the children of the one who is not clipping its children. If none of them pass the hit test, then we need to go back and carry on from where we were.
I have a feeling some type of queue could be useful but I'm just not sure how.
The essential result of the modification is that it would be the same outcome as if the same algorithm was used as above, except if a widget is not clipping its children, we just let its children be processed as children of the parent.
Thanks
Answer: Give your AguiWidget a hitTest, and let it recurse into its children when positive.
Then when clicking on a clipped area, the gitTest of the parent (clipping) widget will fail, and the hit test will never be performed for the clipped Widget.

Help with hit test function


Adding footer to ms word using POI api

Question: I searched a lot and getting some results in which some sample code is there but no one is working. All are either getting null pointer exception or if document is generated then at the time of opening file (.docx) giving error and displaying message
A text/xml declaration may occur only at the very beginning of innput.
I thought may be I am adding some content and then adding footer is giving some problem so I pasted my footer code at very beginning now this time I am getting

index out of bound exception

Here is my complete code
String fileName ="Book.docx";
String   folderPath=SystemProperties.get(SystemProperties.TMP_DIR)+File.separator+"liferay" + File.separator    + "document_preview";
String filePath=folderPath+File.separator+fileName;
File file=new File(filePath);
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraphOne = document.createParagraph();
paragraphOne.setAlignment(ParagraphAlignment.CENTER);
XWPFRun paragraphOneRunOne = paragraphOne.createRun();
paragraphOneRunOne.setText("Training Report");
paragraphOneRunOne.addBreak();
XWPFTable table = document.createTable();
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("No");
tableRowOne.createCell().setText("Name");
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
            if (headerFooterPolicy == null) {
                CTBody body = document.getDocument().getBody();
                CTSectPr sectPr = body.getSectPr();
                if (sectPr == null) {
                sectPr = body.addNewSectPr();
                }
                headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
                }
            CTP ctP1 = CTP.Factory.newInstance();
            CTR ctR1 = ctP1.addNewR();
            CTText t = ctR1.addNewT();
            t.setStringValue("first footer");
            XWPFParagraph codePara = new XWPFParagraph(ctP1);
            XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
            newparagraphs[0] = codePara;
             XWPFFooter xwpfFooter = null;
    xwpfFooter =  headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
 FileOutputStream fileoutOfTraining = new FileOutputStream(file);
            document.write(fileoutOfTraining);
            fileoutOfTraining.flush();
            fileoutOfTraining.close();
   downloadOperation(file, fileName, resourceResponse);

code in downloadOperation method
HttpServletResponse httpServletResponse =PortalUtil.getHttpServletResponse(resourceResponse);
BufferedInputStream input = null;
        BufferedOutputStream output = null;
 httpServletResponse.setHeader("Content-Disposition", "attachment;    filename=\""+fileName+"\"; filename*=UTF-8''"+fileName);
int  DEFAULT_BUFFER_SIZE=1024;
        try {
            input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            resourceResponse.flushBuffer();
            output = new BufferedOutputStream(httpServletResponse.getOutputStream(), DEFAULT_BUFFER_SIZE);
        } catch (IOException e) {
            e.printStackTrace();
        }
byte[] buffer = new byte[2*DEFAULT_BUFFER_SIZE];
        int length;
        try {
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

Please help me to generate footer, this is my code, if I add footer code after my paragraph and table then no run time error but error in opening generated file, if I placed footer at before the contents that I want to add in documents then I am getting error "index out of bound exception".
Please help me if any one having any code snippet or at least some pointers towards the solution.
Thanks
Answer: I faced this issue and the solution is
We have to use 3.10 final poi jar.
3.9 having this problem.
Please remove jars of previous version and add jars of 3.10 final version in which this bug is fixed.
Jars requires are:

poi-3.10-FINAL.jar
poi-ooxml-3.10-FINAL.jar
poi-ooxml-schemas-3.10-FINAL.jar

Easily available in net:
http://mvnrepository.com/artifact/org.apache.poi/poi/3.10-FINAL
XWPFDocument document = new XWPFDocument();
CTP ctp = CTP.Factory.newInstance();
CTR ctr = ctp.addNewR();
CTRPr rpr = ctr.addNewRPr();
CTText textt = ctr.addNewT();
textt.setStringValue( " Page 1" );
XWPFParagraph codePara = new XWPFParagraph( ctp, document );
XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
newparagraphs[0] = codePara;
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new  XWPFHeaderFooterPolicy( document, sectPr );
headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );

The above code is working perfectly, please use 3.10 wars those I mentioned above.
Comment: thank you very much for sharing the knowledge ,i need a little more help.I want to add an image in the header can you help me in that??
Comment: I am really happy that my post is useful for someone. I haven't add image in header, if I get free time then I will try to help you.
Answer: I don't know if adding image to header from scratch works in new version, but I know for a fact that "templating" works just perfectly. I created the template document in word, adapted the header the way I needed it to be (in my case, logo-image was on the right, paragraph with dummy text on the left, and another image that separates the upper two objects from the content, on the header bottom, and all was repeating on all the pages) and left the rest of the document empty. On the very beginning, I didn't create the XWPFDocument by calling the ...new XWPFDocument() anymore, I created it this way:
XWPFDocument doc = new XWPFDocument(new FileInputStream("pathTo/template.docx"));

Than just fill your document with your content, and if you need to update the header text for different exports like I did, call the update header function, that in my case looks something like this:
public void updateHeader() throws InvalidFormatException, IOException {
        // load the header policy from template and update the paragraph text
        XWPFHeaderFooterPolicy headerFooterPolicy = document
                .getHeaderFooterPolicy();
        XWPFHeader defaultHeader = headerFooterPolicy.getDefaultHeader();
        defaultHeader.getParagraphs().get(0).getRuns().get(0)
                .setText(profileName, 0);
        // this is only to put some space between the content in the header and the real content
        defaultHeader.getParagraphs()
                .get(defaultHeader.getParagraphs().size() - 1)
                .setSpacingAfter(300);
    }

As far as I know, this works since 3.10, and if you stumble upon some java security issues, try the current nightly version where many of these security issues were resolved. For me it even worked on Google App Engine.

Adding footer to ms word using POI api


How to get an array of selected  values in a Table

Question: I have a table with 10 columns

I am trying to loop through the NAME row to get the 4 selected names from the dropdowns.
I used to only need one, but had to add 3 more. I get one by this code
 var $tds = $(this).find('td').filter(':visible')
                name = $tds.eq(0).children().val()

I just can't work it out... GONE blank.
Any code or help would be appreciated.
Happy Holidays
Answer: You should be able to use .map
var vals = $tds.eq(0).children('select').map(function() {
    return $(this).val();
}).get();

Fiddle
Comment: You should filter using children('select') instead of children() , else you would also get the value of any other html tag within that td.
Answer: You can iterate through each select in the first td cell using $.each(). To get to the correct selector, you may use :first instead of eq(0).
var arr = [];
$('td:visible:first select').each(function()
{
  arr.push($(this).val());
});

Example : https://jsfiddle.net/DinoMyte/rv3wwpsf/1/
UPDATE : To find all select values in all rows :
var arr = [];
$('tr').each(function()
{
   $(this).find('td:visible:first select').each(function(){
     arr.push($(this).val());
  });
});

alert(arr);

https://jsfiddle.net/DinoMyte/rv3wwpsf/2/
Comment: That works great. I have another row below with 4 more and it is not finding those.
Comment: updated the code and fiddle. Follow the section in UPDATE
Comment: In my code, it shows all 12 values 3 times.
What I mean is I have 3 rows of 4 selects (so my image in the question * 3
I need to get them in groups of 4 so I can send the four to a DB and then get the next four, etc
Make sense?
Comment: Check this : https://jsfiddle.net/DinoMyte/rv3wwpsf/5/ . If you still have issues, you might need to post the html you are working with


Red Cards issued during regular time in Extra Time

Question: If one team is down to 10 players and a game goes extra time are the sides equalized after extra time starts?
Answer: No. There's only one theoretical edge case in which a team with ten players could be allowed to even up the numbers again in extra time:

A team uses up all their substitutions
They then have a player come off injured, forcing them to play with ten players since they can't substitute on a fit one
The tournament allows one extra substitution in the case of extra time (e.g. Euro 2020)

In that scenario, they could theoretically (I'm not sure whether this is actually allowed in practice) bring on a fit player to replace the injured one and get back up to eleven men.
In all other scenarios, the team with ten players would be forced to play on with ten, and their opponents would keep their numerical advantage (i.e. they wouldn't be forced to bring someone off to make it 10 v 10). As an example, the Euro 2020 match between Spain and Switzerland just finished, and the teams' numbers were not equalised in extra time.


What are the rules regarding return of serve in tennis doubles?

Question: I was playing up front in tennis doubles. The server hit a trick shot to my partner in the receiving court. The ball hit in the serve court near the center line, bounced and spun into my side. I returned the ball for what I thought was a point. Everyone else said that's not legal. I said it was legal since the ball was served per the rules, and was in play once it hit the court.
Was my return against the rules?
Answer: Yes, your return was against the rules.  The "receiver" (i.e., the player who returns the serve) is designated, and alternates with each point.  See Rule 15 in the ITF Rules of Tennis:

ORDER OF RECEIVING IN DOUBLES

The team which is due to receive in the first game of a set shall decide which player shall receive the first point in the game. Similarly, before the second game starts, their opponents shall decide which player shall receive the first point of that game. The player who was the receiver's partner for the first point of the game shall receive the second point and this rotation shall continue until the end of the game and the set. After the receiver has returned the ball, either player in a team can hit the ball.

It's not clarified further than that in the rules, but it's consistently interpreted as such.
Answer: Apparently, if it was the FIRST point of the set, your move is legal. It's been ruled that way in pro doubles matches.
"This famously happened to John Barrett, a former British tennis player and commentator. Apparently he wasn't happy.
Comment: Welcome to Sports SE. Can you add a link to the supporting rule?
Comment: Per current USTA rules (https://www.usta.com/content/dam/usta/coach-organize/content-fragments/resource-library/assets/pdfs/2023-Friend-at-Court.pdf) the receiver must be designated before the serve.  See Comment 15.1


Erro em formatação de string

Question: Estou tentando personalizar o espaçamento usado numa string formatada, centralizar pra ficar bem visual entre as linhas. O programa está me retornando erro de valor.
Segue o código:
def titulo(msg):
  tam = len(msg) + 4
  print('=' * tam)
  print(f'{msg:^tam}')
  print('=' * tam)

titulo('TRATAMENTO DE ERROS E EXCESSÕES')

O Python não aceita uma variável inteira como parâmetro pra usar no espaçamento? No caso a variável tam.
Qual seria a maneira correta pra centralizar exatamente entre as linhas, levando em consideração o tamanho delas e da própria mensagem.
Answer: Se você tem uma variável em um local que espera um literal precisa dizer que é uma variável, então da mesma forma que faz para dizer que é uma expressão a ser interpolada e não um literal de texto, tem que dizer que ali é uma expressão, esta forma é o uso das chaves nessa parte também, portanto pode usar chaves aninhadas:
def titulo(msg):
  tam = len(msg) + 4
  print('=' * tam)
  print(f'{msg:^{tam}}')
  print('=' * tam)

titulo('TRATAMENTO DE ERROS E EXCESSÕES')

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Erro em formatação de string