Is it possible to map mathematics without advanced set theory?

Question: I wish to make a large digraph (network) linking various proofs together in mathematics from, say, the definition of a group to Galois theory. I got in my head that I wanted to do this after reading about the "truth mines" in Greg Egan's book, diaspora, which I would wholeheartedly recommend.
The issue is, at the moment I could only start this graph from naive set theory, starting with the "definition" of a set, of the natural numbers, and so on (though definition stretches things as I could not rigorously define a set as it stands). It seems like this potentially invites danger as there's a reason such set theory is called naive, it leads to paradoxes.
If I were to start this graph from naive set theory, could I then substitute in more advanced material later on and amend it, so for instance eventually linking the ZFC axioms to where I had previously started my graph? Or is naive set theory so far from the truth that I could not possible hope to untangle it?
I understand that this is a strange question, but don't you think it would be amazing to be able to see a map of the mathematical landscape?
Comment: You can make a map of whatever you want, obviously, so it's fine with me if you simplify the set theory on your map, or leave it out altogether! But I'm having trouble imagining what you want your map to look like. Is it that the nodes are mathematical statements, and an arrow "P-->Q" represents that "Q is provable from P"? Or something else?
Comment: Yes, so if a proof of one theorem is reliant on another, a directed line is drawn from one to the other. I was thinking of having as either a hierarchical upwards looking graph or a radial one, not sure which would look better
Comment: In addition if the understanding of a statement or proof requires knowledge of a definition, lines are drawn from the definition
Comment: Perhaps even notation too but that's murkier
Comment: Most of the mathematics you learn at the undergraduate level was developed prior to the development of what you might call "advanced set theory." It was certainly not a required course in my day. You could probably be quite a competent mathematician today without ever having encountered say, the axioms of foundation or infinity. Don't get me wrong. I find set theory to be fascinating and have devoted perhaps thousands of hours to it in my spare time.
Comment: Just looked at current course requirements for pure math at my alma mater: Still mostly analysis, some algebra and combinatorics, but no advanced set theory.
Comment: I think [proofwiki](https://proofwiki.org/wiki/Main_Page) is similar in spirit to what you want to create, so maybe check out how they deal with foundational issues.
Answer: That depends what you wish to include in this graph.
If you wish to limit yourself to results that were proved before 1878, which include some of the seminal results of Galois theory mentioned on this page, and many results in basic analysis, then by all means, naive set theory is more than enough. You could probably extend the range to 1900, or even slightly later without having to worry about encountering anything advance in set theory.
If your graph will include, from "group" a "Whitehead group" and then the question "Is every Whitehead group free?", then you cannot proceed further without axiomatic set theory, because to prove or disprove whether or not every Whitehead group is free, you will need to assume axioms which extend from $\sf ZFC$ and certainly go well beyond naive set theory.
Perhaps you'd like to prove that every Abelian group with a discrete norm is free. But the only proof I am aware of, for the general case, uses heavy set theoretic tools (transfinite induction on the cardinals, and Shelah's compactness theorem for singular cardinals).
Mmmm, okay, maybe you'd rather avoid these two questions. But then you can ask yourself, suppose that you have $\aleph_1$ sets of reals, each of Lebesgue measure $0$. Is their union a null set also? Again, you'd have to defer the question until additional set theoretic axioms have been stated. What about meager sets? Well, same thing.
And so on and so forth. Can you map mathematics without appealing to advanced set theory? Sure, but depends on what you call mathematics, if your mathematics is solely based on finite objects, or the natural numbers, or pre-20th century... sure. You can probably avoid it. But if you don't want to live in the past, then you will have, at some point, to run into axiomatic set theory in one way or another.
Because set theory is the tool through which we understand infinite sets, and when you ask something about "every ring" or "every $R$-module" or "every group", you ask a question about pretty large infinite sets, and then some.
Answer: Well, your graph is never going to be a complete description of all of mathematics! So a simple answer is that you shouldn't worry about it too much, and just focus on what's useful to you.
In other words, if what you're really interested in is Galois Theory, then maybe you want to have a node that represents $P$, where $P$ is the statement "$S_5$ is not solvable." There'd probably be an arrow to $P$ from the node that represents the statement "$A_5$ is simple," as well as an arrow to $P$ from the statement "$A_5$ is not abelian", and others as well. Each of these nodes would have arrows pointing to them from other nodes, too, but the point is that it's up to you how far back you want to continue tracing these chains before you're not interested anymore.
If it were me, I believe I'd quit long before any propositions of pure set theory, naive or otherwise, really showed up. In fact, what you could do is just declare that "set theory" is going on in the background of your entire graph. (This is really what mathematicians do most of the time in practice; rarely do we explicitly state all of our axioms and methods of inference unless we are specifically interested in that type of mathematics.)
This project could definitely be illuminating and certainly could help you to understand an area of mathematics better, but probably not if you're extremely worried about getting every detail correct and including absolutely everything.  Just try it and see what you get, and then add in more and more details/nodes/edges as you go.  Enjoy!
Comment: Hypothetical question here, apart from mere time constraints and the fact that one person could never comprehend all of mathematics, at least certainly not quickly enough to add nodes before ever more information was created to be added, is there any reason such a map of all of our current mathematics could not be created?
Comment: @Nethesis: It is too large to be a setmap, unless you do not mind a serious contradiction.


Hooking up UIButton to closure? (Swift, target-action)

Question: I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, action: Selector, forControlEvents: UIControlEvents) function. This uses the Selector construct presumably for backwards compatibility with Obj-C libraries. I think I understand the reason for @selector in Obj-C – being able to refer to a method since in Obj-C methods are not first-class values.
In Swift though, functions are first-class values. Is there a way to connect a UIButton to a closure, something similar to this:
// -- Some code here that sets up an object X

let buttonForObjectX = UIButton()

// -- configure properties here of the button in regards to object
// -- for example title

buttonForObjectX.addAction(action: {() in

  // this button is bound to object X, so do stuff relevant to X

}, forControlEvents: UIControlEvents.TouchUpOutside)

To my knowledge, the above is currently not possible. Considering that Swift looks like it's aiming to be a quite functional, why is this? The two options could clearly co-exist for backwards compatibility. Why doesn't this work more like onClick() in JS? It seems that the only way to hook up a UIButton to a target-action pair is to use something that exists solely for backwards compatibility reasons (Selector).
My use case is to create UIButtons in a loop for different objects, and then hook each up to a closure. (Setting a tag / looking up in a dictionary / subclassing UIButton are dirty semi-solutions, but I'm interested in how to do this functionally, ie this closure approach)
Comment: http://stackoverflow.com/questions/26449053/strongly-typed-selectors-in-swift/
Answer: You can replace target-action with a closure by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained.
This is a similar solution to the one in n13's answer. But I find it simpler and more elegant. The closure is invoked more directly and the wrapper is automatically retained (added as an associated object).
Swift 3 and 4
class ClosureSleeve {
    let closure: () -> ()

    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }

    @objc func invoke() {
        closure()
    }
}

extension UIControl {
    func addAction(for controlEvents: UIControlEvents = .primaryActionTriggered, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
    }
}

Usage:
button.addAction {
    print("Hello")
}

It automatically hooks to the .primaryActionTriggered event which equals to .touchUpInside for UIButton.
Comment: This was what worked best for me. I've adapted it and added the possibility to remove the event listener as well as register a listener that removes itself once the action is invoked. Here: https://gist.github.com/PEZ/e4a790870855a0bb3a45da2da8f71aa3
Mentioning it because  I'm new to Swift and don't really know what I am doing, so any feedback is welcome.
Comment: Nice idea to have a `listenOnce` listener. I am not sure I have a use for it but it might come handy in some use cases. Feedback added to github.
Comment: make sure not to capture self inside the closure otherwise you will leak the memory
Answer: The general approach for anything you think should be in the libraries but isn't: Write a category. There's lots of this particular one on GitHub but didn't find one in Swift so I wrote my own:
=== Put this in its own file, like UIButton+Block.swift ===
import ObjectiveC

var ActionBlockKey: UInt8 = 0

// a type for our action block closure
typealias BlockButtonActionBlock = (sender: UIButton) -> Void

class ActionBlockWrapper : NSObject {
    var block : BlockButtonActionBlock
    init(block: BlockButtonActionBlock) {
        self.block = block
    }
}

