Single drawRect implementation across multiple UIView subclasses

Question: Across my app I have several different subclasses of UIView: UIDatePicker, UIPicker, UIButton, UITableView, UITableViewCell, UITextView, etc. etc... For each of these I'd like to add a very simple drawRect custom implementation that I have working great.
Is there a simple way to get multiple subclasses of UIView to all have the same drawRect implementation without creating a subclass and repeating the same code across each UIPicker, UIButton, etc. etc... ?
I realize the solution to this is probably to write a delegate class for UIView's layer property and do the custom drawing in drawLayer, but I thought I would ask before I go re-working my code.
Comment: FYI - you shouldn't be modifying the `drawRect:` method of any of the custom UI widgets.
Comment: You could do this at the language level via swizzling. A category clobber in the ancestor class, in addition to being a terrible, bad, no-god, horrible practice, won't work because the intervening subclasses presumably have their own implementations. The only other language-based option would be the one you mention: your own subclass just above your custom classes and below the last framework class, but then again I'm not sure that's actually possible since some of the classes you mention are `UIControl`s, and others direct descendents of `UIView`.
Comment: I'm curious as to how you are using exactly the same drawing code for such disparate UI elements.
Comment: @rmaddy I am curious what you mean. Custom implementations of drawRect in UIView and its subclasses are one of the backbones of Cocoa/Objective-C if you want to add anything to how the class draws itself. https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/drawRect:
Comment: Yes, implementing `drawRect:` for your *own* custom views if great. But Apple provided widgets are supposed to be black boxes with private view hierarchies. You shouldn't mess with how the provided widgets are drawn.
Comment: @rmaddy So is your advice to write a drawLayer method in a CALayerDelegate class and set each UIView subclass's layer.delegate to that class?
Answer: The answer seems to be no.
Furthermore, it appears that my idea for the workaround also doesn't work: I was thinking I could write a nice little class that implements the drawLayer method from CALayerDelegate and do the drawing in there, and then in each UIView or UIView subclass' init method do a self.layer.delegate = niceLittleCALayerDelegateClass.
My research, however, happened upon this: https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CALayer_class/#//apple_ref/occ/instp/CALayer/delegate which contains the damning sentence: In iOS, if the layer is associated with a UIView object, this property must be set to the view that owns the layer.
So, double nope.
Against rmaddy's advice I'm going to just write a subclass for each of the UIView subclasses I want to implement this drawing behavior in. We'll see how that goes.
Update:
I can't believe I didn't think of this before, but the "right" way to do this (that is to say without subclassing UIView's subclasses and adding a custom drawRect method to each subclass's subclass), from everything I can find, seems to be to either create a subview or a sublayer with a transparent background that does whatever custom drawing you want.
Obviously this is going to draw on top of the UIView you're actually using, so this would get exceedingly complicated if you're trying to draw things that interact with the default elements of the UIView, but for my purposes (just a simple frame drawn with a UIBezierPath) it seems to work great.
At present I'm not sure if the subview or the sublayer approach is more efficient. If anyone can shed light on that, I'd appreciate it.


Habilitei uma extensão do PHP e aparece um Warning?

Question: Habilitei a extensão php_oci8_11g.dll porém recebo o seguinte alerta.

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\php\ext\php_oci8_11g.dll' - %1 nÒo Ú um aplicativo Win32 vßlido.

Já reinstalei o PHP várias vezes, mas o erro continua. Alguém sabe o que pode ser?
Obs: Estou usando Windows 10 de 64 bits e o meu PHP está na versão 5.6.30.
Comment: O seu PHP é versão?
Comment: Vou colocar na pergunta
Comment: Você está instalando o PHP através de algum pacote (xamp, wamp, etcc) ou de forma nativa? O PHP é x86 ou x64?
Comment: @GabrielHeming nativo e x86
Comment: Se adicionar no google apenas o nome da DLL, encontrará inúmeros resultados para o seu problema. Três links apenas do stack overflow: http://stackoverflow.com/questions/38709005/php-oci8-11g-dll-is-not-a-valid-win32-application
http://stackoverflow.com/questions/28460945/php-oci8-unable-to-load-not-a-valid-win32-application
http://stackoverflow.com/questions/20825405/php-warning-at-startup-while-trying-to-load-php-oci8-dll
https://blogs.oracle.com/opal/entry/using_php_oci8_with_32-bit_php
Comment: @GabrielHeming preciso que seja nessa versão, a segunda resposta não responde a pergunta.
Comment: Todos falam a mesma coisa, procure pela DLL 32 bits compilada no VC11. É provável que esteja utilizando uma em outra
Comment: @GabrielHeming estou usando a de 32 bits
Answer: Resolvi, tive que reinstalar o Oracle Client, baixei uma versão com Thread Safe do PHP e a seguinte DLL.


Calculating the second order partial derivatives of $z(x,y.)$.