extension UIButton {
    func block_setAction(block: BlockButtonActionBlock) {
        objc_setAssociatedObject(self, &ActionBlockKey, ActionBlockWrapper(block: block), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        addTarget(self, action: "block_handleAction:", forControlEvents: .TouchUpInside)
    }

    func block_handleAction(sender: UIButton) {
        let wrapper = objc_getAssociatedObject(self, &ActionBlockKey) as! ActionBlockWrapper
        wrapper.block(sender: sender)
    }
}

Then invoke it like this:
myButton.block_setAction { sender in
    // if you're referencing self, use [unowned self] above to prevent
    // a retain cycle

    // your code here

}

Clearly this could be improved, there could be options for the various kinds of events (not just touch up inside) and so on. But this worked for me.
It's slightly more complicated than the pure ObjC version because of the need for a wrapper for the block. Swift compiler does not allow storing the block as "AnyObject". So I just wrapped it.
Comment: Also note, that the block is retained by self, therefore references to self inside the block will require "unowned self": myButton.onTouchUpInsder { [unowned self] sender in  < block logic > }
Comment: Such a nice piece of code! To add more flavour to this, you can replace UIButton with UIControl and pass 'UIControlEvents' as second parameter to block_setAction, so as to work with other controls too. e.g. textfield's editingChanged.
Comment: How to remove target from here?
Comment: Works great! I did change block_setAction to onTouchUpInside, to reflect the event the block is handling, and to be able to  later add other block events.
Comment: Good point, putting that in the sample code. I wasn't referencing self in the action so did not need that.
Comment: @AkshayGajarlawar ^ That's a really good idea; haven't needed it so far but it would be great. Second parameter would simply default to touchupinside.
Answer: This is not necessarily a "hooking," but you can effectively achieve this behavior by subclassing UIButton:
class ActionButton: UIButton {
    var touchDown: ((button: UIButton) -> ())?
    var touchExit: ((button: UIButton) -> ())?
    var touchUp: ((button: UIButton) -> ())?

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:)") }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButton()
    }

    func setupButton() {
        //this is my most common setup, but you can customize to your liking
        addTarget(self, action: #selector(touchDown(_:)), forControlEvents: [.TouchDown, .TouchDragEnter])
        addTarget(self, action: #selector(touchExit(_:)), forControlEvents: [.TouchCancel, .TouchDragExit])
        addTarget(self, action: #selector(touchUp(_:)), forControlEvents: [.TouchUpInside])
    }

    //actions
    func touchDown(sender: UIButton) {
        touchDown?(button: sender)
    }

    func touchExit(sender: UIButton) {
        touchExit?(button: sender)
    }

    func touchUp(sender: UIButton) {
        touchUp?(button: sender)
    }
}

Use:
let button = ActionButton(frame: buttonRect)
button.touchDown = { button in
    print("Touch Down")
}
button.touchExit = { button in
    print("Touch Exit")
}
button.touchUp = { button in
    print("Touch Up")
}

Comment: just a quick question, shouldn't you make the self in the closure weak reference to avoid the memory leak?
Answer: According to n13's solution, I made a swift3 version.
Hopes it could help some people like me.
import Foundation
import UIKit
import ObjectiveC

var ActionBlockKey: UInt8 = 0

// a type for our action block closure
typealias BlockButtonActionBlock = (_ sender: UIButton) -> Void

class ActionBlockWrapper : NSObject {
    var block : BlockButtonActionBlock
    init(block: @escaping BlockButtonActionBlock) {
        self.block = block
    }
}

extension UIButton {
    func block_setAction(block: @escaping BlockButtonActionBlock, for control: UIControlEvents) {
        objc_setAssociatedObject(self, &ActionBlockKey, ActionBlockWrapper(block: block), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        self.addTarget(self, action: #selector(UIButton.block_handleAction), for: .touchUpInside)
    }

    func block_handleAction(sender: UIButton, for control:UIControlEvents) {

        let wrapper = objc_getAssociatedObject(self, &ActionBlockKey) as! ActionBlockWrapper
        wrapper.block(sender)
    }
}

Answer: This is easily solved using RxSwift
import RxSwift
import RxCocoa

...

@IBOutlet weak var button:UIButton!

...

let taps = button.rx.tap.asDriver()

taps.drive(onNext: {
    // handle tap
})

Edit:
I wanted to acknowledge that RxSwift/RxCocoa is a pretty heavy-weight dependency to add to a project just to solve this one requirement. There may be lighter-weight solutions available or just stick with target/action pattern.
In any case, if the idea of a general purpose declarative approach to handling application and user events appeals to you, definitely give RxSwift a look. It's the bomb.
Answer: UIButton inherits from UIControl, which handles the receiving of input and forwarding to the selection. According to the docs, the action is "A selector identifying an action message. It cannot be NULL." And a Selector is strictly a pointer to a method.
I would think that given the emphases Swift seems to be placing on Closures, this would be possible, but this doesnt seem to be the case.
Answer: You can approach this with a proxy class that routes events through the target / action (selector) mechanism to a closure of your making.  I have done this for gesture recognizers, but the same pattern should hold for controls.
You could do something like this:
import UIKit

@objc class ClosureDispatch {
    init(f:()->()) { self.action = f }
    func execute() -> () { action() }
    let action: () -> ()
}

var redBlueGreen:[String] = ["Red", "Blue", "Green"]
let buttons:[UIButton] = map(0..<redBlueGreen.count) { i in
    let text = redBlueGreen[i]
    var btn = UIButton(frame: CGRect(x: i * 50, y: 0, width: 100, height: 44))
    btn.setTitle(text, forState: .Normal)
    btn.setTitleColor(UIColor.redColor(), forState: .Normal)
    btn.backgroundColor = UIColor.lightGrayColor()
    return btn
}

let functors:[ClosureDispatch] = map(buttons) { btn in
    let functor = ClosureDispatch(f:{ [unowned btn] in
        println("Hello from \(btn.titleLabel!.text!)") })
    btn.addTarget(functor, action: "execute", forControlEvents: .TouchUpInside)
    return functor
}

The one caveat of this, is that since addTarget:... does not retain the target, you need to hold on to the dispatch objects (as done with the functors array).  You don't strictly need to hold on to the buttons of course, as you could do that via a captured reference in the closure, but likely you will want explicit references.
PS. I tried to test this in playground, but could not get sendActionsForControlEvents to work.  I have used this approach for gesture recognizers though.
Answer: The associatedObject and wrapping and pointers and import of ObjectiveC are unnecessary, at least in Swift 3. This works great and is much more Swift-y. Feel free to throw a typealias in there for () -> () if you find it more readable, bit I find it easier to read the block signature directly.
import UIKit

class BlockButton: UIButton {
    fileprivate var onAction: (() -> ())?

    func addClosure(_ closure: @escaping () -> (), for control: UIControlEvents) {
        self.addTarget(self, action: #selector(actionHandler), for: control)
        self.onAction = closure
    }

    dynamic fileprivate func actionHandler() {
        onAction?()
    }
}

Comment: The reason why associated object is used in other solutions is that it is an extension for UIButton. The difference in your solution is that it is using subclassing. That might be a disadvantage - if using a subclass is not possible.
Comment: Yeah the whole point of associatedObject was to avoid making a subclass. An extension is much better as one can simply use it anywhere, on any button. If you use Swift, learn to love extensions - it makes life a lot easier.


Adicionar parametros dinamicamente em uma função JavaScript

Question: Galera, tudo bem?
Estou tentando criar uma função(chamarei de executar) que receba como parâmetro outra função(chamarei de palavra), uma lista de objetos e uma lista de atributos para serem acessados nos objetos da lista.
Esta função "executar" ira executar a função que ela receber como parâmetro, mas como eu não sei quais são os parâmetros que devo passar na função que recebo em "executar", quero uma forma genérica de passar os parâmetros...
Segue código de exemplo:
//Lista com os parametros que quero pegar do objeto
  var listKeyParam = ["nome", "idade", "altura"];

  //Lista de objetos
  var objs = [
    { nome: "Anderson", idade: "21", altura: "1.85" },
    { nome: "Ranger", idade: "18", altura: "1.85" },
    { nome: "Renan", idade: "21", altura: "1.85" },
    { nome: "Guto", idade: "70", altura: "2.15" }
  ];

  //Funcao generica testar o recebimento dos parametros
  function palavra(nome,idade,altura) {
    console.log("nome => ",nome);
    console.log("idade => ",idade);
    console.log("altura => ", altura);
  }

  //Funcao que deve receber uma funcao como parametro,
  //uma lista de objetos e a lista com os atributos que devem ser pegos dos objetos
  function executar(funcao, objs, listKeyParam) {

    objs.forEach((item, index) => {
      let argumentsFunc =[]
      $.each(item,(paramKey,paramValue) => {
        if(listKeyParam.includes(paramKey)) argumentsFunc.push(paramValue);
      });
      funcao(arguments = argumentsFunc);
    });

  }

  //Executando funcao
  executar(palavra, objs , listKeyParam);

Answer: como não conheço o contexto do seu projeto apenas alterei um pouco seu código para passar os parâmetros de forma genérica, como você citou. Basicamente para cada item o Array objs eu procuro as propriedades dentro do item que estão no array listKeyParam e crio um array com estes valores que ficam armazenados na variável argumentos. Depois utilizo o spread operator para passá-los como parâmetro:

//Lista com os parametros que quero pegar do objeto
var listKeyParam = ["nome", "idade", "altura"];

  //Lista de objetos
var objs = [
  { nome: "Anderson", idade: "21", altura: "1.85" },
  { nome: "Ranger", idade: "18", altura: "1.85" },
  { nome: "Renan", idade: "21", altura: "1.85" },
  { nome: "Guto", idade: "70", altura: "2.15" }
];

// Funcao generica testar o recebimento dos parametros
function palavra(nome, idade, altura) {
  console.log("nome => ", nome);
  console.log("idade => ", idade);
  console.log("altura => ", altura);
}

// Funcao que deve receber uma funcao como parametro,
// uma lista de objetos e a lista com os atributos que devem ser pegos dos objetos
function executar(funcao, objs, listKeyParam) {
  objs.forEach(item => {
    const argumentos = listKeyParam
      .filter(key => !!item[key])
      .map(key => item[key]);

    funcao(...argumentos);
  });
}

// Executando funcao
executar(palavra, objs , listKeyParam);

Espero que te ajude ;)
Comment: Cara, muito obrigado! Era exatamente isso que eu estava querendo \õ/
Só não voto na tua resposta pq tenho menos de 15 pontos de reputação huahuahuhua
Comment: @AndersonDuarte muito obrigado, vlw ;)


Unexpected white background on top of carousel images in Bootstrap 4

Question: I don't understand why an unexpected white background appears on top of the bootstrap 4 carousel  when I apply a black background color. How can I correct this unexpected issue? You can find the example of this issue here https://codepen.io/edquijano/pen/MQxogR  Thanks for your input.

        Previous

        Next

Comment: can you share the screenshot of the white background you are talking about? I'm not sure which area you are pointing to.
Comment: Yes there is a codepen. Here it's https://codepen.io/edquijano/pen/MQxogR
Comment: Yes, in the codepen, are you talking about the white background in the navbar? Cuz, I don't see anything wrong with the carousel.
Comment: The white background is on top of the carousel images. The navbar has a white bg.
Comment: I checked from my laptop and, the white bg is there. You can increase the opacity and you'll see the washout img.
Comment: Got what you meant now.
Answer: The carousel is enclosed in an overlay div, which comes with an opacity of 0.6. This makes the images look like they have a whitish cast over them.
You can either choose to remove the overlay div or explicity set opacity:1 on the images.
Here is the output with the overlay div removed: https://codepen.io/anon/pen/XZGevv


create a custom resource in kubernetes using generateName field

Question: I have a sample crd defined as
crd.yaml
kind: CustomResourceDefinition
metadata:
  name: testconfig.demo.k8s.com
  namespace: testns
spec:
  group: demo.k8s.com
  versions:
    - name: v1
      served: true
      storage: true
  scope: Namespaced
  names:
    plural: testconfigs
    singular: testconfig
    kind: TestConfig

I want to create a custom resource based on above crd but i dont want to assign a fixed name to the resource rather use the generateName field. So i generated the below cr.yaml. But when i apply it gives error that name field is mandatory
kind: TestConfig
metadata:
  generateName: test-name-
  namespace: testns
spec:
  image: testimage

Any help is highly appreciated.
Answer: You should use kubectl create to create your CR with generateName.
"kubectl apply will verify the existence of the resources before take action. If the resources do not exist, it will firstly create them. If use generateName, the resource name is not yet generated when verify the existence of the resource." source


Tell me if this iphone app will work

Question: I'm looking at adding iphone support to an application in the simplest way possible. I don't have any experience writing code for the iphone, so I'm trying to keep it very simple. Here's my current concept of what the application will do:
1) Copy some data from the PC to the iphone - this would probably be sent by an application running on the PC, either over wireless or USB (whichever is easier)
2) Store the data locally on the iphone
3) View the data in Safari (or a web browser control in the application)
Originally I was hoping we could just let the user manually copy HTML files to the iphone to view, but apparently Safari on iphone doesn't let you view local files. :( Are there any other "gotchas" with the above ideas that I should be aware of (e.g. "you can't embed a web browser control in your application and have it view local files"), or should this concept work?
Thanks.
Answer: Here's one option: create an app that uses UIWebView. You can read data from files on the disk & also load other data over the net dynamically using javascript.
The advantage is you get the most up to date info via the net, with some navigation either in native app mode (more efficient) or using UIWebView.

Tell me if this iphone app will work


Show that the following mapping is a contraction.

Question: I have the following problem from a past paper:
"Show that the mapping,
$$T(x_1,x_2)=\left(\frac{x_1+2x_2}5-1,\frac{x_1-2x_2}7+1\right)$$
is a contraction on $(\mathbb R^2,d_\infty)$."
I understand that the way to approach this problem is to consider two points in $\mathbb R^2$, say $x=(x_1,x_2)$ and $y=(y_1,y_2)$, and then to consider $d_\infty(T(x),T(y))$, however, I am tripping myself up with the fact that we have both components $x_1$ and $x_2$ included in both arguments of the mapping, and so, I am not too sure how to continue.
On the other hand, if I had the mapping, $T(x_1, x_2) = (\frac{x_1}2,\frac{x_2}3)$, it is easy to see that in this case,
$$d_\infty(T(x),T(y))=d_\infty\left(\frac12|x_1-x_2|,\frac13|y_1-y_2|\right)$$
because each argument of the mapping includes only one of the components of the input vectors.
How should I proceed with the former example?
Comment: Write down $T(x) - T(y)$. Look at each component separately. Since you want an estimate using $d_\infty(x,y)$, it is advisable to write the expression in terms of $(x_1 - y_1)$ and $(x_2 - y_2)$.
Comment: What is $d_{\infty}$ again?  I forgot :)
Comment: If $x=(x_1,x_2)$ and $y=(y_1,y_2)$ then $d_\infty(x,y)=\max\{|x_1-y_1|,|x_2-y_2|\}$
Comment: Then, $d_\infty(T(x),T(y))=d_\infty(\frac15(x_1-y_1+2(x_2-y_2),\frac17(x_1-y_1-2(x_2-y_2))$? Is that correct?
Comment: You forgot to close a couple of parentheses, but the essence is correct.
Answer: Let's denote for convenience $\Delta x=y-x$, so that $y=x+\Delta x$, and consider
$$
\Delta T=T(x+\Delta x)-T(x)=(\Delta T_1, \Delta T_2)=\Bigl(\frac{\Delta x_1+2\Delta x_2}{5},\frac{\Delta x_1-2\Delta x_2}{7}\Bigr).
$$
We need to estimate
$$
d_\infty(T(y),T(x))=\max\{|\Delta T_1|,|\Delta T_2|\}.
$$
Let's do one component at at time
$$
|\Delta T_1|=\Bigl|\frac{\Delta x_1+2\Delta x_2}{5}\Bigr|\le\frac15\underbrace{|\Delta x_1|}_{\le d_\infty(y,x)}+
\frac25\underbrace{|\Delta x_2|}_{\le d_\infty(y,x)}\le \Bigl(\frac15+\frac25\Big)d_\infty(y,x)=\frac35 d_\infty(y,x).
$$
Similarly,
$$
|\Delta T_2|=\Bigl|\frac{\Delta x_1-2\Delta x_2}{7}\Bigr|\le
\frac17\underbrace{|\Delta x_1|}_{\le d_\infty(y,x)}+
\frac27\underbrace{|\Delta x_2|}_{\le d_\infty(y,x)}\le \Bigl(\frac17+\frac27\Big)d_\infty(y,x)=\frac37 d_\infty(y,x).
$$
Therefore
$$
d_\infty(T(y),T(x))=\max\{|\Delta T_1|,|\Delta T_2|\}\le\max\left\{\frac35 d_\infty(y,x),\frac37 d_\infty(y,x) \right\}\le\frac35 d_\infty(y,x).
$$
Answer: $$
\begin{align}
&d_\infty[T(x_1,x_2)-T(y_1,y_2)]\\
&=d_\infty\left[\left(\frac{x_1+2x_2}5-1,\frac{x_1-2x_2}7+1\right)-\left(\frac{y_1+2y_2}5-1,\frac{y_1-2y_2}7+1\right)\right]\\
&=d_\infty\left[\left(\frac{(x_1-y_1)+2(x_2-y_2)}5,\frac{(x_1-y_1)-2(x_2-y_2)}7\right)\right]\\
&=\max\left[\left|\frac{(x_1-y_1)+2(x_2-y_2)}5\right|,\left|\frac{(x_1-y_1)-2(x_2-y_2)}7\right|\right]\\
&\le\max\left[\,\tfrac15\left|x_1-y_1\right|+\tfrac25\left|x_2-y_2\right|,\tfrac17\left|x_1-y_1\right|+\tfrac27\left|x_2-y_2\right|\,\right]\\[3pt]
&=\tfrac15\left|x_1-y_1\right|+\tfrac25\left|x_2-y_2\right|\\[3pt]
&\le\tfrac15\max\left[\,\left|x_1-y_1\right|,\left|x_2-y_2\right|\,\right]+\tfrac25\max\left[\,\left|x_1-y_1\right|,\left|x_2-y_2\right|\,\right]\\[3pt]
&=\tfrac35d_\infty\left[x_1-y_1,x_2-y_2\right]
\end{align}
$$


Continuous functions with specified area under them in $[0,1]$

Question: Prove that there is only one continuous function $f:[0,1]\to\mathbb{R}$ satisfying
$$\int_0^1 f(x)(1-f(x))\,dx=1/4.$$
I am able to see that the constant function $f(x)=1/2$ satisfies the hypotheses but I just can't prove uniqueness. Help please.
Answer: Hint. Note that
$$0\leq \int_0^1 \left(\frac{1}{2}-f(x)\right)^2\,dx=\int_0^1 \left(\frac{1}{4}-f(x)+f(x)^2\right)\,dx=\frac{1}{4}-\int_0^1 f(x)(1-f(x))\,dx.$$
Comment: Nice simple answer.
Answer: Hint
For every real number $u$, $$u(1-u)\le {1\over 4}$$so that $$f(x)[1-f(x)]\le {1\over 4}$$
Comment: Thank you for your help
Answer: $f(x)=1/2$ qualifies.
Assume there is another continuos function $g(x)$
Set $g(x):=1/2+h(x)$;
$\int_{0}^{1}((1/2)+h(x))(1/2-h(x))dx=$
$\int_{0}^{1}((1/4)-h^2(x))dx=$
$(1/4)-\int_{0}^{1}h^2(x)dx;$
$h(x)$ continuous implies $h(x) \equiv 0$.


Não consigo visualizar a pagina jsp de um projeto Spring MVC

Question: Não consigo visualizar a pagina form.jsp
estou colocando a seguinte URL   http://localhost:8080/Loja/
Com essa URL ele somente visualiza a pagina hello-world.jsp
eu até coloco o seguinte endereço  http://localhost:8080/Loja/produtos/form mas gera erro, aonde será que estou errando.
aqui está o meu projeto completo;
https://github.com/wladimirbandeira/Loja/tree/master/Loja
part1;
public class ServletSpringMVC extends AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    // esse pedaço do código informa qual pagina ira ser mapeada
    @Override
    protected Class<?>[] getServletConfigClasses() {

        return new Class[]{AppWebConfiguration.class};
    }

    // esse código mapea o projeto
    @Override
    protected String[] getServletMappings() {
        // TODO Auto-generated method stub
        return new String[] {"/"};
    }

part2;
@EnableWebMvc
@ComponentScan(basePackageClasses={HomeController.class})
public class AppWebConfiguration {

    //esse pedaço do código informa aonde está a pagina dentro pacote especifico

    @Bean
    public InternalResourceViewResolver
        internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

part3;
@Controller
public class HomeController {

    @RequestMapping("/")
    public String index(){

        System.out.println("carregando produto");
        return "hello-world";// essa é a pagina que está sendo visualizada
    }

Answer: Boa tarde, grande da uma olhada na tua configuração do arquivo spring.xml e se você configurou a welcome-list-file no web.xml, mas caso a configuração tenha sido feita por classes anotadas ou extendidas (beans) da uma olhada se na classe de configuração do spring mvc você configurou o sufix e o prefix que ele vai informar para o servidor interpretar e se você configurou o welcome file para o que você deseja.
Ok, entendi agora, no caso você precisa adicionar a página que você quer carregar na pasta views, no teu controller quando coloca o request mapping ("/") ele está dizendo que toda requisição feita para a url http://localhost:8080/Loja/ será tratada por aquela classe e no método como o retorno é uma string, esse retorno representa o nome da view que após juntar com o prefix .jsp que foi configurado na classe AppWebConfiguration ficará hello-world.jsp, ou seja, ele irá carregar na tela a view retornada pelo método, caso você queira subistituir essa view por outra basta implementar um novo método com um outro request mapping ou apenas mudar o retorno para o nome da página que deseja carregar na tela, se você tem uma página index.jsp que queira carregar ela deve estar dentro da pasta views e no retorno do método você deve informar o retorno como index.
Comment: acabei de atualizar minha postagem e coloquei anotações no código para você entender, dá uma olhada por favor para me ajudar melhor


Android N Multi-Window and AdView

Question: How are we supposed to show Admob ads in the Multi-Window feature introduced in Android N? The ads are logging that there isn't enough space to show the ad.
Any thoughts?
Comment: This is a good point for sure. I'm sorry I can't help you more.
Comment: Did you try using SmartBanner type of adMob?
Comment: @ChrisK. Yes, I always use `SMART_BANNER`.
Comment: In a couple of relative questions point that fixed dimensions are required. I.e. http://stackoverflow.com/a/26597854/2104724. This stands for tablets that support multi window screens, but I guess that this will happen in N too.
Comment: @ChrisK. Am I allowed to make the AdView smaller? I don't think that really is a good idea... I don't want to get banned because of some reason.
Answer: I think it was fixed in one of the latest updates. The ads now appear for me when in multi-window.

Android N Multi-Window and AdView


Pathauto and taxonomy

Question: I use the default taxonomy view (with default path: /taxonomy/term/%) to display videos that have been categorized at the time of their upload. The viewer has access to an exposed filter that allows him to select like 10, 30 or 40 video thumbnails per page (default is 10.)
The Pathauto taxonomy pattern for all video paths is:
[term:vocabulary]/[term:name]
Token is enabled.
The url of the landing page is correctly displayed www.example.com/videos/sports when the vocabulary "videos" and the term "sports" are selected through a menu.
But if, on that same page, I select to view 30 video thumbnails per page instead of 10, the url changes to:
www.example.com/taxonomy/term/1989/0?items_per_page=30
This appears normal since the the view path is /taxonomy/term. The content displayed is correct, but the page theming is totally out of wack.
How do I keep the url at www.example.com/videos/sports/0?items_per_page=30 ?
Shouldn't Pathauto handle this?
Answer: Again, I will give my own answer here:
After reading about tokens, pathauto and views, it appears that exposed filters DO NOT work with path (dixit Merlinofchaos in https://drupal.org/node/1257952#comment-4898854 .) So what I am experiencing is normal.
However, views have a "Use Ajax" option that is specifically there for exposed filters. Enabling it solves the issue and keep the url clean (without the *0?items_per_page=30* part.)
It does so because ajax does not refresh the page, so the url remains the same (www.example.com/videos/sports in this case.)   :)

Pathauto and taxonomy


Why do Homeomorphisms imply "no tearing" and "no gluing"?

Question: Is it true that continuity between topological spaces is what's responsible for "no tearing" and bijectivity is responsible for "no gluing"? The answer in this post: Is it correct to think about homeomorphisms as deformations? says that this is the truth.
However, a comment to that answer said that ""gluing together" implies the continuity of $f^{−1}$  (instead of bijectivity)"
I read in a comment from a separate post:What is the intuition behind homeomorphism, especially behind the geometrical notion of "gluing together"?  which also says that ""gluing together" implies the continuity of $f^{−1} $"
I don't quite know which to be true. I can see how, for example, if two points are mapped to a single point, that would in a sense behave as gluing and would imply non-bijectivity.
However, I can also see gluing in a sense as reverse tearing, which would imply inverse continuity is responsible for gluing. Are they both somehow responsible?
Is it true that no tearing and no gluing is the reason why holes are preserved in homeomorphisms? If only bicontinuity is responsible for hole preservation, what role does bijectivity play in homeomorphisms?
Lastly, in a topological sense, can the reason for no tearing done by continuous functions be thought of as continuity preserving topological indistinguishability? Or, is preservation of connected spaces the only way of implying no tearing? I always read that continuity is about close points mapping to close points. I'll write out the indistinguishability preservation proof:
suppose $ f:(X, \mathcal{T}_x) \to (Y, \mathcal{T}_y)$ is continuous and that $f(x_1) \in U \in \mathcal{T}_y$
$\Rightarrow x_1 \in f^{-1}(U) \in \mathcal{T}_x$ by definition of pre-image and continuity
let $x_1$ and $x_2$ be indistinguishable
$\Rightarrow x_2 \in f^{-1}(U)$
$\Rightarrow f(x_2) \in U$
$\Rightarrow f(x_1)$ and  $f(x_2)$ are indistinguishable
I believe this proof in a metric sense implies that points that are infinitesimally close/distance is zero to each other get mapped to points that are infinitesimally close/distance is zero to each other because if two points share every neighborhood, this must hold true for arbitrarily small neighborhoods. In topological spaces with no distance, it's best to refer to these points as indistinguishable rather than categorize by distance. This seems as a valid concept of no tearing because it sort of tells me that connectedness between points is preserved like a web or grid holding the points together, rather than connectedness between subsets. If there is a hole in a topological space, I don't necessarily see the space as having to equal disjoint subsets, which makes me wonder if this indistinguishability proof better describes preservation of tearing/gluing/holes verses the traditional preservation of connectedness of spaces by continuous functions.
Comment: I think the commenter is "less right". If there is glueing, then $f$ is not bijective, and there is no function $f^{-1}$, the continuity of which we could study. The answerer there is using the (standard but kind of neat) lemma saying that a continuous bijection from a compact space to a Hausdorff space is automatically a homeomorphism. Hence the continuity of $f^{-1}$ is never in doubt. Of course, that limits the scope of the answer to compact+Hausdorff, but that covers the scope of "no tearing or glueing" quite well, I think.
Comment: Looking for ***the truth*** of an intuition such as "no tearing" or "no gluing" seems a quixotic quest.
Answer: I think the best way to think about this is if we take a map like $f : [0, 1) \to \mathbb{T}$ (the complex unit circle) given by $f(t) = e^{it}$, what this does is take the half open interval, and glue the two ends together. This is still bijective, and the forwards map is continuous, but the inverse map is not. The reason is that the forwards map took points that were far apart and made them arbitrarily close (gluing), so the inverse then takes those arbitrarily close points and makes them far apart. In this sense, we are not allowed to tear because of forwards continuity, and we are not allowed to glue (even bijectively!) because of inverse continuity. Tearing takes arbitrarily close points and makes them far, violating continuity, and gluing takes points which are far apart and make them arbitrarily close, which in the inverse, takes arbitrarily close points and makes them far, violating continuity.
The reason for the requirement that our map be a bijection is so that we can talk about the inverse at all! if our function is not bijective, $f^{-1}$ doesn't make sense.
Also note that this is a loose heuristic that is (in my opinion) only really helpful sufficiently nice subspaces of $\mathbb{R}^n$, so don't get too involved in doing it with gross arbitrary subspaces - think of grabbing some playdough and stretching/squishing it without tearing or gluing, nothing more. If anyone has a way to think about it with "gross" topological spaces, I'd appreciate a comment.
Comment: Thanks for this. That clears it up. Is preservation of topological indistinguishability under continuous functions not a way to think about it for gross topological spaces? I believe indistinguishable points is the topological generalization of "arbitrarily close".


Is there a name for this polynomial theorem?

Question: I came across this question:

Let $P$ be a polynomial with real coefficients and $z$ be a complex number. It is known that $P(z) = 2 + i$, what is the value of $P(\overline{z})$.

The answer is $2 - i$, which just on first glance seems like some combination of the remainder theorem and the conjugate root theorem, but I have no idea if this is a known theorem with a name, or how to go about proving it, but from testing a bunch of examples, it seems to be the case that in general if $P(z) = a + bi$, then $P(\overline{z}) = a - bi$. Does anyone have a proof for this, or know what this is called?
Comment: It works like this because conjugation is an automorphism of the complex numbers which fixes the real numbers.
Answer: For a polynomial with real coefficients $P(\bar{z})=\overline{P(z)}$.
Let $$P(z)=a_0+a_1z+a_2z^2+\cdots+a_nz^n,\ a_i\in\mathbb{R}$$
Then $P(\overline{z})=a_0+a_1\overline{z}+a_2\overline{z}^2+\cdots+a_n\overline{z}^n$.
Now $z=re^{i\theta}$ for $r=|z|$ and $\theta=\arg(z)$. Then $\overline{z}=re^{-1\theta}$. Hence $\overline{z^k}=\overline{re^{ik\theta}}=re^{-ik\theta}=\overline{z}^k$. Thus we have $$\overline{z^k}=\overline{z}^k\ \ \forall\ z\in\Bbb{C}$$.
Also $$\overline{cz}=c\overline{z}\ \ \forall\ z\in\Bbb{C},c\in\Bbb{R}$$
And finally $$\overline{z_1+z_2}=\overline{z}_1+\overline{z}_2$$
Combining these three results we get $$\overline{a_0+a_1z+a_2z^2+\cdots+a_nz^n}=a_0+a_1\overline{z}+a_2\overline{z}^2+\cdots+a_n\overline{z}^n$$
Answer: It is just as you said a simple corolaly. $a\bar z^n=\overline{az^n}$, for any real $a$ ,(if $a$ is real then note that $\overline a=a$). Now add the monomials and you have what you need.


How to upload images to google drive from NodeJS API

Question: I have written API and got to upload in Heroku server. When I push the data in the Heroku after changes then all the images are gone. I don't know why they were not shown. I found some other option like images upload in Google Drive directly and I have gone through relevant documentations. I couldn't find any resources related to this.
Can anyone help me out with references or suggestions to upload files to Google Drive?
Answer: @KarlR's answer is helpful, but the code has it's own faults. (The scope does not support for file uploads). Let me explain this step by step so that you can easily upload a file to Google Drive.
Step 1: Go to Google Drive API V3 NodeJS quickstart
Follow the initial steps and see whether it works. Then proceed to the next step.
Step 2: Have a function named uploadFile and change the scope to suit the uploads. The code segment is given below.
In the below example, the file is fetched from files/photo.jpg and is renamed as photo.jpg and uploaded to the root folder of Google Drive.
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
const TOKEN_PATH = 'token.json';

/**
 * Create an OAuth2 client with the given credentials, and then execute the given callback function.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });
    console.log('Authorize this app by visiting this url:', authUrl);
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    rl.question('Enter the code from that page here: ', (code) => {
        rl.close();
        oAuth2Client.getToken(code, (err, token) => {
            if (err) return console.error('Error retrieving access token', err);
            oAuth2Client.setCredentials(token);
            // Store the token to disk for later program executions
            fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) return console.error(err);
                console.log('Token stored to', TOKEN_PATH);
            });
            callback(oAuth2Client);
        });
    });
}
/**
* Describe with given media and metaData and upload it using google.drive.create method()
*/
function uploadFile(auth) {
  const drive = google.drive({version: 'v3', auth});
  const fileMetadata = {
    'name': 'photo.jpg'
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg')
  };
  drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id'
  }, (err, file) => {
    if (err) {
      // Handle error
      console.error(err);
    } else {
      console.log('File Id: ', file.id);
    }
  });
}

fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), uploadFile);
});