Question: If we know that $z_{x}^{'} = \frac{yz}{z^{2} - xy },$, how can I calculate the second order partial derivative with respect to x, knowing that the final answer should be (as given at the back of the book) $z_{xx}^{''} = \frac{2xy^{3}z}{(z^{2} - xy)^3 },$. could anyone explain to me how to do it? I do not know from where the power 3 in the denominator came.
Comment: This is a bit strange; you want to find _"the second order partial derivative with respect to $y$"_ but you refer to an answer for $z_{xx}^{''}$, which looks like a second order derivative with respect to $x$...? Do you have $z(x,y)$ as well? Please include all relevant information.
Comment: I am sorry I will fix this mistake @StackTD
Answer:
If we know that $z_{x}^{'} = \frac{yz}{z^{2} - xy }$, how can I calculate the second order partial derivative with respect to x

Take the partial derivative with respect to $x$: use the quotient rule and don't forget that $z$ is a function of $x$ (and $y$). This will then contain the first partial derivative $z'_x$ again, but you can substitute that with:
$$z_{x}^{'} = \frac{yz}{z^{2} - xy }\tag{$*$}$$
and then simplify.

Here's a start:
$$\begin{align}z_{xx}^{''}=\frac{\partial}{\partial x}z_{x}^{'}
& =\frac{\partial}{\partial x}\left(\frac{yz}{z^{2} - xy }\right) \\[6pt]
& =\frac{\left(z^{2} - xy\right)\color{red}{\frac{\partial}{\partial x}\left(yz\right)}-\left(yz\right)\color{blue}{\frac{\partial}{\partial x}\left(z^{2} - xy\right)}}{\left(z^{2} - xy\right)^2 } \\
& = \ldots
\end{align}$$
Now $\color{red}{\frac{\partial}{\partial x}\left(yz\right)}=yz_{x}^{'}$ and use $(*)$ for $z_{x}^{'}$ and don't forget the chain rule for $\color{blue}{\frac{\partial}{\partial x}\left(z^{2} - xy\right)}$ and you'll be able to use $(*)$ once again to eliminate $z_{x}^{'}$.


Expressing a block matrix using Kronecker product

Question: Let $A=[a_{ij}]$ be an $m \times m$ matrix  and $B$ be a $nm \times nm$ block diagonal matrix with diagonal blocks $B_i$, $i=1, \ldots, m$, $n \times n$ matrices. I want to express
$\left[
\begin{array}[cccc]
\\a_{11} B_1 & a_{12}B_1 & \cdots & a_{1m} B_1 \\
a_{21} B_2 & a_{22}B_2 & \cdots & a_{2m} B_2 \\
\vdots & \vdots & \vdots & \vdots\\
a_{m1} B_m & a_{m2}B_m & \cdots & a_{mm} B_m \\
\end{array}\right]_{mn \times mn}$
in a compact form, possibly in one shot using Kronecker products. Is it possible?
Answer: Let $e_k$ be the $k$-th column vector of the standard basis of $\mathbb{R}^m$ and $I_n$ the $n \times n$ identity matrix. Thus we can write
$$ \sum_{k=1}^{m} (e_k \otimes I_n)((e_k^T A) \otimes B_k) \tag{1} $$
Lets see how we construct this expression.
The term $(e_k^T A)$ is just the $k$ row of $A$
$$ (e_k^T A) = \left[ \begin{matrix} a_{k1} & \cdots & a_{km} \end{matrix} \right]_{1 \times m} $$
Hence
$$ (e_k^T A) \otimes B_k = \left[ \begin{matrix} a_{k1}B_k & \cdots & a_{km}B_k \end{matrix} \right]_{n \times mn} $$
Then we use
$$ (e_k \otimes I_n) = \left[ \begin{matrix} 0 \\ \vdots \\ I_n \\ \vdots \\ 0 \end{matrix} \right]_{mn \times n} $$
to "immerse" $(e_k^T A) \otimes B_k$ as the $k$-th row of a $mn \times mn$ matrix
$$ (e_k \otimes I_n)((e_k^T A) \otimes B_k) =
\left[ \begin{matrix}
0 & \cdots & 0 \\
\vdots & \vdots & \vdots \\
a_{k1} B_k & \cdots & a_{km} B_k \\
\vdots & \vdots & \vdots \\
0 & \cdots & 0 \\
\end{matrix} \right]_{mn \times mn} $$
And then finnaly we add up all these $m$ matrices.
Now we can use the Kronecker product "mixed-product" property to simplify $(1)$ as
$$ \sum_{k=1}^{m} (e_k \otimes I_n)((e_k^T A) \otimes B_k) = \sum_{k=1}^{m} ((e_k e_k^T A) \otimes (I_n B_k)) = \sum_{k=1}^{m} (e_k e_k^T A) \otimes B_k \tag{2} $$


Which is better: using a map inside array list or a pojo class to interact with json response

Question: I'm a bit confused, as from a long time i am saving the json response directly to an ArrayList> and displaying to my listView, but now, looking on other people code i noticed that they are using POJO class to interact with JSON, Is it is better way? if it is please explain why? cause using POJO means I have to write extra code, But if saving the response directly to the arraylist make my work done, then why should i use a POJO class?
Answer:
So, Pojo usage better due to OOP pattern, because you work at runtime with your Java object without intermediate Json parse. Manual json parsing too ugly due to code style(its my opinion).

But if saving the response directly to the arraylist make my work done

If, you collect your object in Maps, you can apply different features out of the box(sort, compare etc) to your map, but in case when your map contains POJO instead of JSONS.

Encapsulation. When you work with dates for examples or with type, its pretty good to use getters/setters for data mapping instead of manual parsing again and again.

4.Object scaling and mapping:
 Lets image that we have some object user:
public class User{
  int id;

  @SerializedName("specific_id_for_blah_blah")
  private int mSpecId

  @SerializedName("date_of_birthaday")
  private String mBDay;

  public Date getBirthday() {
    return new Date(mBDay);
  }
}

What I want to say by this example.

You can map your json to POJO with one line of code only
User user = new Gson.fromJson(response, User.class);
Pretty simple isn't?.
Name serialization. When your response contain key name which looks to long or weird, you can use your own style naming with easy changes, just with small annotation. mSpecId returns value of "specific_id_for_blah_blah"
Platform specific encapsulation. You can use only platform specific object at your runtime, instead parsing operations in your business logic. String with data -> Date or Calendar
Also you can override Object methods in your POJO (equals, hashcode, toString) for your logic spec. operations.
If your serverside change some key you can change name of key in POJO instead looking through where you parse it before. IN same case you can add new field and setter/getter, if some of parameter will be added to your response
Comment: Can you explain a bit more about the serialization part.
Comment: What do you mean under "serialization part" ? Common principles of serialization or annotation @SerializedName?
Comment: I mean How the serialization is implemented here as I can't get how serialization is happening here
Comment: This annotation means that object which will be mapped to field has alternative name/s. Gson parser look through your Json object and get primitive or complicated type. Before getting the object it looking for your variable name. If this name equal to Json key, parser map value to this name, if not, it looking for alternative names which has this annotation. For example if your Json use underline separation, but in code you use camel text, or 'm' suffix as member declaration, you can use this annotation, in opposite case use variable names the same as in Json(camel or underlined ).
Comment: By the way, more details your can find in https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html documentation
Comment: And the last things:
If your Json value has array value -> Gson map it as List. If your Json value has another complicated json object -> Gson map it as another POJO object. Try this service http://www.jsonschema2pojo.org  Create some complicated Json and look through generated POJOs, classes. May be it more understandable. So, if my answer was helpful, left the vote please)
Answer: There is no right and wrong answer here. It all depends on your use case. If your solution works, and you are happy with it, I don't see why do you need to change it.
If I had to choose, I would go with a POJO class to represent the response, but this is a subjective opinion. I think that you have the following benefits:

It's cleaner - having a separate, dedicated class to represent your payload gives you the ability to be more specific in your code. You are no longer manipulating Maps of key - value pairs, but instances of a specific class, that can have a more specific behaviour. You can specify natural ordering, criteria for equality, etc - things that may be useful for your program's logic
It's simpler - I would prefer calling a getter every time then accessing a map by a property name and getting an Object back. The logic of the program will be much simpler and safer.
It's better in terms of OOP best practices - the whole point behind OOP is to have objects, that define properties and behaviours. IMHO, using POJOs to represent responses forces you to adhere more closely to best practices.

There are also some cases that will fit the no - POJO approach better - for example, if you only display your data, not manipulating it in any way inside the app. Or if you want to shave off some time for the complex parsing that may be needed if you are trying to inflate object hierarchies.
My best suggestion is - profile your app, check your use cases and make an educated decision which approach is better.


Raphaeljs: Why is paper.getFont() undefined? Cufon.replace() works

Question: I'm using Raphaeljs and I'm trying to get paper.print() to work in a .js-file. I've Cufonized a font and imported the .font.js file into the html-file. In the html-file, Cufon.replace('h1') works (since text with this tag in the body use the font) but I can't get paper.print() to work in my .js file.
According to the .font.js-file the font family is "Champagne & Limousines", so I'm trying to get the font by calling
paper.getFont('Champagne & Limousines')

An alert shows that the result of the getFont-call is undefined. I try to print letters by doing the following:
var letters = paper.print(100, 100, "STRINGSTRING", paper.getFont('Champagne & Limousines'), 40);

This does nothing. I've done some other things in the javascript file, so I know there's nothing wrong with paper, nor with including the javascript file in the html file.
What am I doing wrong?
Comment: Could it be the ampersand? If you rename the font to Champagne does that work? If so perhaps you need to write & as & in the getFont call.
Comment: I changed the "font-family" attribute to "Champagne" (for one of the different kinds of fonts) in the .font.js file, but
alert(paper.getFont('Champagne'));
unfortunately still returns "undefined" and the print still doesn't work. Thanks for trying though.
Answer: Please download the latest version of Raphael.That solved this for me.


inject js to head (with full-code in script)

Question: I want to add a script to the head of a site so the the head of the target html looks like so .

With this script works that perfect:
var head = document.getElementsByTagName('head')[0],
    script = document.createElement('script');

script.src = 'http://www.example.com/example.js';
head.appendChild(script);

But i don't want to use any link in source.
So i'm tried to add some code like this:
    function addJS(jsCode) {
    var styleElement = document.createElement('script');

    styleElement.type = 'text/javascript';

       (scriptElement.javascript) {
        scriptElement.javascript.jsText = jsCode
        scriptElement.appendChild(document.createTextNode(jsCode))

    document.getElementsByTagName('head')[0].appendChild(scriptElement);
}

var jsCode = '';
jsCode += 'code';
jsCode += 'some more code';

But I've failed. That script is not working.
How can I add a  Element to the head of any html site like this?
Would be great if someone could help me.
Comment: To clarify, you want to dynamically add javascript from an external file to the head of an html document?
Comment: Are you using jquery? Also, is the javascript source in the same domain as the site?
Comment: I don't prefer to use jquery, but if there no other way to do this I also suppose that.
Answer: Just tried this and it seemed to work. Try
function addJS(jsCode) {
    var s = document.createElement('script');

    s.type = 'text/javascript';
    s.innerText = jsCode;
    document.getElementsByTagName('head')[0].appendChild(s);
}

Demo here
Comment: Thank you, but how I could add a script with more than on line & funtion & some "" in it?
Comment: @Michael Updated my fiddle. Take a look.
Comment: Thank you very much, but I try this and it dosen't work. http://jsfiddle.net/dF445/ (The shortcut.js for this script is already in the page...)
Comment: @Michael What is shortcut by the way. No such object exists in the window object
Comment: Thats just a example with "" in it... I only to make sure that the script whichs writes the code to the head accepts also "" in the code.
Comment: @Michael updated my example. If your string is wrapped in double quotes remember you can only use single quotes within you javascript code. Or vice-versa, if you wrap the code in single quotes you can only use double quotes inside your string.
Comment: Thank you for the update, the code works. But the target site keep on relaodloading when script is enable. (I add it with a userscript.)
Comment: I think I only should add a if arry to the script which check if the code is injected, but with my limited Javascript knowledge I don't really know how to do this. Can you help me?
Answer: Using jquery
   var head = document.getElementsByTagName('head')[0],
        script = document.createElement('script');

    $(script).attr('type' , 'text/javascript');
    head.appendChild(script);
    $(script).append("alert('Hello')");


calling different package and choosing the correct one

Question: I have to switch from first apk to second apk and that i have done successfully. But the problem is I have to choose between multiple package. If the package is correct then application should switch. So for that i tried to put multiple package names in string and calling in intent but it is going in else part only.
The code snippet is:
i initialise a string variable
String value="com.android.example";

and passing here in intent
intent = pm.getLaunchIntentForPackage(value);

When I run the apk, it is not accepting the any value even the correct package and going in else part. Please give me suggestions for the same and kindly let me know if i can do the same through any other method.
Comment: Your question isn't very clear.
Comment: The question is simple as that I have to choose the correct package between multiple packages using if else and if the package chosen is correct then the further action should be done.But i am getting the problem in choosing the correct package because through package manager I am only able to know the current apk package. How that it can identify the other package name installed on device? So this is the prob and I am not able to identify
Answer: Use PackageManager to check if packages you look for do exist on this device and then act accordingly to the results you obtained from the check.
Comment: yes i have checked through package manager also. But not working
Comment: the prob is it is not recognising the package.
Comment: Well, I quite doubt so and suspect you doing something wrong (or I missed your point). Show your code. If your package is there, you installed it w/o any troubles, then I see no reason PackageManager can't see it. That'd be odd, as PackageManager was already involved when you installed the package
Comment: yes that needed for the testing purpose. So i got the solution that now i an entering package name in edit text and if it is correct then it can invoke the other application. Now its working fine.


Do I need to do StreamWriter.flush()?

Question: Suppose this C# code:
using (MemoryStream stream = new MemoryStream())
{
    StreamWriter normalWriter = new StreamWriter(stream);
    BinaryWriter binaryWriter = new BinaryWriter(stream);

    foreach(...)
    {
        binaryWriter.Write(number);
        normalWriter.WriteLine(name); //<~~ easier to reader afterward.
    }

    return MemoryStream.ToArray();
}

My questions are:

Do I need to use flush inside the
loop to preserve order?
Is returning MemoryStream.ToArray() legal? I using the using-block as a convention, I'm afraid it will mess things up.
Answer: Scratch the previous answer - I hadn't noticed that you were using two wrappers around the same stream. That feels somewhat risky to me.
Either way, I'd put the StreamWriter and BinaryWriter in their own using blocks.
Oh, and yes, it's legal to call ToArray() on the MemoryStream - the data is retained even after it's disposed.
If you really want to use the two wrappers, I'd do it like this:
using (MemoryStream stream = new MemoryStream())
{
    using (StreamWriter normalWriter = new StreamWriter(stream))
    using (BinaryWriter binaryWriter = new BinaryWriter(stream))
    {
        foreach(...)
        {
            binaryWriter.Write(number);
            binaryWriter.Flush();
            normalWriter.WriteLine(name); //<~~ easier to read afterward.
            normalWriter.Flush();
        }
    }
    return MemoryStream.ToArray();
}

I have to say, I'm somewhat wary of using two wrappers around the same stream though. You'll have to keep flushing each of them after each operation to make sure you don't end up with odd data. You could set the StreamWriter's AutoFlush property to true to mitigate the situation, and I believe that BinaryWriter currently doesn't actually require flushing (i.e. it doesn't buffer any data) but relying on that feels risky.
If you have to mix binary and text data, I'd use a BinaryWriter and explicitly write the bytes for the string, fetching it with Encoding.GetBytes(string).
Comment: It affects the order in which the values may be written though - unless you set AutoFlush to true, StreamWriter may not write anything to the MemoryStream for a long time (or *ever* if you don't dispose it). It just feels brittle to me.
Comment: @Nefzen - see Environment.NewLine http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx
Comment: Wrapping one stream with two stream writers does seem dangerous/error prone though I don't think flushing them will do anything in this case. Flush doesn't affect the reading of the MemoryStream, only the writing of the buffered bytes into their respective streams.
Comment: the thing is, I want a newline at the end of the the name, and WriteLine seems the safe way to so so.
Comment: "Flush doesn't affect the reading of the MemoryStream, only the writing of the buffered bytes into their respective streams" .... but that's exactly what the OP is doing... writing.
Comment: @dss539 - but will that be read when using readline every time?
Comment: @Nefzen: Using ReadLine is going to be dodgy with a StreamReader anyway, if you're mixing it with binary data. ReadLine will read into an internal buffer, consuming some of that binary data. Mixing text and binary data without a well-defined container (e.g. length-prefixing the text having indicated that there *will* be text) is always tricky.
Comment: binary data is constant in length - 32 bit.
I came at a new problem - in the other side, I want to read the line, yes? well, if I use StreamReader, I'm not sure what encoding it is using, and if I use BinaryReader, I need to find the end of line. Hmm, maybe I should use '\0'.
Comment: @dss539 the buffer will be filled in the correct order so flushing or not, the bytes will be written in the correct order.
Answer: Update
Nevermind this answer, I got confused with the writers...

No, the order will be preserved (update: maybe not). Flush is useful/needed in other situations, though I can't remember when.
I think so, using makes sure everything cleans up nicely.
Comment: I don't think the order *will* necessarily be preserved, between the binary writer and the stream writer here - you may end up with a load of values from the binary writer and then the next buffer's worth of the stream writer.
Comment: 1. No the order won't be preserved.
2. No the `using` does not `Dispose()` normalWriter or binaryWriter.
Comment: Both writers share the same buffer?
Comment: @Crossbrowser: No - the BinaryWriter doesn't know about the StreamWriter or vice versa. The StreamWriter has its own buffer.
Comment: Dam, I was so confused, I kept focusing on the writer part not thinking that one of the writers took his source from what the other wrote in the stream. In that case, I think only the first flush is necessary.

Do I need to do StreamWriter.flush()?


How to show basic page without summary?

Question: So I've got a basic page 'home' I want to use as my homepage. But when I make one and publish it to front page, I only see a summary, like it's an article. And if I don't publish it to front page, it's just not there, even with homepage link setup.
So basically I want text on my front page without the "read more" button, just the full text.
Answer: Go to Configuration > Site Information. Under the Front Page section, change FRONT PAGE to include your node information - meaning set the path you want to show as front page and then click save. see the below screenshot.

If you made the above settings then it will show the new front page without summary.

How to show basic page without summary?


Save logs from form into a txt file

Question:

form {position: absolute; left: 45%; top: 35%;}
#email {position: relative;left: 30%;bottom: 90%;text-shadow:1px 1px #D8E3EC;color: #097BDA;}
#password {position: relative;left: 25%;bottom: 100%;text-shadow:1px 1px #D8E3EC;color: #097BDA;}
#submit {position: absolute;bottom: -30%;left: -30%;text-shadow:1px 1px #D8E3EC;padding: 0.5% 25%;border-radius: 2px;background-color: #31A1FF;border-width: 4px;border-color: #0468BB;}
#submit:hover{background-color: #67BAFF;}
#eee {border-radius: 5px;}
#ppp {border-radius: 5px;}
#titlu {position: absolute;left: 31.5%;text-shadow:2px 2px #F9FBFC;font-family: fantasy;color: #097BDA;}
body {background-image: url(background.jpg);}
#tran {opacity: 0.9;position: absolute;left: 37%;top: 20%;;width: 30px 30px;}
<!DOCTYPE HTML>

<title>Website</title>
<link rel="stylesheet" type="text/css" href="styles.css">

Welcome,please login to get free games right now!

<form class="formm" action="form.php" method="get">

Email

<input id="eee" type="email" placeholder="Put your email here">

Password

<input id="ppp" type="password" placeholder="Put your password here">

<input id="submit" type="submit" value="GET YOUR FREE GAME NOW!">

</form>

So I want to add something like - when I put my email and password and press submit button, to get the logs into another file, like logs.txt.
Comment: Is it ok if I give you a PHP solution?
Comment: Yes,i'm kinda newbie,but maybe i'll get it done
Comment: Maybe you never used PHP before, remember that you need a server installed on your computer. I hope this answer helped you!
Answer: In PHP is really simple creating files and writing something into them. If you want write a log every time someone submits your form, you just need to call this function :
<?php
function write_log($string) {
    $log_file = 'log.txt';
    $string .= PHP_EOL;
    if ($fh = @fopen($log_file, "a+")) {
        fputs($fh, $string, strlen($string));
        fclose($fh);
        return true;
    } else {
        return false;
    }
}
?>

Naturally it must exists a file called 'log.txt' to write in. If it extists, you just need to call this function setting your log content as the string parameter. Here is an example :
<?
//Write "Hello World" into your log.txt file.
write_log("Hello World");
?>

What does PHP_EOL do?
PHP_EOL is a constant the simply find the best method to break a line in the system you're using. So that you can insert multiple lines formatted in a great schema without do anything.
References
http://php.net/manual/en/reserved.constants.php
http://php.net/manual/en/function.fputs.php
Answer: Javascript can't write to a log.txt file unless you use scripting.FileSystemObject which is an ActiveX and runs with IE only. I would suggest to use console.log() to make it happen or call a webservice to write the log in other end.
Update: If you are flexible, nodeJs can provide you a solution with filesystem
var fs = require('fs');

fs.appendFile('log.txt', 'Log text data to append', function (err) {
  if (err) throw err;
  console.log('Log updated');
});

Save logs from form into a txt file


how to add images to mysql database when a user submit their images

Question: I want to add multiple images into mysql database using a form. Whenever a user submits that form then it captures all data and stores that into mysql database. (it is right way, but i need)
My database table is looking like this.
CREATE TABLE `Owner_detail` (
  `id` int(10) NOT NULL auto_increment,
  `fullname` varchar(30) NOT NULL,
  `List1` varchar(20) NOT NULL,
  `List2` varchar(20) NOT NULL,
  `List3` varchar(20) NOT NULL,
  `area` varchar(30) NOT NULL,
  `ownermobile` varchar(20) NOT NULL,
  `email` varchar(20) NOT NULL,
  `image_one` blob NOT NULL,
  `image_two` blob NOT NULL,
  `image_three` blob NOT NULL,
  `otherdetail` varchar(300) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=49 ;

My html form is looking like this.

<form action="process.php" method="post" enctype="multipart/form-data" name="tripleplay" onsubmit="MM_validateForm('fullname','','R','area','','R','ownermobile','','RisNum','email','','RisEmail','otherdetail','','R');return document.MM_returnValue">

    Full Name :
    <input size="25" type="text" name="fullname" id="fullname" />

    Rental Type:

    <select name='List1' id="List1"     onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Make a Selection</option>
</select>

<select name='List2' id="List2" onchange="fillSelect(this.value,this.form['List3'])">
  <option selected>Make a Selection</option>
</select>

<select name='List3' id="List3" onchange="getValue(this.value,     this.form['List2'].value,
this.form['List1'].value)">
      <option selected>Make a Selection</option>
    </select>

    Area :
    <input size="25" type="text" name="area" id="area" />
  sq.ft.

    Owner Mobile / Landline
    <input size="25" type="text" name="ownermobile" id="ownermobile" />

E-mail

    <input size="25" type="text" name="email" id="email" />

    Pictures of Property

       <input type="file" name="image_one" id="image_one" />

        <input type="file" name="image_two" id="image_two" />

        <input type="file" name="image_three" id="image_three" />

    Other details you would like to share about your property:
    <textarea size="25" name="otherdetail" id="otherdetail" cols="45" rows="5">    </textarea>

    <input type="submit" name="submit" id="submit" value="Submit" />

</form>

and my processing form in php is looking like this
<?
if( $_POST )
{
  $con =     mysql_connect("","","");

  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("vkrental", $con);

  $users_fullname = $_POST['fullname'];
  $users_area = $_POST['area'];
  $users_List1 = $_POST['List1'];
  $users_List2 = $_POST['List2'];
  $users_List3 = $_POST['List3'];
  $users_ownermobile = $_POST['ownermobile'];
  $users_email = $_POST['email'];
  $users_image_one = $_POST['image_one'];
  $users_image_two = $_POST['image_two'];
  $users_image_three = $_POST['image_three'];
  $users_otherdetail = $_POST['otherdetail'];

  $users_fullname = htmlspecialchars($users_fullname);
  $users_area = htmlspecialchars($users_area);
  $users_List1 = htmlspecialchars($users_List1);
  $users_List2 = htmlspecialchars($users_List2);
  $users_List3 = htmlspecialchars($users_List3);
  $users_ownermobile = htmlspecialchars($users_ownermobile);
  $users_email = htmlspecialchars($users_email);
  $users_image_one = htmlspecialchars($users_image_one);
  $users_image_two = htmlspecialchars($users_image_two);
  $users_image_three = htmlspecialchars($users_image_three);
  $users_otherdetail = htmlspecialchars($users_otherdetail);

  $query = "
  INSERT INTO `vkrental`.`Owner_detail` (

`fullname` ,
`area` ,
`List1` ,
`List2` ,
`List3` ,

`ownermobile` ,
`email` ,
`image_one` ,
`image_two` ,
`image_three` ,
`otherdetail`
)
VALUES ( '$users_fullname',
        '$users_area', '$users_List1','$users_List2','$users_List3',     '$users_ownermobile', '$users_email',     '$users_image_one','$users_image_two','$users_image_three', '$users_otherdetail'
        );";

  mysql_query($query);

  echo "
Success.
";

   mysql_close($con);
}
 ?>

My Problem is when ever I am inserting images from mysql database it stores successfully.
but when i am doing that from my html form it is not storing images. it is storing only data(text).
I don't know what is the actual error in my forms.
Comment: My suggestion would be to upload the images in a particular folder and storing their `URL`s in the database (as `varchar`) and not directly as `blob` data type.
Comment: This is not how file uploads work. See http://php.net/manual/en/features.file-upload.post-method.php
Comment: @Kevin adding some code and send reply how it is possible
Comment: htmlspecialchars() is not the correct way to escape data so it can be stored in a database. Also note that all `mysql_` functions are deprecated.
Answer: I wonder what using htmlspecialchars() for binary data would do.
$users_image_one = htmlspecialchars($users_image_one);
$users_image_two = htmlspecialchars($users_image_two);

[Edit:]
htmlspecialchars() is used to preserve special characters of text data. However, if you use it for binary data, it would mess up everything.
Troubleshoot them yourself:
You can try to find out the problem by first just uploading only the images.
Also have a look at this link : File upload using POST method
Comment: There's plenty more stuff he needs to do than that. He's not dealing with the uploaded files at all
Comment: @user2481198 Sorry, my mistake. Edited my answer.
Comment: @KevinPaladin     $users_image_one = htmlspecialchars($users_image_one);
    $users_image_two = htmlspecialchars($users_image_two); if i doing same procedure with this code it is running. if i remove this code also it is running. but images are not in both ways.
Comment: @KevinPaladin i think the problem is form action="process.php" i am using but some others are says action="" then what i am suing now?
Comment: @user2481198 as suggested by Pekka , I would suggest you to have a look at this link first http://php.net/manual/en/features.file-upload.post-method.php :)
Answer: Does not sound like there is an error . . . .
You don't store the actual images in your database, but rather just their name, or a reference to the images
e.g. product_one.jpg
Then when you want to display it you would do something like
<img src=" <?php $echo \images\$users_image_one ?> ">


What module do I turn off to hide or remove the voting widget in Drupal Commons?

Question: Our client wants this voting widget turned off? At worst, I could hide with CSS but I'd like to turn this off. What module produces this? Should I remove/hide a field from the content type?
Answer: Nevermind. I found it was the Rate module.


How may I fix my error prone on_foo_bar slots

Question: I have eight list widgets in a tab widget. They have similar names, and Designer's "Go to slot" mechanism has made links to slots it names (in the "private slots" section of "mainwindow.h") like:
<code>void on_SR0listWidget_itemClicked(QListWidgetItem *item);
</code>
I saw warnings that "Slots named on_foo_bar are error-prone," and now I need to change their names in order to discover if that's the cause of the weird behaviour I'm getting.
I tried simply refactoring the names, but that stopped the slot code from working. I used Designer's graphical "Edit Signal/Slot" mechanism and was able to connect a newly added list widget's "itemClicked(QListWidgetItem *item)" signal to a newly added slot, and it looks OK in the graphical representation, but there's no debug message (that I set up in the Slot function) when an item is clicked.
I also use those widgets' "entered" signals, so there will be at least 16 to fix. I would write a script if it could be done by parsing the relevant files.
One example of exactly how to rename one of my replacement slots and connect an "item clicked" or "entered" signal to it (and where it should go) would be a great help.
Comment: I understood nothing from your explanation nor did I find what you are asking...
Comment: How can I rename or replace that slot and connect a signal from a listWidget to it?
Comment: If you generate slots via the Creator and then change the names in the code, this will lead to problems. I think that's where the problem comes from.
Comment: BanAnn You're right. I tried refactoring the names and the slots stopped getting the signals. The warnings I saw in mainwindow.h, about the on_foo_bar names, kind of implied that changing the names would get rid of the warnings.
Answer: Signals/slots setup through the designer rely on the names of the widgets involved. This can lead to problems if the widget names are changed. There are times when using the designer method will lead to code that compiles but doesn't actually make the connections you expect. This is why you are getting that warning.
You can get more reliable behavior by connecting the signals and slots programmatically. For example, let's say you have a class header such as:
<code>#include <QMainWindow>

namespace Ui {
class MyWindow;
};

class QListWidgetItem;

class MyWindow : public QMainWindow {
   Q_OBJECT
public:
   explicit MyWindow(QWidget* parent = nullptr);
   ~MyWindow() override;

private:
   void handleItemClicked(QListWidgetItem* item); // this is your slot

   Ui::MyWindow* ui;
};
</code>
You can connect the signal/slot together in the cpp file like this:
<code>#include "MyWindow.h"
#include "ui_MyWindow.h"

#include <QDebug>

MyWindow::MyWindow(QWidget* parent)
   : QWidget(parent),
     ui(new Ui::MyWindow()) {
   ui->setupUi(this);

   // connect() has many overloads, but in this case we are passing:
   // 1. the object emitting the signal
   // 2. the signal being emitted
   // 3. the object whose slot we want to call
   // 4. the slot to connect to
   connect(
      ui->listWidget, &QListWidget::itemClicked,
      this, &MyWindow::handleItemClicked);
}

MyWindow::~MyWindow() {
   delete ui;
}

void MyWindow::handleItemClicked(QListWidgetItem* item) {
   qDebug() << "item clicked";
}
</code>
You can still use the designer to layout your UI - but prefer to manage connections directly in code rather than through the designer.
Comment: Dean thank you for a perfect answer. Not only did it give me exactly the necessary syntax for the connection, but also an understandable explanation of the problem.
Comment: So why does the QT designer give the ability to (even today) do the slot creation using the designer part of Qt designer and then give a warning? I mean, if it is going to give a warning, why even let the user do this in the first place?


Mongoose find filtering by attached document

Question: I am struggling with a query using mongoose and nodejs. I am trying to get all the bookings from a provider, this provider is related to the bookings Doc by the package Doc.
I have this booking schema:
const bookingSchema = new Schema( {

    package: {
        type: Schema.Types.ObjectId,
        ref: 'Package',
        required: [ true, 'A reference to a package must exist']
    },

    requesters: {
        type: Number,
        default: 1
    },

    status: {
        type: String
    },

});

And this is the package schema:
const packageSchema = new Schema( {

    title: {
        type: String
    },

    profile: {
        type: Schema.Types.ObjectId,
        ref: 'Profile',
        required: [ true, 'A reference to a profile must exist']
    },

    service: {
        type: Schema.Types.ObjectId,
        ref: 'Service',
        required: [ true, 'A reference to a service must exist']
    },

});

Now I am trying to get all the booking for this provider with the profile and service related:
 const filter = {
        $and: [
        {"package" : { $exists: true } },
        {"package.profile": ObjectId(profile._id)}
        ]
    };

return Booking.find( filter )
            .populate({
                path: 'package',
                match: {'profile' : { $exists: true}},
                model: 'Package',
                select : 'profile service',

                populate : [
                    {
                    path : 'profile',
                    model: 'Profile',
                    select : '_id name user'

                    },
                ]
            })
            .populate(
                {
                    path : 'service',
                    model: 'Service',
                    select : '_id'
                }

            )
            .sort( { date: -1 } )
            .exec();

But I get an empty array, not results. This is the query I can see in the console.
Mongoose: bookings.find({ '$and': [ { package: { '$exists': true } }, { 'package.profile': ObjectId("5f2a668ccee9bd8fd7a75d29") } ]}, { sort: { date: -1 }, projection: {} })
bookings []

I ONLY need the bookings for this provider, where the profile._id is equal to the provider profile I pass to the find method.
Many thanks in advance.
Answer: finally I solved it doing this:
 const packages = await Package.find({'profile' : profile._id}).select('_id').exec();

    const ids: any = packages.map( (pkg: any) => {
        return pkg._id;
    });

 return Booking.find( {'package': {$in: ids}} ) .....

Is there another better solution?


Filtro Sqlite como erro no retorno da data com a função strftime

Question: Olá estou com o erro no seguinte código
SELECT L.*, C.DESCRICAO AS CATEGORIA , CASE WHEN L.TIPO_LANCAMENTOS = 'C' THEN 0 ELSE 1 END AS ICONE
FROM LANCAMENTOS L JOIN CATEGORIAS C ON(C.CODIGO = L.COD_CATEGORIA)
WHERE strftime('%m', L.DATA) = '10'
AND strftime('%Y', L.DATA) = '2016'

O select funciona perfeitamente já rodei essa query e está correta o problema começa exatamente no where que é de suma importância essa condição para o meu filtro. Acredito que com esse código era para estar trazendo todos os registros do mês 10 e ano de 2016, porém nada acontece. Tentei fazer essa mudança.
SELECT L.*, C.DESCRICAO AS CATEGORIA , CASE WHEN L.TIPO_LANCAMENTOS = 'C' THEN 0 ELSE 1 END AS ICONE
FROM LANCAMENTOS L JOIN CATEGORIAS C ON(C.CODIGO = L.COD_CATEGORIA)
WHERE strftime('%m', L.DATA = '10')
AND strftime('%Y', L.DATA = '2016')

Alterei a posição do fechamento dos parenteses, porém desse modo ele não executa o filtro e acaba trazendo todos os registros da tabela de todos os meses e de todos os anos e não é isso o que quero. Desde já agradeço a ajuda.
Comment: Se vc montar o SQL assim:
`SELECT strftime('%m', L.DATA) AS MES, strftime('%Y', L.DATA) AS ANO FROM LANCAMENTOS L JOIN CATEGORIAS C ON(C.CODIGO = L.COD_CATEGORIA)`
Qual será o retorno?
Comment: Dessa forma não tentei, mas eu preciso trazer todos os campos dessa tabela, a data seria apenas para executar o filtro
Comment: Sim, entendi isso. Mas o retorno do `SQL` nos ajudará a ver como corrigir o filtro. Podes nos informar o resultado desse `SQL` que te sugeri?
Comment: fiz isso que você falou ele retorna NULL nos campos MES e ANO creio que não está conseguindo encontrar os valores
Comment: Aí está o problema... o campo `L.DATA` é do tipo `Date`? Talvez você precise converter o campo para _Data_. Faça mais ou menos assim:
`strftime('%m', datetime(L.DATA, 'unixepoch'))`
Comment: É DATETIME o campo por isso estou achando estranho não era para acontecer esse erro.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/48673/discussion-between-andrey-and-alison-paulo).
Answer: Faça assim:
SELECT L.*, C.DESCRICAO AS CATEGORIA , CASE WHEN L.TIPO_LANCAMENTOS = 'C' THEN 0 ELSE 1 END AS ICONE
FROM LANCAMENTOS L JOIN CATEGORIAS C ON(C.CODIGO = L.COD_CATEGORIA)
WHERE strftime('%m-%Y', L.DATA ) = '10-2016'


Probability distribution of the product of two dependent random variables

Question: It is well known that being $X$ and $Y$ two independent random variables with distributions $f_X(x)$ and $f_Y(y)$, respectively, then the probability distribution of the multiplicative function $z = xy$ is given by
$$
f_Z(z)=\int_{-\infty}^{\infty}f_X(x)f_Y(z/x)\frac{1}{|x|}dx,
$$
where $\frac{1}{|x|}$ is the Jacobian of the transformation.
What if $X$ and $Y$ are not independent, in such a way we cannot write the probability distributions by separate functions? We need to use the joint distribution probability $f_{X,Y}(x,y)$. So, will the probability distribution of $z=xy$ be
$$
f_Z(z)=\int_{-\infty}^{\infty}f_{X,Y}(x,z/x)\frac{1}{|x|}dx,
$$
that is, the only difference is that we cannot separate the pdfs of $x$ and $y$ in the integral?
Answer: Yes, this is the only difference - though sometimes you can simplify the calculation if you can phrase the dependency as $f_{X,Y}=f_X(x)\cdot f_Y(y|x)$, using the conditional probability density function, yielding:
$$
f_Z(z)=\int_{-\infty}^{\infty}f_X(x)f_Y(z/x | x)\frac{1}{|x|}dx,
$$
(In the case of independence, $f_Y(z/x | x) = f_Y(z/x)$, returning to your first equation).


How to set these complex types in ZEND SOAP AutoDiscovery?

Question: Hello I need to write a SOAP server, where I would be able to pass complex types, structuraly that would look like this:
<ParcelDetails>
  <countryType></countryType>
  <addressType>
    <countryType></countryType>
      .... .....
      .... ....

    <contact></contact>
  </addressType>
<ParcelDetails>

and I/m using following code to generate WSDL file for this service
<?php
include_once("Zend/Soap/Wsdl/Strategy/ArrayOfTypeSequence.php");
include_once("Zend/Soap/Wsdl/Strategy/DefaultComplexType.php");
include_once("Zend/Soap/Wsdl/Strategy/Composite.php");
include_once("Zend/Soap/Wsdl/Strategy/ArrayOfTypeComplex.php");
include_once("Zend/Soap/Wsdl/Strategy/AnyType.php");
include_once('Zend/Soap/AutoDiscover.php');

include_once('Zend/Soap/Server.php');
include_once('Zend/Soap/Client.php');
include_once('Zend/Soap/Wsdl.php');

//*************************************
// Classes used by getGroup service method below

class countryTypeSpace
{
    /** @var country */
    public $country = '';
}

class addressTypeSpace
{
    /** @var countryType */
    public $countryType = '';

    ....

    /** @var contact */
    public $contact = '';

}

class ParcelDetailsSpace
{

    /** @var countryType */
    public $countryType;

    /** @var addressType[]  */
    public $addressType;

}

//*************************************

class ServiceClass
{
    /**
     *  ParcelDetails
     */
    public function registerParcel( $username, $pasword) {

        $group = new ParcelDetailsSpace();

        //fill in the array
        for ($i = 1; $i <= 3; $i++) {
            $countryType = new countryType();
            $countryType->country = 'country';

            $addressType = new addressTypeSpace();
            $addressType->address = 'Adresas';
            $addressType->area = 'Area';

            $group->countryType = $countryType;
            $group->addressType = $addressType;
        }

        return $group;
    }
}

if(isset($_GET['wsdl'])) {
    $autodiscover = new Zend_Soap_AutoDiscover('Zend_Soap_Wsdl_Strategy_AnyType');
    $autodiscover->setClass('ServiceClass');
    $autodiscover->handle();
} else {
    $soap = new Zend_Soap_Server("http://localhost/zs/zserverComplex.php?wsdl");
    $soap->setClass('ServiceClass');
    $soap->handle();
}

?>

on the client end I'm getting an error:
 Fatal error: Uncaught SoapFault exception: [VersionMismatch] Wrong
 Version in C:\Program Files
 (x86)\EasyPHP-220.127.116.11\www\zs\Zend\Soap\Client.php:1121 Stack trace:

# 0 C:\Program Files
 (x86)\EasyPHP-126.96.36.199\www\zs\Zend\Soap\Client.php(1121):
 SoapClient->__soapCall('registerParcel', Array, NULL, NULL, Array)

# 1 C:\Program Files (x86)\EasyPHP-184.108.40.206\www\zs\zclientDpd.php(6):
 Zend_Soap_Client->__call('registerParcel', Array)

#2 C:\Program Files
 (x86)\EasyPHP-18.104.22.168\www\zs\zclientDpd.php(6):
 Zend_Soap_Client->registerParcel(Array)

#3 {main} thrown in C:\Program Files
(x86)\EasyPHP-22.214.171.124\www\zs\Zend\Soap\Client.php on line 1121

I'v tried different Zend_Soap_Wsdl_Strategy strategies as you might see from includes at the top of my server file, but no success at all
I know that probably I'm missing something, but I'm not sure where to look...
I would be glad if someone would be able to point me to the right direction, about these complex types and auto discovery, at least, if not the right answer to this problem
Because I couldnt get any good info on this
Thank you in advance
Answer: I might be out of my league here, but I just wrote a web service in PHP using NuSOAP, and it allows you to define complex types and generates the WSDL for you.
Might be something to check out: http://www.scottnichol.com/nusoapintro.htm
In NuSOAP, to create a complex type like the one you provided, the code would look something like this:
$server = new nusoap_server();

$server->wsdl->addComplexType(
    "addressType",
    "complexType",
    "struct",
    "all",
    "",
    array(
        "countryType" => array("name" => "countryType", "type" => "xsd:string"),
        ...
        "contact" => array("name" => "contact", "type" => "xsd:string")
    )
);

$server->wsdl->addComplexType(
    "ParcelDetails",
    "complexType",
    "struct",
    "all",
    "",
    array(
        "countryType" => array("name" => "countryType", "type" => "xsd:string"),
        "addressType" => array("name" => "addressType", "type" => "tns:addressType")
    )
);


iOS Client + Rest API to upload photos

Question: I have a basic requirement of uploading an image from an iOS App to a remote server. I know that I can use NSURLConnection to transfer the image to a remote server but I need to develop a REST Webservice also in the remote server which can accept images from the iOS Client and store inside a DB/hard disk .
Can anyone please suggest me the best method/libraries which can be used to  to develop the REST Webservice .
Answer: I'd recommend using Ruby on Rails with the Paperclip gem.
If it's completely new to you, you can start with the Guides.
There's a lot of material on how to build a RESTful API with Rails, like this screencast.
Once you've understood how to develop an API, and how to use Paperclip to save images on the server, the answer to this question might help you with the file upload part.
Comment: Can you please suggest me a method to do the same in Java ? Is jersey a good one ?
Comment: Hmm you could use Spring http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch18s02.html - It will have better performance probably (if done right) but it will definitely take a lot more work, in my experience...

iOS Client + Rest API to upload photos


Deploying a rails app ... how to load first user?

Question: Maybe I'm missing something really simple here, I don't know -- I've never deployed a rails app before. I'm about to. I'm using Devise for user authentication, and have several actions that require authentication. The app is not set up so just anyone can register, registration is restricted to a set of users who will administer the app.
But, what I don't know ... is when the app switches to the production database, how do I get myself set up as the first user? The user model will be empty, I won't be able to even access the controllers that would let me set up a new user, because those controllers require authentication.
Answer: Use <code>/db/seeds.rb</code>
Check http://railscasts.com/episodes/179-seed-data
Answer: Connect to the database directly and insert the records manually.
Comment: @Final Draft generate them in the rails console first, then save info and run with it.


Finding a basis for the Eisenstein space $\mathcal{E}_1(12,\chi)$

Question: I am trying to find a basis of the Eisenstein space $\mathcal{E}_1(12,\chi)$ of modular forms of weight 1, level 12 and Dirichlet character
\begin{equation*}
    \chi(m)=\genfrac{(}{)}{}{}{-12}{m}=\begin{cases}
    1 ~~&\text{  if  } m\equiv 1,\,7\pmod{12}\\
    -1 ~~&\text{  if  } m\equiv 5,\,11\pmod{12}\\
    0 ~~&\text{  if  } m\equiv 0,\,2,\,3,\,4,\,6,\,8,\,9,\,10 \pmod{12}.
    \end{cases}
\end{equation*}
For this I am following the approach described in Section 4.8 of "A first course in modular forms" by Diamond and Shurman.
Since $\chi$ is induced by the primitive character modulo 3, it has conductor 3. Therefore I am led to believe that a basis of $\mathcal{E}_1(12,\chi)$ is given by $E_1^{\mathbf{1}_1,\chi,1}(z)=E_1^{\mathbf{1}_1,\chi}(z)$, $E_1^{\mathbf{1}_1,\chi,2}(z)=E_1^{\mathbf{1}_1,\chi}(2z)$ and $E_1^{\mathbf{1}_1,\chi,4}(z)=E_1^{\mathbf{1}_1,\chi}(4z)$. Here $E_1^{\mathbf{1}_1,\chi}(z)$ has $q$-expansion
$$ E_1^{\mathbf{1}_1,\chi}(z)=L(0,\chi) + 2 \sum_{m=1}^{\infty}\sigma_0^{\mathbf{1}_1,\chi}(m)q^m, $$
where
$$\sigma_0^{\mathbf{1}_1,\chi}(m) = \sum_{\substack{d|m\\d>0}}\chi(d).$$
Writing out the first few coefficients in the $q$-expansions I obtain
\begin{align*}
    E_1^{\mathbf{1}_1,\chi,1}(z) &= \frac{2}{3} + 2q + 2q^2 + 2q^3 + 2q^4 + 2q^6 + 4q^7 + 2q^8 + \dots \\
    E_1^{\mathbf{1}_1,\chi,2}(z) &= \frac{2}{3} + 2q^2 + 2q^4 + 2q^6 + 2q^8 + \dots \\
    E_1^{\mathbf{1}_1,\chi,4}(z) &= \frac{2}{3} + 2q^4 + 2q^8 + \dots .
\end{align*}
However, the span of these forms does not agree with the span of the forms that Sage outputs as a basis for $\mathcal{E}_1(12,\chi)$ and I can not manage to express the theta function of the quadratic form $Q(X)=X_1^2 + 3X_2^2$ in terms of the basis I obtained.
Something is going wrong here, but I can not seem to put my finger on where I am making a mistake. Any help will be greatly appreciated!
Answer: I don't know about how to generate that Eisenstein space, but from quadratic reciprocity for $O_K = Z[\frac{\sqrt{-3}+1}{2}]$ which  is a PID we have
$$\sum_{a,b \ne (0,0)} |a+b \frac{\sqrt{-3}+1}{2}|^{-2s} = |O_K^\times| \zeta_K(s) =6 \zeta(s) L(s,(\frac{-3}{.}))=6 \zeta(s) L(s,(\frac{.}{12}))\\ =6 \sum_{n=1}^\infty n^{-s} \sum_{d | n, d \ odd} (\frac{d}{3})(-1)^{(d-1)/2}$$
So that with the quadratic form $f(a,b) = |a+b \frac{\sqrt{-3}+1}{2}|^2$ we have
$$\sum_{a,b} q^{f(a,b)} = 1 +6 \sum_{n=1}^\infty q^n \sum_{d | n, d \ odd} (\frac{d}{3})(-1)^{(d-1)/2} \in M_1(\Gamma_1(12))$$
Then with the quadratic form $Q(a,b) = |a+b\sqrt{-3}|^2$ I think it is not of level $12$ but of level $12 [O_K : Z[\sqrt{-3}]] = 24$, that's why you won't find it in your Eisenstein space.


Justifying the choice of covariance function

Question: For a Gaussian process I run I have chosen to use the Matern52 covariance function, as from research this is practical to use for physical data as it does not overally smooth the function. However is there a numerical way to prove this suits my data?
What would be the benefits of using Matern32 or Matern52, as I am quite sure that the Matern class is the correct thing to use for my data, as it allows for flexibility, whereas the other stationary covariance functions have been described to have no flexibility with regard to local behaviour and act like a prior
Comment: What is the Matern52 covariance function? Is it the same as [this](https://en.wikipedia.org/wiki/Mat%C3%A9rn_covariance_function)?
Answer: Let us say that there are $M$ number of covariance functions, indexed by $m=1,\dots,M$, and we want to decide which of these $M$ offers better modelling for some dataset at hand which we denote by $\mathcal{D}$.
Dataset $\mathcal{D}$ consists of $(x,y)$ input-target pairs.
The problem can be approached with K-fold cross-validation.
First you need to choose a performance criterion.
This criterion can be e.g. predictive log-likelihood (other are possible), which tells you what the log-likelihood is when evaluated on some test data, i.e. data that you have not trained on:
$p(y_{test}) = \mathcal{N}(y_{test}|\boldsymbol{\mu}, \boldsymbol{\Sigma})
$,
where:
$\boldsymbol{\mu} = K(X_{test}, X_{train})(K(X_{train}, X_{train}) + σ^2\boldsymbol{I})^{-1}\boldsymbol{y}$ and
$\boldsymbol{\Sigma} = K(X_{test}, X_{test}) − K(X_{test}, X_{train})(K(X_{train}, X_{train}) + σ^2\boldsymbol{I})^{-1}K(X_{train}, X_{test})$.
(This equation appears as equation 2.23 in Chapter 2 in the Rasmussen and Williams book)
K-fold cross validation divides the data in $K$ non-overlapping partitions called folds.
Let us denote the k-th fold of the data as $\mathcal{D}_k$. Let us denote the data we are left with after removing $\mathcal{D}_k$ as $\mathcal{D}_{-k}$. Note that $\mathcal{D}_k\cup\mathcal{D}_{-k}=\mathcal{D}$, that is the union of the two gives us the entire dataset back.
For each $m$-th candidate covariance function and each $k=1,\dots,K$ we perform the cross-validation as follows:

Train the Gaussian process (i.e. optimise its marginal log-likelihood wrt hyperparameters) on  fold $\mathcal{D}_k$. In other words, $\mathcal{D}_k$ is your training set.
Evaluate the trained Gaussian process on $\mathcal{D}_{-k}$ using your criterion of choice and record the value returned by your criterion as $c_{m,k}$. In other words, $\mathcal{D}_{-k}$ is your test set.

Once you have completed the above $K$-fold cross-validation for all $M$ number of candidate covariance functions, you can calculate the following estimate for the $m$-th candidate covariance function $C_m = \sum_{k=1}^K c_{m,k}$. The covariance function with the highest $C_m$ is the most appropriate one for the dataset $\mathcal{D}$ in question.
Finally, note that cross-validation for Gaussian process can be evaluated in a more efficient manner than presented above. For more info, please look at section 5.3 in the Rasmussen and Williams book)


Maximum probability returned much less than 1: truncated calibration curve

Question: There's a sklearn calibration curve example which shows curves for different estimators.  I changed it to reproduce an issue I am having on a true dataset by adding class imbalance (.95,.05).  I get the following curve.

I see that for the blue curve "Mean predicted value" never goes above 0.8. Why?
Same thing here
Austin and Steyerberg (2013) 10.1002/sim.5941

Comment: Could this be because your model never produces predictions that are higher than about 0.8? You could check the maximum value in your `y_prob` vector.
Comment: Yes, I think this was the case. Realized this today
Answer: It could be that your model never produces predictions that are higher than about 0.8.
With an unbalanced data set like the one you're investigating, a linear model (high bias) will tend to be more sensitive to the class distribution: the probability that your model assigns a high prediction to a data point decreases as the proportion of the positive class decreases.
Comment: `a linear model (high bias) will tend to be more sensitive to the class distribution` can you explain why?


Probability that $n$ dice roll a sum higher than $m$ dice

Question: I am playing the popular online game World Wars 2. Where neighbouring nations can attack each other and the probability of an attack being successful depends on some dice mechanic.
Each nation is allocated a number of fair 6-sided dice to roll, equal to the number of solider units inside it. When you choose to attack, you roll $n$ dice, and the attack is successful if the sum of these $n$ dice is higher than the sum of $m$ dice rolled from the defending nation.
Each nation requires a minimum of two units to attack, and all units are used in the attack. However a defending nation may have just 1 unit inside, and all units are used in the defense, and the maximum number of units allocated to any nation is 8. So the question can be posed as What is the probability that $n$ fair 6-sided dice roll a sum higher than $m$ fair 6-sided dice, where $2 \leq n \leq 8, 1 \leq m \leq 8$?. The number  of units in the attacking nation and the defending nation are known by both players prior to each attack.
Expressed  mathematically:
$$P(\sum_{i=1}^{n}d_{i} > \sum_{j=1}^{m}d_{j})$$
I have written code to simulate the probabilities for this problem, but I would like to answer this question so that it can be expressed in the general case. I have already looked at questions here, and here, however these questions weren't considering the sum of these rolls.
Each dice has 6 sides, and is fair so it follows a uniform distribution. I have tried to answer this by looking at possible combinations of $n$ and $m$ rolls, and assessing the distribution.
I started by working backwards from the extremes, i.e 8 dice will always roll a sum higher than 1 dice with probability 1, same goes for seven dice. $$P(\sum_{i=1}^{8}d_{i} > \sum_{j=1}^{1}d_{j}) = 1$$
As we work down to 6 dice, there is a non-zero probability that 6-dice will not roll a sum higher than one dice. i.e $$P(\{1,1,1,1,1,1\}) = \frac{1}{6^6}= \frac{1}{46656}$$ And the probability of the 1 die rolling a 6 is $$P(\{6\}) = \frac{1}{6}$$ I then calculated the probability of this even to be $$P(\{1,1,1,1,1,1\}) \times P(\{6\}) = \frac{1}{46656} \times \frac{1}{6} = \frac{1}{279936}$$
This analysis is easy to do in extreme cases however I was stuck on how to proceed from here.
Answer: Let $P(n,s)$ be the probability that you the sum of $n$ dice is exactly equal to $s$. It can be shown that
$$
P(n,s)=\frac1{6^n}\sum_{i=0}^{\lfloor (s-n)/6\rfloor } (-1)^i\binom ni \binom{s-6i-1}{n-1}
$$
Furthermore, let $L(n,s)$ be the probability that that the sum of $n$ dice is strictly less than $s$. We can also give a formula for this:
$$
L(n,s)=\frac1{6^n}\sum_{i=0}^{\lfloor (s-1-n)/6\rfloor}(-1)^i\binom ni \binom{s-6i-1}n
$$
With these auxiliary functions, we can easily compute the probability that sum of $n$ dice is greater than the sum of $m$ dice. The answer is
$$
P(\text{sum of $n$ dice}>\text{sum of $m$ dice})=\sum_{s=n}^{6n}P(n,s)L(m,s)
$$
We are just summing over all of the distinct ways the event can happen; the player with $n$ dice needs to roll some number, call it $s$, and then the player with $m$ needs to roll less than $s$.
Here's the table of values relevant to the dice game.
  \ m   1        2        3        4        5        6        7        8
  n ┌──────────────────────────────────────────────────────────────────────┐
  2 │ 0.838 │  0.444 │  0.152 │  0.036 │  0.006 │  0.001 │    0.0 │    0.0 │
  3 │ 0.973 │  0.779 │  0.454 │  0.192 │  0.061 │  0.015 │  0.003 │    0.0 │
  4 │ 0.997 │  0.939 │  0.743 │   0.46 │   0.22 │  0.083 │  0.025 │  0.006 │
  5 │   1.0 │  0.988 │  0.909 │  0.718 │  0.464 │  0.242 │  0.104 │  0.037 │
  6 │   1.0 │  0.998 │  0.975 │  0.884 │    0.7 │  0.467 │   0.26 │  0.122 │
  7 │   1.0 │    1.0 │  0.995 │  0.962 │  0.862 │  0.685 │  0.469 │  0.274 │
  8 │   1.0 │    1.0 │  0.999 │   0.99 │  0.948 │  0.844 │  0.673 │  0.471 │
    └──────────────────────────────────────────────────────────────────────┘

Comment: The table would be clearer if you used more decimals or distinguished the 1.0 result of rounding from the full 1 probability.
Answer: The most important theory simplification in this problem that you can make is to recognize that subtracting a dice roll is the same as adding a dice roll and subtracting 7. Thus you can go from, "what's the probability that $n$ dice roll greater than $m$ dice?" to "what's the probability that $m+n$ dice roll greater than $7 m$?"
For $m+n=3, 4, 5$ we can get this table, for example the coefficients for 3d6 probabilities are [0, 0,1,3,6,10,15,21,25,27,27,25...] and taking the numbers <= 7 are:
m+n  m       (1-p)              p
 3   1   (1+3+6+10+15)/216   181/216  (83.8%)
 4   1   (1+4+10+20)/1296   1261/1296 (97.3%)
 4   2      721/1296         575/1296 (44.4%)
 5   1       21/7776        2585/2592 (99.7%)
 5   2     1722/7776        1009/1296 (77.9%)
 5   3     6594/7776         197/1296 (15.2%)

You can make this table of coefficients in Google Sheets, for instance, by filling cells A7, A8,... with counting numbers 1,2,3,... off as high as you will need, then filling B7-B12 with "1" each, six ones, this column is the weights for one die, and then filling cell C7 with the formula =sum(b1:b6) and autocompleting down to get the weights for two dice, then autocomplete right to get the weights for 3,4,5... dice. The sum will always be $6^n$ as your normalizing factor.
So if you want the exact answers, build these probability tables in a spreadsheet, to get them exact just don't bother dividing by 6 ever, normalize by the sum at the very end instead. Etc.
Asymptotics
We can do a little bit better if you only care about approximate answers and asymptotic behavior. For four or more dice the central limit theorem is going to hold with pretty good accuracy, so that sum of $m+n$ dice is approximately a normal random variable. More precisely we should say that we want to consider the area $5.5 < x < 6.5$ as area which belongs to the sum 6, for instance.
This then reduces the entire problem to thinking about "Z-scores", the number of standard deviations the result is above the mean.
For one die the mean is $\frac72$ and the variance is $\frac{35}{12}$, these are both additive for independent random variables like dice. So for $m+n$ dice the mean is $\frac72(m+n)$ and the variance $\frac{35}{12}(m+n),$ and we are trying to evaluate the probability that a standard normal random variable $Z$ satisfies
$$
\frac72(m+n) + Z~\sqrt{\frac{35}{12}(m+n)} > 7m + \frac12
$$
which rearranges to
$$
Z > \frac{7}{2}\sqrt{\frac{12}{35}}~\frac{m-n+\frac17}{\sqrt{m + n}}\\
Z > -\sqrt{4.2}~\frac{A-\frac17}{\sqrt{2m + A}},
$$
where I have defined attacker's dice advantage $A = n - m$, as I figure the idea is "when do I really need 1 extra die, when do I need 2 extra dice," and so on. The thing on the right is the "Z-score" and you can just evaluate this. So the parallel version of the above table is:
 m   A      Z      p
 1   1   -1.014   84.5%
 1   2   -1.903   97.1%
 2   0    0.146   44.2%
 1   3   -2.619   99.6%
 2   1   -0.786   78.4%
 3  -1    1.047   14.7%

Just comparing the calculated percentages the result is not that bad! (Spreadsheet formulas here are pretty straightforward, =-sqrt(4.2)*(M7-1/7)/sqrt(2*L7+M7) and =1-NORMDIST(N7,0,1,1) in Google Sheets.)
The other thing we can do with this formula is convert probability buckets to some notion of "how decisive is your advantage/disadvantage" and then ask where the thresholds are. In practice this is probably what I would do, just define some buckets like "slight advantage: 50% < p < 75%, solid advantage: 75% < p < 90%, nearly-sure-thing: 90% < p." Then you can use normsinv to convert these thresholds to Z-scores: 0, 0.6745, 1.282.
And then I could say something like,

When I attack with advantage -1, that is, $n = m - 1$, it's a nearly sure loss when $m=2$, a solid disadvantage when $m < 7$, and a slight disadvantage for $m \ge 7$.
When I attack with $n=m$, that is always a slight disadvantage.
When I have one extra die of advantage, that is never nearly-sure, but it is a solid advantage when there are 1-2 defenders, a slight advantage for 3+.
When I have two extra dice, that is nearly-sure when $m < 4$, and remains a solid advantage until like $m=15$ where it becomes and remains a slight advantage.
With $n$ extra dice the win is nearly-sure until there are something like $n^2$ defenders or so, given the scalings involved.
Answer: Let $Q(s,n)$ be the probability that $n$ dice roll a sum of $s$. Then we are looking for the probability
$$P(m,n)=\sum_{s=n}^{6n}\sum_{t=m}^{s-1} Q(s,n)Q(t,m)$$
$Q(s,n)$ has the generating function
$$\sum_{s=n}^{6n} Q(s,n)x^s=\left(\sum_{i=1}^6\frac{1}{6} x^i\right)^n$$
$$=6^{-n}\left(\frac{x^7-x}{x-1}\right)^n$$
So
$$Q(s,n)=\frac{1}{6^ns!}\left(\frac{d}{dx}\right)^s\left(\frac{x^7-x}{x-1}\right)^n|^{x=0}$$
I haven't yet managed to make this into a nice formula for $P(m,n)$ though.


real-value solution

Question: I have this integral
$$\int\frac{dz}{\sqrt{(z^{2}-\rho^{2})(\lambda^{2} - z^{2})}}$$
and parameters obey the following conditions
$$z= \exp[k\varphi],$$ $$\lambda^{2} = \frac{b + \sqrt{b^{2} - 4ac}}{-2a} > 0,$$ $$\rho^{2} = \frac{b- \sqrt{b^{2} - 4ac}}{-2a} > 0,$$
$ \rho^{2} < \lambda^{2}$, $\rho \leq z \leq \lambda$, $a <0$, $c<0$, $b>0$.
I have tried to evaluate the integral using the elliptic integral of the first kind, the obtained result is complex.
Is there a way to find an analytical (real-value) solution to the integral?
Answer: You can in fact bring it to the elliptic integral of the first kind (without complex numbers)
$$F(\phi,k)=\int_0^{\sin\phi} \frac{dt}{\sqrt{(1-t^2)(1-k^2 t^2)}}.\qquad(1)$$
Starting with ($0<\rho< z<\lambda$)
$$I=\int\frac{dz}{\sqrt{(z^{2}-\rho^{2})(\lambda^{2} - z^{2})}}$$
You proceed via a Möbius transformation $z = \sqrt{\lambda \rho}(x - 1)/(x + 1)$. The integral then reads
$$I=\int \frac{2 \sqrt{\lambda \rho} \,dx}{\sqrt{(A_- -A_+ x^2)(A_+-A_-x^2)}}$$
where $A_+=(\lambda+\sqrt{\lambda \rho})(\rho+\sqrt{\lambda \rho})$ and $A_- =(\lambda-\sqrt{\lambda \rho})(\sqrt{\lambda \rho}-\rho)$.
Making the substitution $x=t \sqrt{A_-/A_+}$ brings the integral finally in the desired form:
$$I=\int\frac{2\sqrt{\lambda\rho}\, dt}{A_+\sqrt{(1-t^2)(1-k^2 t^2)} }$$
with $k=A_-/A_+<1$.
Using the definition (1), we obtain
$$I=\frac{2\sqrt{\lambda \rho}}{A_+}F(\arcsin t,k)$$
with $$t=\sqrt{\frac{A_+}{A_-}}\frac{z-\sqrt{\lambda\rho}}{z+\sqrt{\lambda\rho}}$$
More information can be found here.
Comment: Thanks for your answer! It is exactly what I have been looking for. However let me note that the transformation should be $z= \sqrt{\lambda\rho}\frac{x-1}{x+1}$. If $z = \sqrt{\lambda\rho}\frac{x+1}{x- 1}$, then $dz = -2\sqrt{\lambda \rho}\frac{1}{(x-1)^2}dx$ and one obtains the integral with sign $"-"$.
Comment: @AnastasiaKrotoff: as far as I understand, either of the two transformations does the job (I agree that I might have lost a minus sign along the way). But if you like your version better then I will change the answer accordingly...
Comment: @Anastasia: Any appropriate Möbius substitution should do the job. IIRC Byrd and Friedman take the route given by Fabian, but they mention that your route is also suitable.

real-value solution


Bartik theme: How to extend text/content below blocks in sidebar 1 and 2

Question: Am using the Bartik theme on my site. I noticed that whenever i place a block in the sidebar 1 and sidebar 2, all the space below the block becomes 'redundant' (i.e. content is limited to the middle of the page.) All the text on the page becomes restricted to the middle of the page.
Please, is there a way to make the content/text extend below the blocks in side bar 1 or 2?
Answer: Edit your page.tpl.php
Cut and paste both the sidebar sections into the content section.
Content section starts with:

I mean these parts:
<?php if ($page['sidebar_first']): ?>

      <?php print render($page['sidebar_first']); ?>

  <?php endif; ?>

<?php if ($page['sidebar_second']): ?>

    <?php print render($page['sidebar_second']); ?>

<?php endif; ?>

I think you will need some extra CSS to make it look nice.


React: avoid child component rerender on state change

Question: I'm working on a React app where a graph component fetches and displays data using props passed on from the parent component. The problem is that the parent does some data fetching as well, and updating the parent state (although not affecting the child props) seems to rerender the child thus initiating a duplicate data fetch in the child.
See https://jsfiddle.net/ctombaugh/cgzn7wst/10/ and below for code.
function App(props) {
  const [year, setYear] = React.useState(2019);
  const [list, setList] = React.useState([]);
  React.useEffect(() => {
    alert("App is fetching some lists");
    setList(["a", "b", "c"]);
  }, [setList]);
  function handleYearChange(e) {
    setYear(e.target.value);
  }
  return (

    <YearSelector value={year} onChange={handleYearChange}></YearSelector>
    <Plot year={year}></Plot>

);
}

function YearSelector(props) {
  return <select value={props.value} onChange={e => props.onChange(e)} >
    <option value="2019">2019</option>
    <option value="2018">2018</option>
  </select>
}

function Plot(props) {
  const [data, setData] = React.useState([]);
  React.useEffect(() => {
    alert("Plot is fetching data for " + props.year);
    setData([1, 2, 3]);
  }, [props]);
  return
I'm a plot
;
}

ReactDOM.render(<App/>, document.getElementById("container"));

Comment: Check out [memoization](https://reactjs.org/docs/react-api.html#reactmemo).
Answer: Whenever the component is rerendered a new props object is generated, so using props as a dependency to useEffect doesn't really help.
If the side effect of should only be fired if the year changes, use just the year as a dependency:
function Plot({ year }) {
  const [data, setData] = React.useState([]);
  React.useEffect(() => {
    alert("Plot is fetching data for " + year);
    setData([1, 2, 3]);
  }, [year]);
  return
I'm a plot
;
}

Comment: I missed the `props` as a dependency.. That's a much simpler solution than using `memo`.
Comment: You're welcome. Remove the props from alert. See updated code.
Comment: Thanks! One additional question: adding the individual props properties as dependencies gives me a `React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array` warning. Anything I should worry about?
Answer: You are looking for React.memo which is equivalent to PureComponent, but it only compares props. (You can also add a second argument to specify a custom comparison function that takes the old and new props. If it returns true, the update is skipped.)
const Button = React.memo((props) => {
  // your component
});

for more info https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate


Center of dihedral group

Question: I am trying to solve the following exercise about the dihedral group and its center:
If $g\in Z(D_{2n})\Leftrightarrow ga=ag, bg=gb$, where $a,b$ are generators of $D_{2n}$.
We have defined the dihedral group of order $2n$ as $D_{2n}=\left \{ a^{i}b^{j} \mid 0\leq i \leq n, j=0,1 \right \}$, the group of all finite products of the generators $a$ and $b$,
where
$a= \bigl(\begin{smallmatrix}
    1 & 2 & 3 & \cdots & n-1 & n \\
    \end{smallmatrix}\bigr)$ and $ b = \bigl(\begin{smallmatrix}
    1 & 2 & 3 & \cdots & n-1 & n \\
    1 & n & n-1 & \cdots &  3  & 2
  \end{smallmatrix}\bigr)$
For the first part ( $\Rightarrow $) i have considered an element $g$ of the center $Z(D_{2n})$, $g$ is also in $D_{2n}$, so it can be written as a finite product of powers of $a$ and $b$. Let's say $g=a^{k}b^{l}$ for $0 \leq k \leq n$ and $j=0$ or $j=1$.
Then i can write $ga = a^{k}b^{l}a=a^{k+1}b^{l}$ and $ag=aa^{k}b^{l}=a^{k+1}b^{l}$. So $ga=ag$. The same for $gb=bg$.
Is this correct? How to start with the other part of the proof? I would appreciate any help and hints. Thank you in advance.
Answer: I don't think I understood what you wrote. Look, if $g\in Z(D_{2n})$, then $gh=hg$ for every $h\in D_{2n}$. In particular it is true for $h=a$ and $h=b$. This proves the half you stated above.
Conversely, suppose $ga=ag$ and $gb=bg$. First note that $ga^i=a^ig$ for all $1\leq i<n$ (you can prove this by induction if you like: $ga^{i}=aga^{i-1}$). Now, any $h\in D_{2n}$ has the form $h=a^ib^j$, $0\leq i<n$, $0\leq j\leq 1$. So,
$$gh=ga^ib^j=a^igb^j=a^ib^jg=hg.$$
This completes the proof.
This gives a fast way to prove that $Z(D_{2n})$ is nontrivial only if $n=2k$ is even. In this case, either $k=1$ and $D_4=\mathbb{Z}_2\times\mathbb{Z}_2$ is abelian, or $Z(D_{2n})=\langle a^k\rangle$. To see this, suppose $g\in Z(D_{2n})\backslash\{1\}$. We consider two cases:
Case 1: $g=a^k$. Then $g$ commutes with $a$. Next we compute $gb=a^kb$, and $bg=ba^k=a^{-k}b$. Since $bg=gb$, we must have $a^{k}b=a^{-k}b$. This forces $k\equiv -k$ (mod $n$), so $n=2k$ is even.
Case 2: $g=a^kb$. Then $ag=a^{i+1}b$ and $ga=a^iba=a^{i-1}b$, so $i+1\equiv i-1$ (mod $n$). This forces $n=2$, and $D_{2n}=D_4=\mathbb{Z}_2\times\mathbb{Z}_2$.
Putting these cases together, $Z(D_{2n})=1$ if $n$ is odd; if $n=2$, $D_4=Z(D_4)$ is abelian; if $n=2k>2$, then $Z(D_{2n})=\langle a^k\rangle$.
Comment: Thank you very much, this is great!
Comment: @DavidHill does this answer only pertain to even dihedral groups, because of your subscript $2n$? I'm confused...
Comment: @JessyCat $D_{2n}$ is the symmetry group of a regular $n$-gon. It has order $2n$.
Comment: $D_4$ is abelian?

Center of dihedral group


Enrichment analysis by gene duplication level

Question: Biological Background
Over time, some plant species tend to duplicate their entire genomes, gaining an additional copy of each gene. Due to the instability of this setup, many of these genes are then deleted, and the genome rearranges itself and stabilises, ready to duplicate again. These duplication events are associated with speciation and invasion events, and the theory is that the duplication helps plants to adapt faster to their new environments.
Lupinus, a genus of flowering plant, invaded the Andes in one of the most rapid speciation events ever detected, and what's more, it seems to have more duplicate copies in its genome than the most closely related genus, Baptisia.
And now the mathematical problem:
The genomes of a member of Lupinus and a member of Baptisia have been sequenced, providing raw data about 25,000 genes in each species. By querying against a database of genes of known function, I now have a "best guess" for what functions that gene might perform - so for example, Gene1298 might be associated with "fructose metabolism, salt stress response, cold stress response". I want to know, if there was a duplication event between Baptisia and Lupinus, whether gene loss took place at random, or whether genes performing particular functions were more likely to be kept or deleted.
I have a script which will output a table like the one shown below. L * is a count of all Lupinus genes associated with the function. L 1+ is a count of lupinus genes associated with the function where at least one duplicate copy exists. I can get it to produce L 2+, L 3+ etc., although L 1+ is a much more reliable group than L 2+ due to the sequencing process.
<code>Function            | L *  | L 1+ | B *  | B 1+ |
fructose metabolism | 1000 | 994  | 1290 | 876  |
salt stress         | 56   | 45   | 90   | 54   |
etc.
</code>
What I would like to do is to test, for each gene function, whether there are more or fewer genes with duplicates than might be expected purely by chance in Lupinus and Baptisia, and whether Lupinus differs from Baptisia in the ratio of observed to expected.
The best thing I have so far
Previous studies on different species have used Enrichment Analysis, with Fisher's Exact Test and FDR correction for multiple sampling, to do a contingency test on each row.
It would be nice to improve on this; I'm not sure this sounds like the best way to do it.
Glen_b has suggested using a GLM to analyse the data; I have played around with GLMs in JMP8, which has been interesting, but I will admit to not really understanding them.
That said, I'm trying to use R instead now.
What am I using this for?
This was originally supposed to be as part of a short research project I'm doing at university, but has now spanned off into an enormous genome annotation project. Why? Because bioinformatics is cool. Being able to take a string of A,T,C and G and use it to infer information about events which happened millions of years ago is amazing.
Needless to say, I am not going to try and submit any kindly provided answer as my own work. I would be happy to include an acknowledgement in the paper if I use a method suggested here in the submitted work.
Comment: Note the problem I mentioned in my earlier [answer to your other question](http://math.stackexchange.com/questions/262311/confidence-intervals-for-two-proportions/262413#262413) -- about testing only against one variable when there are other important variables (I pointed to the wikipedia article on Simpson's Paradox) - Fisher's exact test doesn't get around that.
Comment: Bioinformatics *is* cool!! Welcome to the site!
Comment: I'll come back and give more extensive answers soon, but the appropriate functions in R to look at will be loglin, loglm (in the package MASS, which comes with R but isn't installed by default) and glm itself. The understanding of these models will have a lot of similarity to understanding multiple regression and ANOVA - with the exceptions that the distributions aren't normal, and the logs-of-means is what the models are linear in.
Answer: While I agree that Fisher's test (or something similar) may be the most natural approach here, how about this:

For each unique gene, you determine the difference in number of duplications in L and B
Order genes by this difference. Now the genes showing most differences between the species will be on the top of your list.
Apply a gene set enrichment test to the ordered list of genes. For example, you can use a modified Fisher's method from my package tmod, for which you would have to define your gene sets (it should be quite straightforward). Note that Fisher's method is not related to Fisher's test.

The modified Fisher's test (dubbed CERNO by the authors who first described it in this context) takes any ordered list of genes as the input, as long as you can group them in some useful categories.
The advantage of this approach is that apart from a p-value, you can easily calculate the effect size of the enrichment and visualize it (for example, as a ROC curve over the ordered list of genes). This gives you a much better idea how much what you observe really matters for the biology you study.
Answer: As you say, you're asking two distinct questions.
Question 1 "is the ratio L*/L1+ different from B*/B1+ for a given gene function"
this might be best answered with Fisher's exact test using data across the row as you found previously.
Question 2 "is the ratio: genes where there is a single copy / genes where there is more than one copy, different between gene functions?"
I think this also might be best answered with Fisher's exact test. You'd test the ratio of L*/L1+ for gene function 1 against L*/L1+ for gene function 2. Then gene function 1 Vs gene function 3, etc.
Neither of these sets of questions gets at whether or not they are being maintained/deleted faster than expected purely by chance, only whether they are being deleted/maintained at rates different from each other. To know if they were being deleted/maintained at a rate different than by chance, you'd need to know the ratio of singlecopy/multiplecopies for lots of DNA regions that are only being affected by chance. If you could find such regions, you'd end up with a "Function group" where function is "None". You'd then compare this to your other gene function groups in the same way as I described in question 2.


Turn server back on after power loss with FreeBSD

Question: I have a VIA M'SERV S2100 with FreeNAS 8.
Since I upgraded from FreeNAS 7, the M'SERV no longer turns back on after suffering a power failure. As I remember it, there was a setting for it in the old FreeNAS control panel, but I haven't been able to find one in the new one.
So logically, it should be something I could set from the CLI or some config file. Can someone point me in the right direction?
Comment: Anything in the BIOS?
Comment: I must have been using Macs for too long, had forgotten there was such a thing – there was a setting for it in the BIOS, thanks.
Answer: Like Tom said this is usually a BIOS setting. As far as I know there's nothing in stock FreeBSD that lets you tweak this though there may be something suitable in the ports tree.
The OS knows nothing until the system is turned on and the boot process starts, so BIOS/EFI/Whatever needs to take care of the turning-on-the-power part first.


Boundedness of a signal and its derivative implies convergence

Question: With given ONLY these two pieces of information:

$z(t) \in \mathcal{L}_{\infty}, \forall t$ and $z(t)$ converges to a ball (or bound) around $0$ for some $t > T$ and stays within that ball (or bound) from thereafter to $t \rightarrow \infty$ ($z(t)$ is generally a vector in $\mathcal{R}^n$, hence the term "ball" is used, although a scalar argument would help initially, hence the term "bound" is used). Note that the exact evolution of $z(t)$ within the ball or bound is not known.
$\dot{z}(t) \in \mathcal{L}_{\infty}, \forall t$ (even after entering the ball)

Is it possible to argue (that the average) i.e., $\lim_{t \rightarrow \infty} \int_T^{t} z(\tau) d \tau =$ $0$ or some (known or unknown) constant $c$?
If yes, how to rigorously prove it?
If not, what minimal extra condition is needed to make it happen?
Thank you.
Comment: Are you looking for the average  as the lower integral limit $T\rightarrow\infty$?
Comment: I am looking for the average as stated. $T$ could be any finite time after which the $z$ enters a ball and stays within that forever as $t \rightarrow \infty$.
Comment: In that case, I believe a more appropriate notation would be either $\int_{T}^{\infty}z(\tau)d\tau = 0$ or $\lim_{t\rightarrow \infty} \int_{T}^tz(\tau) d\tau = 0$.
Comment: Thanks. Edited! Please let me know if you have any idea how to approach it.
Answer: Function $z(t)=\sin(t)$ satisfies both assumptions. However, $\int_{T}^{\infty} \sin(\tau)d\tau$ does not converge (for any choice of $T$). Extra assumptions are required, however, I don't known which of them (if any) are necessary (so that they could be described as "minimal").


How to change model of a combobox (Ext JS) from outside its definition

Question: i have two Ext Combo boxes here, i need to change values of second combobox when select event of combobox1 invokes, my problem is i don't know how to change model of a combobox.
   items: [{
        xtype:'combo',
        fieldLabel: 'Course',
        afterLabelTextTpl: required,
        store: new Ext.data.SimpleStore({
            data: [
                [1, 'Bsc CS'],
                [2, 'MSc CS'],
            ],
            id: 0,
            fields: ['value', 'text']
        }),
        name: 'first',
        listeners:{

          select: function( combo, records, eOpts )
          {
              if(this.getValue()=="Bsc CS")
              {
                 // Ext.get('semcombo').getStore.loadData(msc);
              }
              else if(this.getValue()=="MSc CS")
              {

              }
          }

        },
        editable:false,
        allowBlank: false
    },{
        xtype:'combo',
        fieldLabel: 'Semester',
        id : 'semcombo',
        afterLabelTextTpl: required,
        name: 'last',
        allowBlank: false,
    }

Comment: What do you mean by model?  The records?
Comment: Yeah. I thought model is the apt word for that.
Comment: Well... model is actually the object that defines a single record's structure.  Technically the term is interchangeable but in this case record is more clear.
Answer: If you need to change the data completely (JSFiddle)
select: function(checkbox,records) {
      comp.clearValue();
      comp.bindStore(Ext.StoreMgr.lookup(records[0].data.store));
      // you can change the value field if needed
      comp.displayField = 'petname';
      // you can change the display field if needed
      comp.valueField = 'id';
      // you can change the display template if needed
      comp.displayTpl = new Ext.XTemplate(
          '<tpl for=".">' +
              '{[typeof values === "string" ? values : values["' + comp.displayField + '"]]}' +
              '<tpl if="xindex < xcount">' + comp.delimiter + '</tpl>' +
          '</tpl>'
      );
      comp.picker = null;
 }

If you just need to filter (load) the data in second combox you can do something like this
On the select event of the first combobox prepare the second one to filter the data
combobox2.queryData = [{ property: 'fieldName', value: value}];
combobox2.reset();
combobox2.doQuery(combobox.queryData);

where combobox2 is a reference to the activated combo and value a propertyvalue from the combo. To ensure the use of your new query use
combobox2.on('beforequery', function (e) {
    e.query = e.combo.queryData;
});

Answer: For the second combobox, configure a combobox for each model type. Hide or show the appropriate combobox as a selection is made in the first combobox.


Complement of saturated set

Question: Let $A$ be an integral domain and $S \subset A$ a saturated subset (multiplicative subset s.t. if $ab \in S$ then $a \in S$ and $b \in S$). Would you please supply a hint, how to prove that $A \setminus S$ is a union of prime ideals?
Comment: For $a\notin S$ the ideal $aA$ is disjoint from $S$. Take an ideal that is maximal among those containinig $aA$ and disjoint from $S$ (why does such a maximal ideal exist? what sort of ideal is it?).
Comment: There isn't in general such a thing as "the" saturated subset, so rather than "its saturated subset" that should be " *a* saturated subset".
Comment: @Arturo: you are right, of course, but I'm pretty sure that Artem expressed himself the way he did, not because of a mathematical misconception, but because in his native Russian there are no articles.He wrote "its saturated subset" and very probably meant  "*a* saturated subset of it".
Comment: You can also note that if $a \notin S$, then $S^{-1}(a)$ is a proper ideal of $S^{-1}A$.
Comment: Thanks to all. Solved this (as far as I understand). @Georges I guess it would be better to trnslate your comment to answer. It's exactly what I wanted.
Comment: @Arturo: Georges is pretty right about articles.
Comment: @Artem: My apologies if it came across badly.
Comment: @Arturo That was perfectly well. This artiles' related stuff is quite interesting and I'll try to take your comment into account in the future. Thank you!
Answer: At Artem's request I'm transforming my comment into an answer.
Take any $a\notin S$. The principal ideal $aA$ it generates is disjoint from $S$, that is $aA\cap S=\emptyset$ (why?). Take a maximal element $I$ in the set of ideals of $A$ containing $aA$ and disjoint from $S$ (why does such a maximal ideal exist?). This ideal has a property that allows you to conclude (in case of difficulty, look for inspiration at the proof of Proposition 1.8 page 5 in Atiyah-Macdonald's Introduction to Commutative Algebra).

Complement of saturated set


Recursively iterate through a nested dict with list, and replace matched values

Question: I want to make a function that iterate through a nested dict that include list. For each value that match with a keyword, the function replace it with another keyword.
It's not important if the function return another dict or if it change the main dict.
I tried to separate the case:
- if the data is a dict, make something
- if the data is a list, make something else
DICT:

data_dict = {
  "name": "AAAAAA",
  "content": "BBBBBB",
  "dat": [
    {
      "author": {
        "name": "CCCCCC",
        "surname": "DDDDDD",
      },
      "title": "FFFFFF",
      "color": 15258703,
      "fields": [
        {
          "name": "GGGGGG",
          "value": "HHHHHH",
        },
        {
          "name": "IIIIII",
          "value": "JJJJJJ",
        }

      ],
      "thumbnail": {
        "url": "KKKKKK"
      },
      "image": {
        "url": "LLLLLL"
      },
      "footer": {
        "text": "MMMMMMM",
        "icon_url": "NNNNNN"
      }
    }
  ]
}

Now I'm just trying to change each value to see if I'm iterate as well.
I can print all the data_dict with value changed, but I can't manage it in a dict...

def recursive_replace_valuer(data, match, repl):

    if isinstance(data, list):
        for l in data:
            recursive_replace_valuer(l, match, repl)
            if isinstance(l, dict):
                recursive_replace_valuer(l, match, repl)

    elif isinstance(data, dict):
        for k,v in data.items():
            recursive_replace_valuer(v, match, repl)
            data[k] = '______'
        print(data)

recursive_replace_valuer(data_dict, 'a','a')

Answer: The function should recursively apply the function to the values in a dict or a list until the input data is neither a dict nor a list, at which point return the replacement value repl if the given data match the given search string match:
def replace(data, match, repl):
    if isinstance(data, dict):
        return {k: replace(v, match, repl) for k, v in data.items()}
    elif isinstance(data, list):
        return [replace(i, match, repl) for i in data]
    else:
        return repl if data == match else data

Or, to replace the original data in-place, make the function iterate through the given dict or list and replace a value by the key (for dict) or index (for list) if it's a match, and recursively apply the function to the value:
def replace(data, match, repl):
    if isinstance(data, (dict, list)):
        for k, v in (data.items() if isinstance(data, dict) else enumerate(data)):
            if v == match:
                data[k] = repl
            replace(v, match, repl)

Comment: What if the value is a `set`?
Comment: @BasilMusa Just add `elif isinstance(data, set): return {replace(i, match, repl) for i in data}`
Comment: dictionary keys changed during iteration
Comment: @AmulyaAcharya Are you talking about the error "RuntimeError: dictionary changed size during iteration"? Can you provide an example input dataset that can cause this error? All that `data[k] = repl` is doing is to assign a new value to an existing key, so I don't see how it can possibly change the size of the dict to produce that error.


Access imagefield file object during node create/update

Question: I have a content type with an imagefield. I need to get a reference to the file object during node save or update, so I can do something with it.
function foo_node_presave($node){
    if ($node->type ==='foo'){
        $filename = $node->original->field_foo_image['und'][0]['filename'];
    }

In the above code, $filename isn't populated yet when a new node is being created. It does work during a node update if there was already a file in that field.
How can I get a reference to the file object in a filefield/imagefield in a hook during node creation?
Answer: Even if the field hasn't been updated yet you should have access to the fid column (the file ID), which you can use in conjunction with the file_load() function to get the filename:
// Load a file object based on the fid column fo the field.
$file = file_load($node->field_foo_image[$node->language][0]['fid'];

// Get the filename.
$filename = $file->filename;


touch event in box2d?

Question: Is there any way to identify, whether a touch point is in a body in the world??
Answer: I am afraid you don't need to do something like that, because a body is always in the upper layer than the world if it exists, so if the point is both in a body and in the world, it must be the body to respond.

touch event in box2d?


Are $U_{13}$ and $\Bbb{Z}_{12}$ isomorphic? Prove your answer correct.

Question: I am trying to find a quick way to show that it is not the case.
$Ord(\Bbb{Z}_{12})=12$
$Ord(U_{13})=12\times13^{k-1}, k\in \Bbb{Z}_{\ge0}$
Since the order of the groups are not identitical (except for $k=1$), the groups are not isomorphic.
Comment: Is $U_{13}$ the group of units of $\mathbb{Z}/13\mathbb{Z}$?
Comment: Yes , that is correct.
Comment: Well if $p$ is prime then $U_{p}$ is cyclic of order $p-1$. In your case one can verify that $2$ is a generator of $U_{13}$.
Comment: The order of $U_{13}$ is $12$ (since $13$ is prime), and $U_{13}$ is generated by the element $2$, for example. Now, any isomorphism from $U_{13}$ to $\mathbb Z_{12}$ will be entirely specified by where the element $2$ goes. Can you work from here?
Comment: Aston Villa, yes I can. Thank you.
Answer: Note that $|\mathbb{Z}_{12}|=12$ and $|\mathbb{U}_{13}|=\phi(13)=12$ where $\phi$ denotes the Euler phi function.
Since both $\mathbb{Z}_{12}$ and $\mathbb{U}_{13}$ are both cyclic and cyclic groups of same order are isomorphic, $$\mathbb{Z}_{12}\cong \mathbb{U}_{13}$$