Step 3: Change the name of the file being uploaded
In the uploadFile funciton, change the name property.
const fileMetadata = {
        'name': 'any_name_you_like'
};

Step 4: Upload different file types
You only have to change the following code segment in the uploadFile function. See mostly used mime types for your preferred file extension.
const media = {
     mimeType: 'any_mime_type',
     body: fs.createReadStream('files/photo.jpg')
};

Step 5: Upload the file to a specific folder on Google Drive
Open the browser and log in to your Google Drive. Go to the specific folder and look at the browser URL. It will look like the following.
https://drive.google.com/drive/u/0/folders/1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl
1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl is the folder ID (parentID). Change the following code segment in the uploadFile function.
const fileMetadata = {
        'name': 'any_file_name',
        parents: ['1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl']
};

Hope this is comprehensive enough for your requirements.


Minimum sum in a 2D matrix choosing contiguous sub arrays from each row

Question: Given is a data set of number of passengers and taxi driver's time taken to cater each passenger, output the minimum time required by the taxi agency to transfer all passengers.
Constraints:

A driver would like to cater to the next consecutive passenger number. (i.e D1 would go with P1, P2 rather than P1, P3. because his contiguous passenger number chain is broken).
A driver once chosen for the task will not be allowed to participate again. (i.e if D1 goes with P1,P2 and D3 goes with P3, D1 is not considered back for P4, D3 can be considered, as P4 will be contiguous with P3).

Input is a m*n matrix, output the minimum time.
Example:
    P1 P2 P3 P4
D1  2  2  1  2
D2  3  1  2  1
D3  4  2  3  1

Output(minimum time) : 6
Explanation :
we can choose D1 for P1,P2,P3 and D3 for P4 (2+2+1+1 = 6)
or we can choose D1 for P1,P2,P3 and D2 for P4 (2+2+1+1 = 6)
or we can choose D1 for P1, D2 for P2,P3 and D3 for P4 (2+1+2+1 = 6)
or we can choose D1 for P1 and D2 for P2,P3,P4 (2+1+2+1 = 6)
or we can choose D2 for P1,P2, D1 for P3, and D3 for P4 (3+1+1+1 = 6)
PS: It's a modified Assignment problem, but unable to crack the solution.
Comment: People have been posting this question with different descriptions over and over during the past few days. Techgig codegladiators semi final round1 techgig.com/codegladiators . The problem is active till july 6th for submissions. (An accepted solution is actually posted on SO, but not under the algorithm tag.)
Comment: Yea, I should have probably posted this after 6th of July. I was just curious to know the solution.
Answer: As you noticed, The only diffrence from a classical assignement problem is that in case of equality, you should maximize ∑Pi==Di.
This can be done by reducing the cost of Mat[i][i] by an infinitesimal number. In practice 1/1024 is enough if n<<1024.
Once you have done this, you can solve your problem using standard algorithms such as the Hungarian Algorithm.


How To Programmatically Create MySQL Databases on Shared Linux Hosting Plans

Question: Is there a sort of reliable way to programmatically create MySQL databases and MySQL users on shared Linux hosting plans from a PHP page? For instance, accessing cpanel or phpmyadmin through an API or hook if I know my cpanel access information and/or my FTP information?
Occasionally I see this with some sites and products but don't know how they do it.
Answer: Thanks to @Alex C who got me on the right track. The following will work with many shared hosting plans, but you'll want to check with their policies on this first. Mine wrote me back in a tech support ticket and said, "You have to automate through a cpanel script." So, that's what this is.
In the example below, I would have already purchased root.com as my main root domain of my shared hosting plan. I would be wanting to setup a database named "user_myexample" with password "myexample" assigned with full privileges to user "user_myexamp". If the "user_" prefix and "myexamp" looks odd -- it's because cpanel has a prefix based on the root user's user account into cpanel, and the database user name can only be 7 characters maximum.
To connect to Cpanel to make this happen, I entered a cpanel homepage URL (which varies with hosting plan) so that it could be parsed and reused. Also, I provided my root.com's cpanel user/pass information.
The echo statements are just the output response whether each HTTP GET request worked or not. You may want to inspect that to see if there's something you can parse out of that output for success/failure.
Note some hosting plans block file_get_contents connecting to a URL, so you may have to switch with fopen($sURL, 'r') or Curl API.
<code><?php

// @ input vars
$sPastedCpanelHomepageURL = 'https://root.com:2083/frontend/x3/index.html';
$sNewDB = 'myexample';
$sNewDBUser = 'myexamp'; // must be 7 chars max
$sNewDBPass = 'myexample';
$sCPanelUser = 'user';
$sCPanelPass = 'pass';

// @ processing
$sCP = dirname($sPastedCpanelHomepageURL);
$sCP = str_replace('://','://' . $sCPanelUser . ':' . $sCPanelPass . '@',$sCP);

$sPrefix = substr($sCPanelUser, 0, 7) . '_';

$sTask1 = '/sql/addb.html?';
$sTask2 = '/sql/adduser.html?';
$sTask3 = '/sql/addusertodb.html?';

$sNewDB = urlencode($sNewDB);
$sNewDBUser = urlencode($sNewDBUser);
$sNewDBPass = urlencode($sNewDBPass);
$sCPanelUser = urlencode($sCPanelUser);
$sCPanelPass = urlencode($sCPanelPass);

$sNewDBUser = substr($sNewDBUser, 0, 7);

$asData1 = array(
  'db' => $sNewDB
);
$sData1 = http_build_query($asData1);
$s = file_get_contents($sCP . $sTask1 . $sData1);
echo "$s\n";

$asData2 = array(
  'user' => $sPrefix . $sNewDBUser,
  'pass' => $sNewDBPass,
  'pass2' => $sNewDBPass
);
$sData2 = http_build_query($asData2);
$s = file_get_contents($sCP . $sTask2 . $sData2);
echo "$s\n";

$asData3 = array(
  'user' => $sPrefix . $sNewDBUser,
  'db' => $sPrefix . $sNewDB,
  'update' => '',
  'ALL' => 'ALL'
);
$sData3 = http_build_query($asData3);
$s = file_get_contents($sCP . $sTask3 . $sData3);
echo "$s\n";
</code>
Answer: Giving shared user permissions to do anything outside of cPanel seems to miss the point of using cPanel at all, so I would suggest that they probably do not. Your cPanel access information and your FTP information have little to do with MySQL--cPanel uses a MySQL root-authorized user to add databases and users, and unless cPanel exposes an API to do it (I don't think it does, and I don't think anyone sane would enable it on their shared hosting if they did).
Comment: It's all about automation. If you're wanting to make a product that connects to someone's cpanel (with their permission and login info, mind you) and to automate some tasks for them. This is why it is used.


Finite dimensional C*-algebras

Question: Let $A$ be a finite dimensional C*-algebra. Is $A$ unital?
I think since $A$ is finite dimensional and on finite dimensional spaces all topologies are equivalent, then $A$ is a von Neumann algebra and therefore it is unital.
Am I right? If it's not, please give me an example of a non-unital finite dimensional C*-algebra.
Answer: I think Your argument is correct - any finite dimensional $\mathrm{C}^*$-algebra is equal to it's double dual (as a Banach space), hence it has a predual - it follows that it is a von Neumann algebra. Since von Neumann algebras are unital it proves the claim. In fact more can be shown - every finite dimensional $\mathrm{C}^*$-algebra $\mathfrak{A}$ is isometrically $\ast$-isomorphism to a direct sum $\oplus_{i=1}^{n} M_{k_i}$ for some positive integers $k_{1},\dots,k_{n}$.
Answer: Your argument works. But you don't even need to involve topologies. Because $A$ is finite-dimensional, the spectrum of all elements consists only of eigenvalues. Then one can use functional calculus to show that all elements of $A$ are linear combinations of projections. Thinking about projections, because of finite-dimensionality every projection is a sum of minimal projections. And then, thinking first of minimal central projections and then about minimal projections in each "block", one shows that $A$ is a direct sum of full matrix blocks. In particular, it is unital.
Answer: I belive an alternative argument could be:
Finite-dimensional C$^*$-algebras are fully understood: If $A$ is a C$^\ast$-algebra of finite dimension, then
$$
A\cong M_{k_1}(\mathbb{C}) \oplus M_{k_2}(\mathbb{C}) \oplus \ldots \oplus M_{k_r}(\mathbb{C})
$$
For some integer $r\geq 0$. So yes they are unital, as the right-hand side is.

Finite dimensional C*-algebras


"toString()" retornando Null quando não deveria

Question: Tenho a classe Aluno.
public class Aluno {

    private String nome;

    @Override
    public  String toString() {
        return this.nome;
    }
    //metodos getters e setters

}

Classe Vetor
public class Vetor {

    private Aluno[] alunos = new Aluno[5];

    public void Adiciona(Aluno aluno) {
        for(int i = 0; i < alunos.length; i++) {
            if(alunos[i] == null) { //encontrou uma posicao vazia
               alunos[i] = aluno;
               break;
            }
        }

    public int tamanho() {

        return this.alunos.length;
    }

    @Override
    public String toString() {

        if(this.alunos.length == 0) {
            return "[]";
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[");

        for(int i = 0; i < this.alunos.length - 1; i++) {
            builder.append(this.alunos[i]);
            builder.append(", ");
        }

        builder.append(this.alunos[this.alunos.length - 1]);
        builder.append("]");

        return builder.toString();

        }
    }

Quando mando imprimir aqui, retorna todos os elementos dos vetores:
public class Teste {

    public static void main(String[] args) {

        Aluno a1 = new Aluno();
        Aluno a2 = new Aluno();

        a1.setNome("Joao");
        a2.setNome("Maria");

        Vetor lista = new Vetor();
        lista.Adiciona(a1);
        lista.Adiciona(a2);

        System.out.println(lista);
    }
}

O resultado que retorna é esse:

[Joao, Maria, null, null, null, null]
Comment: Não está errado. Você iniciou um vetor com 5 "espaços" e só preencheu dois, logo, o retorno dos outros espaços será null.
Comment: Como faço pra não imprimir? tentei != null, mas nao da certo
Comment: Se tentou, poderia ter colocado na pergunta pra dizermos o que está errado.
Answer: O toString() não deveria ser usado para isso. Se a apostila incentiva esse uso, sinto muito. Mas vamos lá.
Precisa ter uma instrução que mande parar de listar o resto do array quando acha um nulo ou pelo menos filtrar ele:
builder.append("[");
if (this.alunos[0] != null) builder.append(this.alunos[0]);
for (int i = 1; i < this.alunos.length; i++) {
    if (this.alunos[i] != null) {
        builder.append(", ");
        builder.append(this.alunos[i]);
    }
}
builder.append("]");
return builder.toString();

Se quando achar um nulo, é garantindo que todos os seguintes também serão nulos, pode melhorar:
builder.append("[");
if (this.alunos[0] != null) {
    builder.append(this.alunos[0]);
    return "[]";
}
for (int i = 1; i < this.alunos.length; i++) {
    if (this.alunos[i] == null) break;
    builder.append(", ");
    builder.append(this.alunos[i]);
}
builder.append("]");
return builder.toString();

Coloquei no GitHub para referência futura.
Também imprimia um item a mais, consertei isto.
Então eu verifico se o existe pelo menos um item e mando imprimi-lo (tem que por um if ali também).
Depois eu tento ver o resto (no laço) se não form nulos.
Como eu já imprimi o primeiro item (o 0 no array), não preciso imprimir novamente, então começo no 1.
Essa separação do primeiro item é necessária por causa da vírgula. Claro que poderia ter começado do 0 e ir até o length - 1 para não imprimir o último (o último é sempre o length - 1, já que começa do zero, muita gente confunde isso, o último só seria exatamente o length se o array começasse do 1.
Isso nem é computação, é matemática básica, mas como o operador de comparação usado é o "menor que", ele já tira este último) e aí teria que imprimir o último separado (com o if para evitar o nulo).
Dá na mesma fazer antes ou depois, eu prefiro antes, até porque se o primeiro for nulo já posso matar o resto, se for garantido que depois de achar um nulo, todos serão. Em códigos reais, poderia fazer uma função para cuidar disso.
Se tivesse um controle da quantidade de itens existentes no array, poderia matar a execução dentro do próprio for e nem precisaria do if.
Eu tiraria esses this que são completamente desnecessários.
Há outros problemas menores no código.


Finding the PDF of $Y = X^2$ given the pdf and cdf of $X$, where $X$ is uniformly distributed

Question: Example picture
In the above picture (taken from here), they use an alternative way to find the pdf using a change of variables rather than the fundamental theorem of calculus. Specifically, my question involves this part:
$$y = x ^2 \rightarrow dy = 2xdx \rightarrow dx = \frac{dy}{2 \sqrt{y}}$$
$$f_X(x) dx = \frac{dx}{2} = \frac{dy}{4 \sqrt{y}} = f_Y(y) dy$$
How do they equate $\frac{dy}{4 \sqrt{y}}$ to $f_Y(y) dy$ ? I can't figure out how they got this equality
Comment: PS: that is **Uniformly** distributed.
Answer: $F_Y(y) = F_X(x)$ so $$\dfrac{\mathrm d F_Y(y)}{\mathrm d y}=\dfrac{\mathrm d F_X(x)}{\mathrm d y}$$
Apply the Chain Rule to obtain:
$$f_Y(y) = f_X(x)\dfrac{\mathrm d x}{\mathrm d y}$$
Now substitute $x:= +\surd y$ and $\mathrm dx := (\mathrm d y)/2\surd y$  (or rather $\tfrac{\mathrm d x}{\mathrm dy}=\tfrac{\mathrm d \surd y}{\mathrm d y}=\tfrac 1{2\surd y}$ )
$$f_Y(y) = f_X(\surd y)\dfrac {1}{2\surd y}$$

The rest is that $f_X(x) = 1/2$ under $x\in(0..2)$  because this example is uniformly distributed over that support.
$$f_Y(y) = \dfrac {1}{4\surd y}\quad\big[ ~y\in(0..4)~\big]$$
Comment: Why is $F_Y(y)=F_X(x)$?
Comment: $\begin{align}F_Y(y) &= \mathsf P(Y\leqslant y) \\& = \mathsf P(X^2\leqslant y)&\quad&Y:=X^2\\& = \mathsf P(-\surd y\leqslant X\leqslant \surd y) \\& = \mathsf P(X\leqslant \surd y) &&X\in(0..2)\\& =\mathsf P(X\leqslant x)&& x=\surd y\\ & = F_X(x)\end{align}$
Comment: Of course, if $X$ could be negative (say it was distributed over $(-2..2)$), then we would have $F_Y(y) = F_X(\surd y)-F_X(-\surd y)$ and therefore $f_Y(y)= (2\surd y)^{-1}\, (f_X(\surd y)+f_X(-\surd y))$
Comment: Ah, I see why $F_Y(y) = F_X(x)$ now, thank you for the explanation!
Comment: Sorry, I had a quick follow-up question. It seems that this change-of-variable methodology can be applied to a lot of problems of this type (ex: in my question, finding $f_Y(y)$ for arbitrary $y$ by using a change of variable for $y = x^2$). Is there a theorem or something that generalizes this idea?
Comment: Yes, indeed @AdityaMehrotra , the theorem dealing with change of variables in an integral is the [Change of Variables Theorem](https://mathworld.wolfram.com/ChangeofVariablesTheorem.html)
Answer:
I can't figure out how they got this equality

In your example $X\sim U(0;2)$ thus $f_X(x)=\frac{1}{2}$
You arrive at
$$dx=\frac{dy}{2\sqrt{y}}$$
thus this is the same as
$$f_X(x)dx=\frac{1}{2}dx=\frac{1}{2}\cdot\frac{dy}{2\sqrt{y}}=f_Y(y)dy$$

but your main question is how to apply this procedure when $X$ is gaussian. Before doing the calculation, it is important to know if your gaussian is centered (gaussian with mean 0) or it is not...
Comment: Also, because a Gaussian random variable may be either positive of negative: $$f_{X^2}(y)=(2\surd y)^{-1} f_X(+\surd y)+(2\surd y)^{-1} f_X(-\surd y)$$
Comment: I'm so sorry, I accidentally wrote normally distributed in my question title, but I should've written uniform, as that was part of the question I was trying to ask
Comment: @AdityaMehrotra : sometimes a typo can be an opportunity: Try to to the same exercise with $X\sim N(0;1)$. The result is a known distribution


Evaluating a regression model's performance using training and test sets?

Question: I often hear about evaluating a classification model's performance by holding out the test set and training a model on the training set.  Then creating 2 vectors, one for the predicted values and one for the true values.  Obviously doing a comparison allows one to judge the performance of the model by its predictive power using things like F-Score, Kappa Statistic, Precision & Recall, ROC curves etc.
How does this compare to evaluating numeric prediction like regression?  I would assume that you could train the regression model on the training set, use it to predict values, then compare these predicted values to the true values sitting in the test set.  Obviously the measures of performance would have to be different since this isn't a classification task.
The usual residuals and $R^2$ statistics are obvious measures but are there more/better ways to evaluate the performance for regression models?  It seems like classification has so many options but regression is left to $R^2$ and residuals.
Comment: I am not sure exactly what question you are asking but an obvious error metric for a regression model with a continuous output is mean square error (MSE) between the model output and the outcome variable.
Comment: So just an error measure between the actual and predicted.
Comment: Yes, optimized on the training set and validated using the test set.
Answer: As said, typically, the Mean Squared Error is used. You calculate your regression model based on your training set, and evaluate its performance using a separate test set (a set on inputs x and known predicted outputs y) by calculating the MSE between the outputs of the test set (y) and the outputs given by the model (f(x)) for the same given inputs (x).
Alternatively you can use following metrics: Root Mean Squared Error, Relative Squared Error, Mean Absolute Error, Relative Absolute Error... (ask google for definitions)
Comment: Good answer.  These are all associated with the second moment of the distribution.  You can also look at the sum of differences if you are trying to eliminate bias, or use any combination you want.  For example, $err = A\sum (x - x_i) + B\sum (x - x_i)^2$ where A and B are chosen weights for each scoring method.  Really it will depend on what factors are important to your specific problem.


How do you add text wrapping to a cell using OpenXml when creating excel files?

Question: How do you set the format of a text cell to wrap when generating .xlsx files with OpenXml? Here is the code I have currently:
public void Excel()
    {
        var viewModel = new RequirementIndexData();
        viewModel.Requirements = db.Requirement;

        MemoryStream ms = new MemoryStream();

        SpreadsheetDocument dc = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);

        WorkbookPart mdp = dc.AddWorkbookPart();
        WorksheetPart wsp = mdp.AddNewPart<WorksheetPart>();
        Workbook wb = new Workbook();
        FileVersion fv = new FileVersion();
        fv.ApplicationName = "Microsoft Office Excel";
        Worksheet ws = new Worksheet();

        SheetData sd = new SheetData();

        Columns columns = new Columns();
        columns.Append(CreateColumnData(1, 1, 95));
        ws.Append(columns);

        Row r1 = new Row() { RowIndex = (UInt32Value)1u };

        Cell c1 = new Cell();
        c1.DataType = CellValues.SharedString;
        c1.CellValue = new CellValue(OpenSoft.AgileAnalytics.EF.App_LocalResources.GlobalRes.VersionNumber + " " + viewModel.Requirements.OrderBy(r => r.CreatedOn).Select(r => r.CurentVersion).First().ToString());

        r1.Append(c1);
        sd.Append(r1);

        for (int i = 2; i < viewModel.Requirements.Count() + 2; i++)
        {
            Row row2;
            row2 = new Row()
            {
                RowIndex = (UInt32)i,

                Height = 25,
                DyDescent = 1.50D,
                Hidden = false,
                Collapsed = false
            };
            Cell cell2 = new Cell() { StyleIndex = Convert.ToUInt32(1) };
            cell2.DataType = CellValues.SharedString;
            cell2.CellValue = new CellValue((i - 1).ToString() + ". " + viewModel.Requirements.OrderBy(r => r.CreatedOn).Select(r => r.Definition).ElementAt(i - 2).ToString());

            row2.Append(cell2);
            sd.Append(row2);
        }

        ws.Append(sd);
        wsp.Worksheet = ws;
        wsp.Worksheet.Save();
        Sheets sheets = new Sheets();
        Sheet sheet = new Sheet();
        sheet.Name = "specification1";
        sheet.SheetId = 1;
        sheet.Id = mdp.GetIdOfPart(wsp);
        sheets.Append(sheet);
        wb.Append(fv);
        wb.Append(sheets);

        dc.WorkbookPart.Workbook = wb;
        dc.WorkbookPart.Workbook.Save();
        dc.Close();
        string filename = "specification1.xlsx";
        Response.Clear();
        byte[] dt = ms.ToArray();

        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
        Response.BinaryWrite(dt);
        Response.End();
    }

    private WorkbookStylesPart AddStyleSheet(SpreadsheetDocument spreadsheet)
    {
        WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();

        Stylesheet workbookstylesheet = new Stylesheet();

        // <Fonts>
        Font font0 = new Font();         // Default font

        Fonts fonts = new Fonts();      // <APENDING Fonts>
        fonts.Append(font0);

        // <Fills>
        Fill fill0 = new Fill();        // Default fill

        Fills fills = new Fills();      // <APENDING Fills>
        fills.Append(fill0);

        // <Borders>
        Border border0 = new Border();     // Defualt border

        Borders borders = new Borders();    // <APENDING Borders>
        borders.Append(border0);

        // <CellFormats>
        CellFormat cellformat0 = new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }; // Default style : Mandatory

        CellFormat cellformat1 = new CellFormat(new Alignment() { WrapText = true }); // Style with textwrap set

        // <APENDING CellFormats>
        CellFormats cellformats = new CellFormats();
        cellformats.Append(cellformat0);
        cellformats.Append(cellformat1);

        // Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
        workbookstylesheet.Append(fonts);
        workbookstylesheet.Append(fills);
        workbookstylesheet.Append(borders);
        workbookstylesheet.Append(cellformats);

        // Finalize
        stylesheet.Stylesheet = workbookstylesheet;
        stylesheet.Stylesheet.Save();

        return stylesheet;
    }

Answer: You need to define styles for this. Styles are defined inside a stylesheet. Each style has an ID and when you create Cells you can refer defined style ID.
Defining stylesheet for the spreadsheet:
private WorkbookStylesPart AddStyleSheet(SpreadsheetDocument spreadsheet)
{
    WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
    Stylesheet workbookstylesheet = new Stylesheet();

    // <Fonts>
    Font font0 = new Font();            // Default font
    Fonts fonts = new Fonts();          // <APPENDING Fonts>
    fonts.Append(font0);

    // <Fills>
    Fill fill0 = new Fill();            // Default fill
    Fills fills = new Fills();          // <APPENDING Fills>
    fills.Append(fill0);

    // <Borders>
    Border border0 = new Border();      // Defualt border
    Borders borders = new Borders();    // <APPENDING Borders>
    borders.Append(border0);

    // <CellFormats>
    CellFormat cellformat0 = new CellFormat()   // Default style : Mandatory
    {
        FontId = 0,
        FillId = 0,
        BorderId = 0
    };
    CellFormat cellformat1 = new CellFormat(new Alignment() { WrapText = true });          // Style with textwrap set

    // <APPENDING CellFormats>
    CellFormats cellformats = new CellFormats();
    cellformats.Append(cellformat0);
    cellformats.Append(cellformat1);

    // Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
    workbookstylesheet.Append(fonts);
    workbookstylesheet.Append(fills);
    workbookstylesheet.Append(borders);
    workbookstylesheet.Append(cellformats);

    // Finalize
    stylesheet.Stylesheet = workbookstylesheet;
    stylesheet.Stylesheet.Save();

    return stylesheet;
}

Now when you add cells, use the defined style ID as follows:
// Assign our defined style with text wrap.
Cell c1 = new Cell(){ StyleIndex = Convert.ToUInt32(1) };

EDIT: You need to add stylesheet after adding workbookpart.
Comment: Thanks for your help.
Unfortunately when you open a document Excel window appears with the message:
`"In the book "specitication.xlsx" found content that could not be read. Try to restore the contents of the book? If you trust the source of this workbook, click "Yes"."`
If you select "No", the document does not open.
If you choose "Yes", then opens the document without style.
Comment: Couldn't get this to work, either I am adding in the stylesheet at the wrong time, or the ID is wrong (where do you define this?). Would be nice to have a full example as the code you details is never called in the problem statement
Comment: Did you had this problem previously ? Or did it occur after adding styles
Comment: This message appears after adding changes. I add stylesheet after adding workbookpart. I can insert code changes, but I think it's too much
Comment: This is the only way :) Actually if you need add styles you need to define all of these code .. And you define it only one time so nothing to worry [the correct way] .. btw code works fine.. Did you use correct Stylde ID index ?? Check it please
Comment: At the announcement of the cell, I wrote what you wrote           `Cell cell2 = new Cell() { StyleIndex = Convert.ToUInt32(1) };`
Comment: I changed the code in question, look, please. I've done everything you've written
Comment: Can you check it now, I updated your code on OP.. :) Run It and Check
Comment: Thank you so much! :) You helped me a lot, now I understood what each section of code
Answer: using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

// pathToExcel is filename of the existing file
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(pathToExcel, true))
{
    // Get workbookpart
    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
    WorkbookStylesPart wbsp = CreateStylesheet(workbookPart.WorkbookStylesPart);

    // then access to the worksheet part
    List<WorksheetPart> worksheetPart = workbookPart.WorksheetParts.ToList();
    foreach (WorksheetPart WSP in worksheetPart)
    {
        // find sheet data
        IEnumerable<SheetData> sheetData = WSP.Worksheet.Elements<SheetData>();

        // Iterate through every sheet inside Excel sheet
        foreach (SheetData SD in sheetData)
        {
            IEnumerable<Row> row = SD.Elements<Row>(); //  Get the row
            int rowindex = 1;
            foreach (Row currentrow in row)
            {
                foreach (Cell cell in currentrow.Descendants<Cell>())
                {
                    // Doing Wordwrap in the cell using openxml - in open xml we need to do cell level word wrap
                    cell.StyleIndex = Convert.ToUInt32(1);
                }
                // Here Row AutoFit property is not available, setting the row height manually and skipping 1st two rows
                if (rowindex > 2)
                {
                    currentrow.Height = currentrow.Height + 5;
                    currentrow.CustomHeight = true;
                }
                rowindex++;
            }
        }
        WSP.Worksheet.Save();
    }

    // workbookPart.Workbook.Save();
    spreadsheetDocument.Close();
}

private static WorkbookStylesPart CreateStylesheet(WorkbookStylesPart spreadsheet)
{
    WorkbookStylesPart stylesheet = spreadsheet;
    Stylesheet workbookstylesheet = new Stylesheet();

    // <CellFormats>
    CellFormat cellformat0 = new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }; //  Default style : Mandatory
    CellFormat cellformat1 = new CellFormat(new Alignment() { WrapText = true });

    // Style with textwrap set
    Fills fills = new Fills();
    Fill fill = new Fill();
    PatternFill patternFill = new PatternFill();
    patternFill.PatternType = PatternValues.None;
    fill.PatternFill = patternFill;
    fills.Append(fill);

    // <APPENDING CellFormats>
    CellFormats cellformats = new CellFormats();
    cellformats.Append(cellformat0);
    cellformats.Append(cellformat1);

    //  Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
    workbookstylesheet.Append(fills);
    workbookstylesheet.Append(cellformats);

    //  Finalize
    stylesheet.Stylesheet = workbookstylesheet;
    stylesheet.Stylesheet.Save();

    return stylesheet;
}

Comment: Please consider adding an explanation in plain English for your answer to improve its quality and describe how your code solves the OP's problem.


Force browser to empty DNS cache

Question: So I migrated a mediawiki site to a new Server. The old one is still up but the database is locked and I merge the new Content with rsync and mysqldump every 15 min. So we can read the content from the old IP.
Now I changed the A record of the domain to point to the new server. After 3 hours and when I am using a cache cleared browser, I am at the new server.
However, when I am using an not cache cleared browser, I am landing at the old server.
How to tell the browser, that it should clear its dns cache, or that there is an IP change?
Comment: There's no reliable way, since upstream servers may also hold the cache. You could try another name server, or running your own (which you can clear whenever)
Answer: You can't tell the browsers of random people on the Internet to flush their caches; it's not how things are done.  For next time, remember to reduce the TTL on your A records to some suitably small value (like, say, "five minutes") some time before the change over will happen; at least as long as the previous TTL was set to.  That will limit the time that well-behaved Internet citizens will cache, and the transition will complete nice and quickly. Once the change occurs and sufficient time has passed, the TTL can be switched back to something longer.
Answer:
For next time, remember to reduce the TTL on your A records to some suitably small value (like, say, "five minutes") some time before the change over will happen; at least as long as the previous TTL was set to. That will limit the time that well-behaved Internet citizens will cache, and the transition will complete nice and quickly.

Even doing this WELL ahead of time (with NetSol), we are hearing user reports that they are still landing on the old "site" which is now just a custom error page.  Stubborn browsers!
But asking visitors to try a different browser seems to be the easiest solution for even the most novice users.

Force browser to empty DNS cache


Find an operation so that it makes $D^{2}=\{z\in \mathbb{C}\mid |z|<1\}$ a group.

Question: Let $D^{2}=\{z\in \mathbb{C}\mid |z|<1\}$. Find operation $\oplus: D^{2}\times D^{2}: \rightarrow D^{2}$ so that it makes $D^{2}$ a group.
I have already defined some operations but these don't verify associative property. For example, I defined $f(z)=\frac{z}{1+|z|}$ and I defined $z\oplus w:=f(f(z)+f(w))$, but they don't verify associative property.
Thanks, any help is appreciated.
Comment: Any element in $D^2$ can be written as $e^{ix}$. Define $f(x,y)=e^{i(x+y)}$. Maybe this would work. I didn't check the conditions.
Comment: Does this answer your question? [A unique operation on a set that makes it a group](https://math.stackexchange.com/questions/995580/a-unique-operation-on-a-set-that-makes-it-a-group)
Answer: Choose any bijection $f:D^2\to\mathbb R^2$ (it may even be a diffeomorphism) and let
$$z\oplus w:=f^{-1}(f(z)+f(w)).$$


Guitar fingering question

Question: When I play G#/Ab on the high E string on the guitar, I use my pinky for the fourth fret, but what about all the fingers before the pinky? Can they be packed closely to my pinky? Or do all fingers have to be at their own frets like stretched? Like in a scale exercise or something?
Comment: That note is rarely played in isolation! Usually there are notes before and after it, which will be the deciders as to which finger is used for top string 4th fret. If I play around the 5th fret in A, I'm far more likely to play that G# with index! Not enough information for a helpful answer yet. If that's the highest note played, then it really doesn't matter what happens to the other fingers behind - on or off the fingerboard
Answer: If you're playing just this single G# it even doesn't matter which finger you use and where the other fingers are. But as Tim says there are certainly other notes (chord or melody ...) that will be added.
So you have to keep in mind what you will play as next and bring your other fingers in "pool-position" that they are ready for what they will have to play as next.

Guitar fingering question


Prove that no disconnected region exists

Question:
Ten points in space, no three of which are collinear, are connected, each oneto all the others, by a total of $45$ line segments. The resulting framework $F$ will be "disconnected" into two disjoint nonempty parts by the removal of one point from the interior of each of the 9 segments emanating from any one vertex off. Prove that $F$ cannot be similarly disconnected by the removal of only $8$ points from the interiors of the 45 segments.

I thought it was simple to prove this since you must disconnect at least $9$ segments in order to disconnect a vertex.
Comment: But disconnecting one vertex is not as general as disconnecting into two disjoint parts (which could be of any sizes, say 2 and 8...or 3 and 7). You are assuming that the split has to be into ones of size 1 and 9 (it does, but you should show why I think).
Comment: In order to disconnect into disjoint parts we must disconnect a vertex, correct?
Comment: Not necessarily...look at the graphs [here](http://mathworld.wolfram.com/images/eps-gif/BarbellGraph_875.gif).  The center edge can be deleted and disconnect the graph.
Comment: So that is the only exception then. I must show it doesn't have a center vertex?
Comment: I am confused can anyone help?
Answer: Let there be $n$ points, to generalize on the $n=10$ case of the post. Suppose we remove a number of edges, so as to create a result having $k>1$ connected components remaining. If the sizes of the components are $a_1,a_2,\cdots a_k$ then how many edges do we need to remove to do this? For each ordered pair $(s,t)$ with $1 \le s<t\le k,$ we must remove each of the $a_sa_t$ edges which connect a vertex in the component going with size $a_s$ to another vertex in the component going with size $a_t.$ So in all we must remove at least
$$\sum_{s<t} a_sa_t$$
edges. We can get a lower bound for this by only using the pairs which have $a_1$ in them, that is, the above sum is at least
$$a_1a_2+a_1a_3+\cdots +a_1a_k=a_1(n-a_1),$$
the last because $a_1+a_2+ \cdots +a_k=n.$
Now we need to note that the minimal value of $a_1(n-a_1)$ occurs when $a_1=1$ or $a_1=n-1$ and is $n-1.$ The upshot is that, no matter how we delete edges so as to create a result having more than one connected component, we must in all cases remove at least $n-1$ edges to do it. Applied to $n=10$ case it shows we need to delete at least nine edges.
Answer: Ok, so we want to show that to cut a complete Graph on n (here 10) vertices into disjoint pieces we need to remove at least n-1 edges.

Say we have removed m edges and cut the graph into disjoint pieces. Then there are 2 vertices $a_1, a_n$ so that the graph without those edges (let's call it G) doesn't contain a path between the two.
Now we look at the n-1 paths of the form
$a_1 a_n, a_1 a_2 a_n, a_1 a_3 a_n, ... , a_1 a_{n-1} a_n$
These paths are all contained in our original graph (it was complete) and no two of them share any edges. for $a_1$ and $a_n$ to be disconnected in G we must have removed at least one edge in each of the paths, so m >= n-1
Comment: Paths $a_1a_2a_n$ and $a_1a_2a_3a_n$ share edge $a_1a_2$.
Comment: whoops sorry, fixed it, meant to be $a_1 a_2 a_n, a_1 a_3 a_n ...$


How to query the date format YYYY-MM-dd HH-MM-ss?

Question: How to query the date with the format :
02/13/2013  12:05:48
select *
from TOTAL_SUBS
where TIME BETWEEN TO_DATE('2013-13-02 00:00:00', 'SYYYY-MM-DD HH24:MI:SS')
AND TO_DATE('2013-12-14 00:00:00', 'SYYYY-MM-DD HH24:MI:SS');

I have try with that code but what i expected from the date only came out the 02/13/2013, There is no Time "12:05:48" came out in the result.
Comment: AFAIK, there is no a month with the number of 13
Comment: If you are able to filter out this date using this select statement then definitely timestamp is there. You can check that by selecting `to_char(time, 'RRRR-MM-DD HH24:MI:SS)` from the table. If NLS date format is set to a format in which timestamp is not specified, it won't show up in the tool where you are querying it. Moreover '2013-13-02 00:00:00' is not a valid month.
Comment: 12:05 , youexpect from which day 14th?
Comment: What application do you use ? if Oracle SQL Developer, you just need to go to Tools menu -> Database -> NLS. Add the date format as you wish. Without this, no matter how the query structure is, it will never show the time
Comment: First off, don't use `BETWEEN` [with timestamps](https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common), or any other variable-precision type either (essentially, anything but an integer count, and I'd avoid it there too for consistency reasons).  Date/time types don't really have formats - what's the actual type of `TIME`?
Answer: EDIT: It advisable to do to_char() to requirement format, as the NLS_DATE_FORMAT may not be same everywhere you run your Query!
If, at all you want to change NLS, please do this.
alter session set nls_date_format='MM/DD/YYYY HH24:MI:SS';

Finally, a TO_CHAR() conversion in the select. Actually, when you want print(see) a DATE datatype in the format you expect, use this.
select * , TO_CHAR(TIME,'MM/DD/YYYY HH24:MI:SS') my_datetime
from TOTAL_SUBS
where TIME BETWEEN TO_DATE('2013-02-13 00:00:00', 'SYYYY-MM-DD HH24:MI:SS')
AND TO_DATE('2013-12-14 23:59:59', 'SYYYY-MM-DD HH24:MI:SS');

Edited the month and the timestamp to include till mdnight. Hope this helps!
Answer: What application do you use ?
if Oracle SQL Developer, you just need to go to Tools menu -> Database -> NLS.
Add the date format as you wish.
SELECT *
FROM   total_subs
WHERE  time BETWEEN To_date('2013-02-13 00:00:00', 'YYYY-MM-DD HH24:MI:SS') AND
                    To_date('2013-12-14 00:00:00', 'YYYY-MM-DD HH24:MI:SS');

Try your query again.
Without this, no matter how the query structure is, it will never show the time


Order query result based off of information in another table

Question: I have a table called workouts and another table called likedWorkouts. If the user likes or dislikes a workout then I insert the Users ID, the workoutID of the liked workout and true or false into the table called likedWorkouts. The database structure is the same as the accepted answer in this question SQL database structure for Like and DisLike
I am trying to retrieve the workouts from the workouts table ordered by the number of likes each one has but since there is no Likes column and the only way I can get the number of likes a workout has is by doing a COUNT(*) query in the likedworkouts table how am I supposed to order the workouts table by the number of likes they have?
EDIT
So I got it working the only problem is I have another table called Downloads with two columns userID and WorkoutID I need to get the amount of downloads a workout has so I added LEFT JOIN DownloadedWorkouts AS d ON w.ID = d.WorkoutID to your alternative rating system query but it causes the likes and dislikes value to be wrong. Have any idea why?
EDIT2:
So i can get the downloads with this query
SELECT *
FROM (SELECT w.ID,
IFNULL(SUM(CASE WHEN d.WorkoutID THEN 1 ELSE 0 END), 0) AS downloads
      FROM UserWorkouts AS w
      LEFT JOIN Profiles ON w.CreatorID = Profiles.UserID LEFT JOIN DownloadedWorkouts AS d ON w.ID =      d.WorkoutID
     GROUP BY w.ID
   ) AS r;

How can I add this to your alternative query?
Answer: SELECT w.WorkoutID, COUNT(*) AS likeCount
  FROM Workouts AS w
  JOIN LikedWorkouts AS l
    ON w.WorkoutID = l.WorkoutID
 WHERE l.liked = TRUE  -- You might need an alternative spelling of TRUE
 GROUP BY w.WorkoutID
 ORDER BY likeCount DESC;  -- You might need ORDER BY COUNT(*) DESC

This doesn't account for the dislikes at all; the highest ranking result could be one with 1000 likes and 5000 dislikes (which would be rated ahead of one with 300 likes and 0 dislikes).  If you want to report on likes and dislikes separately, or the net sum of likes minus dislikes, or percentage of likes vs dislikes, then you have to modify the query, sometimes modestly radically.
This also doesn't show any workouts which are not liked at all (either because all the values in LikedWorkouts are FALSE or because no-one has registered an opinion on the workout).  There are ways to deal with that, too, but the specification needs to be made clearer if that's what is required.

The more complete specification of the ranking function seems to be 'count of likes' divided by 'count of likes plus count of dislikes' where a workout with no likes or dislikes has a 0 likes and 0 dislikes (and a workout with no likes or dislikes will be treated the same as a workout which has 1000 dislikes and no likes).
For this, I tend to use TDQD — test-driven query design.
Calculate number of likes and dislikes for each workout that is liked or disliked
SELECT WorkoutID,
       SUM(CASE WHEN liked THEN 1 ELSE 0 END) AS likes,
       SUM(CASE WHEN liked THEN 0 ELSE 1 END) AS dislikes
  FROM LikedWorkouts
 GROUP BY WorkoutID

Generate 0 likes and dislikes for a workout with no entries in LikedWorkouts
This tends to be DBMS-specific, and SQL Server isn't my primary platform.  It is probably easiest to use a function such as NVL or IFNULL (along with a LEFT JOIN).  SQL Server seems to use IFNULL.
SELECT w.WorkoutID,
       IFNULL(SUM(CASE WHEN l.liked THEN 1 ELSE 0 END), 0) AS likes,
       IFNULL(SUM(CASE WHEN l.liked THEN 0 ELSE 1 END), 0) AS dislikes
  FROM Workouts AS w
  LEFT JOIN LikedWorkouts AS l ON w.WorkoutID = l.WorkoutID
 GROUP BY WorkoutID

Calculate fraction of likes
SELECT WorkoutID, likes / (likes + dislikes) AS rating
  FROM (SELECT w.WorkoutID,
               IFNULL(SUM(CASE WHEN l.liked THEN 1 ELSE 0 END), 0) AS likes,
               IFNULL(SUM(CASE WHEN l.liked THEN 0 ELSE 1 END), 0) AS dislikes
          FROM Workouts AS w
          LEFT JOIN LikedWorkouts AS l ON w.WorkoutID = l.WorkoutID
         GROUP BY WorkoutID
       ) AS r
 ORDER BY 2;  -- Or rating, or likes / (likes + dislikes)

There's a residual problem to be resolved — divide by zero when there are no ratings for a given workout.
Alternative ranking
In some respects, a better ranking function would subtract the count of dislikes from the count of likes and divide by the sum of the counts of the likes and dislikes.  Then the unranked workout would be in the middle, ranked as 0%; the workout with only dislike votes would be -100%; and the workout with only like votes would be +100%.  Only the last query needs changing, and the rating it generates is not a percentage but just a fraction -1.00 .. +1.00.
SELECT WorkoutID, (likes - dislikes) / (likes + dislikes) AS rating
  FROM (SELECT w.WorkoutID,
               IFNULL(SUM(CASE WHEN l.liked THEN 1 ELSE 0 END), 0) AS likes,
               IFNULL(SUM(CASE WHEN l.liked THEN 0 ELSE 1 END), 0) AS dislikes
          FROM Workouts AS w
          LEFT JOIN LikedWorkouts AS l ON w.WorkoutID = l.WorkoutID
         GROUP BY WorkoutID
       ) AS r
 ORDER BY 2;  -- Or rating, or (likes - dislikes) / (likes + dislikes)

This has the same divide by zero issue to be resolved.
Fix the divide by zero
I think (untested) you can fix the divide by zero problem with:
SELECT WorkoutID,
       CASE
       WHEN (likes + dislikes) != 0
       THEN (likes - dislikes) / (likes + dislikes)
       ELSE 0
       END AS rating
  FROM (SELECT w.WorkoutID,
               IFNULL(SUM(CASE WHEN l.liked THEN 1 ELSE 0 END), 0) AS likes,
               IFNULL(SUM(CASE WHEN l.liked THEN 0 ELSE 1 END), 0) AS dislikes
          FROM Workouts AS w
          LEFT JOIN LikedWorkouts AS l ON w.WorkoutID = l.WorkoutID
         GROUP BY WorkoutID
       ) AS r
 ORDER BY 2;  -- Or rating, or (likes - dislikes) / (likes + dislikes)

Warning: all SQL as yet untested on any DBMS, much less SQL Server.
(NB: I generally avoid ORDER BY 2 which was part of the 1986 SQL standard.  Many DBMS allow you to sort by column aliases from the select-list; others may require you to repeat the expression from the select-list in the ORDER BY clause (which is a sad case of violating the DRY (Don't Repeat Yourself) Principle.  Using ORDER BY 2 is likely to work in most DBMS and bypasses the problems — but isn't very desirable.  I don't know SQL Server well enough to know where it falls on the spectrum w.r.t this issue.)

Adding downloads
The question now suggests this as a way of calculating the downloads:
SELECT *
FROM (SELECT w.ID,
             IFNULL(SUM(CASE WHEN d.WorkoutID THEN 1 ELSE 0 END), 0) AS downloads
        FROM UserWorkouts AS w
        LEFT JOIN Profiles ON w.CreatorID = Profiles.UserID
        LEFT JOIN DownloadedWorkouts AS d ON w.ID = d.WorkoutID
       GROUP BY w.ID
   ) AS r;

This wraps a SELECT * FROM (...) AS r around the necessary query — for the downloads, you could simply use:
SELECT w.ID,
       IFNULL(SUM(CASE WHEN d.WorkoutID THEN 1 ELSE 0 END), 0) AS downloads
  FROM UserWorkouts AS w
  LEFT JOIN Profiles ON w.CreatorID = Profiles.UserID
  LEFT JOIN DownloadedWorkouts AS d ON w.ID = d.WorkoutID
 GROUP BY w.ID

However, this query has three new tables; none of the tables clearly corresponds to those in the original question.  Maybe UserWorkouts is what was previously Workouts.  I don't see why Profiles is involved; it looks like you should be just using the list of all workouts and the DownloadedWorkouts tables.  (In future, please give at least skeletal schemas for the tables in the question; it would simplify things for everyone — for you translating answers, and for us giving you answers.)
SELECT w.WorkoutID,
       IFNULL(SUM(CASE WHEN d.WorkoutID THEN 1 ELSE 0 END), 0) AS downloads
  FROM Workouts AS w
  LEFT JOIN DownloadedWorkouts AS d ON w.WorkoutID = d.WorkoutID
 GROUP BY w.ID

Note that I've used the Workouts table and assumed that the primary key column is WorkoutID as before.
Combining that with the main query gives:
SELECT r.WorkoutID, r.Rating, d.Downloads
  FROM (SELECT WorkoutID,
               CASE
               WHEN (likes + dislikes) != 0
               THEN (likes - dislikes) / (likes + dislikes)
               ELSE 0
               END AS rating
          FROM (SELECT w.WorkoutID,
                       IFNULL(SUM(CASE WHEN l.liked THEN 1 ELSE 0 END), 0) AS likes,
                       IFNULL(SUM(CASE WHEN l.liked THEN 0 ELSE 1 END), 0) AS dislikes
                  FROM Workouts AS w
                  LEFT JOIN LikedWorkouts AS l ON w.WorkoutID = l.WorkoutID
                 GROUP BY WorkoutID
               ) AS r1
       ) AS r
  JOIN (SELECT w.ID AS WorkoutID,
               IFNULL(SUM(CASE WHEN d.WorkoutID THEN 1 ELSE 0 END), 0) AS downloads
          FROM Workouts AS w
          LEFT JOIN DownloadedWorkouts AS d ON w.WorkoutID = d.WorkoutID
         GROUP BY w.ID
       ) AS d
    ON r.WorkoutID = d.WorkoutID
 ORDER BY r.rating, d.WorkoutID;

This is a good demonstration of TDQD in action.  You can create and test the various sub-queries as the development proceeds, ending up with a solid answer even when the resulting query is rather complex.  I'd hate to try to write this final query from scratch; indeed, I wouldn't — I'd use TDQD to get the parts right, pretty much as shown.
NB: All SQL still untested by me.
Comment: @Tanner: that is a detail that varies between DBMS; I don't know SQL Server, and it may or may not require that.  I'll add a comment.
Comment: Think you still have to order by count(*) as it won't be able to evaluate likeCount in the order by
Answer: Something like this:
SELECT  w.*
FROM    workouts w
        LEFT OUTER JOIN (
                    SELECT  workoutID,
                            cnt=COUNT(*)
                    FROM    likedWorkouts
                    WHERE   liked = 1
                    GROUP BY workoutID
                    ) wl ON wl.workoutID = w.workoutID
ORDER BY wl.cnt DESC

Comment: The `OUTER` keyword is optional.


Sending Notification To IOS And Android using Google Cloud Messaging in PHP

Question: I am trying to send notifications to both ios and android from my php server. I didn't get any proper documentation for sending notifications to ios via google cloud messaging. Could you please me in integrating this.
Comment: @Johnny Could you please provide me some code or any link.
Comment: have you checked [this document](https://developers.google.com/cloud-messaging/ios/client)
Comment: @RahulTiwari I like to know whether google will take care of the device(whether it is android or ios) or we need to send separate calls for ios and android.
Comment: As per [documentation](https://developers.google.com/cloud-messaging/server) there is no changes in the server.
Comment: @RahulTiwari Could you please help me with some php code to achieve this.
Comment: @arjunarjun, you should post your php code or curl format HTTP request in your question.
Answer: You can check this link for the API it provides (HTTP will fit you the best)
https://firebase.google.com/docs/cloud-messaging/server#implementing-the-http-server-protocol
And check this one for some examples on how to send to different devices, devices groups etc.
https://firebase.google.com/docs/cloud-messaging/send-message
Besides this, you gonna need to set up the the mobile apps in Firebase Console
https://firebase.google.com/support/guides/launch-checklist


How can I configure django-auth-ldap to use more than one LDAP server?

Question: I've been using django-auth-ldap for a while to auth against a single server (AUTH_LDAP_SERVER_URI in settings.py). There have been some changes in my organization recently, and I now need to be able to check against two different LDAP servers (actually: Active Directory, but I don't think that comes into play here). Unfortunately there is not a single location that has all of the user info I need.
Is there any way I can configure django-auth-ldap to check against more than 1 server? The documentation seems to assume a single server/URI. I'd also entertain ideas outside of django-auth-ldap, but I'd really like to stick with it if possible because it keeps things simple.
Comment: Do the servers have to use the same DSN and filter information? Is the second server just for the sake of redundancy? If so, have you considered the use of a single VIP (virtual IP) for the two LDAP servers?
Comment: No, it's different info; not redundant.
Comment: what happens if there is auth information in more than one server? Which server is authoritative?
Comment: @TerryGardner: did you mean what happens if *the same* auth info is on both servers? I'm assured by my IT team that it won't happen (i.e. 'userA' will only exist on 'LDAPserverA'; 'userB' will only exist on 'LDAPserverB'; we will not ever have 'userA' under 'LDAPserverB').
Answer: You would need to extend the custom auth handler to take an iterable for servers to check against and just step through them.
There is nothing stopping you from checking any number of directories for the information you need - there is no limitation in the underlying libraries.
Comment: Hm...OK, I don't know how to do this (yet) but maybe that's another question. Thanks!
Answer: django-auth-ldap 1.1 (just released) allows you to easily define multiple subclasses of the authentication backend that use different collections of settings. See http://packages.python.org/django-auth-ldap/#multiple-ldap-configs.