equals comparison for 2 objects in Java 7

Question: public class ObjectEqualsComparison {
      public static void main(String[] args) {
           Object ob1 = new Object();  // address location 0×1234
           Object ob2 = new Object();  // address location 0×2345

           System.out.println(ob1 == ob2); // prints false correct
           System.out.println(ob1.equals(ob2)); //prints false which is incorrect//it should be true.

           //ob1 == ob2 gives false which is correct since you are comparing address/references .
           //ob1.equals(ob2) is also giving false.can you tell me why since we are comparing contents
        }
}

EDIT::My question is do i need to override equals() method.if so how should the equals() overriden method look like. Please help
Comment: There are hundreds of questions about equals vs. == on Stack Overflow.  Please use the search facility before posting.
Comment: You cannot override `equals()` on the `Object` class.
Comment: i could not find for objects.Sorry
Comment: `prints false which is incorrect` is an incorrect assertion
Answer: The output of System.out.println(ob1.equals(ob2)); is correct because you are comparing instances of type object. If you were comparing instances of a type that overrides equals then that would be a different story!
For example, if you have:
class SomeType{

    private Object comparisonField;

    public SomeType(Object comparisonValue){
        this.comparisonField = comparisonValue;
    }

    @overrides
    public int getHashCode(Object other){
        if(this.comparisonField == null)
            return super.getHashCode();

        return this.comparisonField.getHashCode();
    }

    @overrides
    public boolean equals(Object other){
        if(comparisonField == null || other == null)
           return super.equals(other);

        return comparisonField.equals(((SomeType)other).comparisonField);
    }
}

When comparing:
SomeType inst1 = new SomeType("SAME VALUE");
SomeType inst2 = new SomeType("SAME VALUE");

bool areEqual = inst1.equals(inst2);  // calls the overriden equals method on SomeType
                                      //   which would return TRUE

// but if you use object:

Object obj1 = new Object();
Object obj2 = new Object();

bool areEqual = obj1.equals(obj2);    // will call equals on Object;
                                      //   and always return false;

Comment: If you were comparing instances of a type that overrides equals then that would be a different story!,any example please
Comment: Try it with String. `String` has an overriden `equals` method.
Comment: but im case if i wanted both ob1 and ob2 to be equal.what shoould i do
Comment: if `ob1` and `ob2` are of type `Object` they will only be equal if they are references to the same instance! Otherwise you need to be more specific about which types you are comparing.. Being more specific means casting them to an appropriate type.
Comment: Miky,could you let me the code which i need to insert in              public bool equals(Object other){
        // put logic to compare two instances of SomeType here
    }
Comment: getting an error at  base and @overrides.help providded will be appreciated Miky
Comment: sorry.. C# syntax.. it should have been `super.equals`
Comment: well do i need to also override hashcode method ?how would that look like?,Miky dont say sorry,this amswer is possible because of your extended efforts.Thanks :-))
Comment: @Deepak - please see update. That said, the implementations of `getHashCode()` as well as `equals(...)` I gave are just examples. You will have to determine the logic that is appropriate for your own types. The idea behind implementing `getHashCode` along with `equals` is to ensure that two instances that test equal also return the same hash code.
Comment: @Miky i guess the getHashcode method is incorrect,could you check it once
Comment: public int getHashCode(Object other){
          if(this.comparisonField == null)
               return super.getHashCode();
        return this.comparisonField.getHashCode();
    }
 This method is showing an incorrect signature,say no method like getHashCode and does not accept arguments.
Comment: @Deepak please ask a separate question and provide as many details as possible. This is not how SO works!
Answer: The default implementation of equals() found in Object will return true only if the 2 objects are the same instance, i.e. the same object in memory.  Any time you create 2 separate Object instances as you did, they do not reference the same object in memory which is why it returns false.
As Miky pointed out, you can modify that default behavior to provide custom equivalency semantics by overriding equals() in your class.
However, Miky is incorrect in that casting your class (e.g. your SomeType instance in his example) to Object will change the outcome of equals().
boolean areEqual = obj1.equals(obj2);

will still invoke the overridden equals() method defined by SomeType regardless of the fact that it is being referenced generically as its supertype, Object.  That's the power of polymorphism.
So, to answer your original question, you have to create your own class and the override equals() in that class with an implementation that performs whatever equivalency checks are meaningful for your class.  For example, if you have a Customer class and customers are defined uniquely by their email address, then in Customer.equals(), you'd compare email addresses and return true if they are the same.
Keep in mind that the signature of equals() accepts an Object argument. A properly constructed equals implementation will check if the argument is null and if it's an instance of the same type.  Also be aware that you MUST override hashCode() when you override equals().
There is a ton of information easily found about overriding equals() and hashCode() that I suggest you research more.  A good place to start is always the "Effective Java" book.
Comment: +1 - you were right about the object cast..


Change select option based on  clicked

Question: I've seen it done before, but basically what I'm trying to do is when a user clicks on an option "Missionary Farewell/Homecoming", it redirects them to a contact form with a dropdown menu where "Missionary Farewell/Homecoming" is already selected for them in the contact form, and do that for the various different  tags and different select options.
HTML Form I'm redirecting to
<form class="contactform" method="post" action="php/events.php">
  <input class="leftbox halfbox" name="contactname" placeholder="Contact's Name">
  <input class="rightbox halfbox" name="eventname" placeholder="Event Name">
  <input class="leftbox halfbox" name="contactphone" placeholder="Contact Phone">
  <input class="rightbox halfbox" name="contactemail" placeholder="Contact Email">
  <select class="fullbox stubborn" name="eventtype">
    <option>What type of event is it?</option>
    <option value="missionary">Missionary Farewell/Homecoming</option>
    <option value="highlight">Athletic/Dance Featurette</option>
    <option value="birthday">Birthday</option>
    <option value="funeral">Funeral</option>
    <option value="graduation">Graduation</option>
    <option value="anniversary">Anniversary</option>
    <option value="engagement">Engagement</option>
    <option value="other">Other</option>
  </select>
  <textarea class="fullbox" id="textarea" name="otheroption" placeholder="If other, please specify"></textarea>
  <input class="leftbox halfbox" name="eventloc" placeholder="Event Location">
  <input class="rightbox halfbox" name="eventtime" placeholder="Event Duration">
  <textarea class="fullbox" id="textarea" name="otherquestions" placeholder="Do you have any other questions/specifications?"></textarea>
  <input class="fullbox stubborn" id="submit" name="submit" type="submit" value="Submit">
</form>

Comment: Set the anchor's `href` to be a URL with a query string `?eventtype=missionary`, then test the query string in the new page - I'd probably do that server-side (PHP, in your case). In a general sense any given anchor could then specify as many or few default settings as required.
Comment: nnnnnn, your idea was my original thought. I tried just what you told me but it didn't quite do anything yet. What do you mean by server-side?
Comment: You're using PHP, right? Any PHP code that you write executes on your web server and the result gets sent to the browser. Any JavaScript code that you write executes within the browser.
Comment: So there's more to it than throwing it in the href then....
Answer: Set the anchor's href to be a URL with a query string that carries the event type:
...

On the form page form-page.php a Javascript reads the URL, parses the query string for the eventtype parameter and sets the option menu accordingly.
In order to do that is better to give an id to the event dropdown, let's use eventtype:
<select class="fullbox stubborn" name="eventtype" id="eventtype">

Then at the end of the body before the closing tag  you put something like this:

This approach is pure client-side (pure html) without php or any server side code to manage the page.
(Of course the same goal can be accomplished without Javascript server-side-building the form page with the option pre-selected)
Credits:
The function getParameterByName() comes from: How can I get query string values in JavaScript?
How to change the selected option by value using JavaScript is described here:
HTML SELECT - Change selected option by VALUE using JavaScript

Change select option based on  clicked


"Ping" errors in apache log

Question: I get a message like this in my apache error log every few minutes:
<code>Jun 29 11:13:37 www apache2[22839]: [error] [client 129.130.453.734] ping, referer: https://www.example.org/user/262725/downloadhistory
</code>
The referer is always a PHP (Drupal) URL, but that may only be because the site is almost all Drupal anyway.  I can't find any documentation for "ping" that doesn't refer to a network ping.
Answer: This sounds like it's probably related to the Drupal Ping module.  See here.

"Ping" errors in apache log


ABC notation : how to draw the "piano brace" at the left of the grand staff?

Question: Good morning-
I have scoured the documentation for EasyABC but can't find how to draw the brace at the left of the grand staff, to couple the two piano parts.

Can anyone advise please? (I'm assuming it can do it....)
(I have EasyABC version 188.8.131.52, which is the one currently on Sourceforge, as pointed to from abcnotation.com.)
EDIT: I changed the title from "EasyABC" to "ABC notation", having realised the question wasn't limited to EasyABC
Answer: Here is an excerpt from the relevant passage from the ABC Standard:

11.1 Voice grouping
VOLATILE: This section is under review as part of the general discussion about multiple voices for abc 2.2. See also the section 11 disclaimer.
Basic syntax:
%%score   ...
The score directive specifies which voices should be printed in the score and how they should be grouped on the staves.
...
If voice groups are enclosed by curly braces {}, the corresponding staves will be connected by a big curly brace printed in front of the staves. Together they form a voice block. This format is used especially for typesetting keyboard music.
Example:
%%score Solo  [(S A) (T B)]  {RH | (LH1 LH2)}

The following code gives the pictured result on the EasyABC 1.3.8 (latest Mac version as of this post) and the ABCjs test editor.

X: 1
T: Bracket Test
M: 4/4
L: 1/8
K: Emin
%%score {V1 V2}
[V:V1] A B c |
[V:V2] D E F |
Comment: Since it's piano music, you'll probably want to add a vertical line, i.e. `%%score {V1|V2}`, so that the barlines between the staves connect (only noticeable for examples with more than one measure).


How to detect certain numbers from a dice roller?

Question: I have made a text-based RPG that uses dice rolling for the combat system. If you get a 1, your attack is forfeited. You can keep rolling until you get a one, or type 'attack'. I made a dice roller, and I just want to know, how to make it detect if the roll is 2 through 6. Here is the code:
print ("Type roll to roll the dice")
rollKeeper = ("1")
while rollKeeper == ("1"):
    rollOn = input ( )
    if rollOn == ("roll"):
        import random
        def rollDice():
            damage = random.randint(1,6)
        damage = random.randint (1,6)
        print (damage)

So I want to get it do detect numbers 2 through 6, and that's it. I know about
if damage == ("1"):

but that is already part of my game. I just need to be able to detect if it is any of the others (up to 6).
Comment: @MarcB you mean logical or: `or`, not bitwise or: `||`. Python can also chain those signs: `if 2 <= damage <= 6:`
Comment: uh, `if (damage >=2) || (damage <= 6)`?
Comment: *"detect numbers 2 through 6"* - `if damage in range(2, 7)`?
Answer: Roll it into a function, since it's reusable.
import random

def roll_die():
    return random.randint(1,6)

then just test.
result = roll_die()
if result == 1:
    # forfeit attack however you're doing that
else:  # roll between 2-6
    # do whatever your game logic has you doing.

Answer: Try adding:
if 2 <= damage <= 6:
    #insert code here


Imprimir variável em div com javascript

Question: Ola duvida talvez boba mas n estou conseguindo resolver pessoal, o seguinte tenho um determinado valor javascript (variavel) e preciso quando a pessoa entrar no site imprima essa variavel na DIV? por exemplo "ola mundo!" lembrando que essa variavel depois ira mudar automaticamente então fora de cogitação por fixo o valor .

Imprimir aqui

Answer: Nunca se esqueça de utilizar o window.onload para poder executar seu código JavaScript após os elementos HTML estarem prontos para serem manipulados.
Criei um exemplo para você ver a mudança em tempo real.

window.onload = function() {
  var myvar = "Olá mundo";

  document.getElementById("mydiv").innerHTML = myvar;

  setInterval(function() {
    if (myvar == "Olá mundo") {
      myvar = "Mudando dinamicamente"
    } else {
      myvar = "Olá mundo"
    }

    document.getElementById("mydiv").innerHTML = myvar;
  }, 2000);
}

Espero ter ajudado.
Comment: Muito obrigado @Andrew Ribeiro cara vc me ajudou muto. Desde ja eu agradeço.

Imprimir variável em div com javascript


Particular SOAP webservice request results in ECONNRESET exception using Datanoise SOAP gem for Ruby/Rails

Question: I have a datanoise action-webservice implemented SOAP rails webservice which interacts with another SOAP webservice by posting XML SOAP requests to the third-party URL:
open("http://localhost:8080/generateResponse?xmlRequest="+CGI.escape(soapRQ.result(binding).gsub("\n","")))

Periodically this results in an exception (stacktrace below). I just cant understand what triggers this ECONNRESET:
Errno::ECONNRESET (Connection reset by peer):
  /usr/local/lib/ruby/1.8/net/protocol.rb:135:in `sysread'
  /usr/local/lib/ruby/1.8/net/protocol.rb:135:in `rbuf_fill'
  /usr/local/lib/ruby/1.8/timeout.rb:67:in `timeout'
  /usr/local/lib/ruby/1.8/timeout.rb:101:in `timeout'
  /usr/local/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
  /usr/local/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
  /usr/local/lib/ruby/1.8/net/protocol.rb:126:in `readline'
  /usr/local/lib/ruby/1.8/net/http.rb:2028:in `read_status_line'
  /usr/local/lib/ruby/1.8/net/http.rb:2017:in `read_new'
  /usr/local/lib/ruby/1.8/net/http.rb:1051:in `request'
  /usr/local/lib/ruby/1.8/open-uri.rb:248:in `open_http'
  /usr/local/lib/ruby/1.8/net/http.rb:543:in `start'
  /usr/local/lib/ruby/1.8/open-uri.rb:242:in `open_http'
  /usr/local/lib/ruby/1.8/open-uri.rb:616:in `buffer_open'
  /usr/local/lib/ruby/1.8/open-uri.rb:164:in `open_loop'
  /usr/local/lib/ruby/1.8/open-uri.rb:162:in `catch'
  /usr/local/lib/ruby/1.8/open-uri.rb:162:in `open_loop'
  /usr/local/lib/ruby/1.8/open-uri.rb:132:in `open_uri'
  /usr/local/lib/ruby/1.8/open-uri.rb:518:in `open'
  /usr/local/lib/ruby/1.8/open-uri.rb:30:in `open'
  app/controllers/my_websvc_controller.rb:2354:in `postRequest'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/invocation.rb:141:in `send'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/invocation.rb:141:in `perform_invocation_without_interception'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/invocation.rb:135:in `perform_invocation'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/dispatcher/abstract.rb:46:in `web_service_filtered_invoke'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/dispatcher/abstract.rb:37:in `web_service_direct_invoke_without_controller'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/dispatcher/action_controller_dispatcher.rb:112:in `web_service_direct_invoke'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/dispatcher/abstract.rb:58:in `web_service_invoke'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/dispatcher/abstract.rb:25:in `invoke_web_service_request'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/dispatcher/action_controller_dispatcher.rb:58:in `dispatch_web_service_request'
 /usr/local/lib/ruby/gems/1.8/gems/datanoise-actionwebservice-2.3.2/lib/action_web_service/dispatcher/action_controller_dispatcher.rb:56:in `dispatch_web_service_request'
(eval):1:in `api'

The server side is on RHEL5 host. Rails 2.3.5 and Ruby 1.8.7. Thirdpart post is a simple java war deployed into JBOSS 4.3
Answer: I found the problem was because of the size of the URL being generated from the ERB binding result for the xmlRequest parameter - it was obviously too long for a URL using open. I switched to a POST and it works fine.


Fermat primes expressed in the form : $x^2+2\cdot y^2$

Question: How to prove or disprove following statement :

Conjecture :
Fermat number , $F_n=2^{2^n}+1$ , $(n \geq 2)$ is a prime number iff exists a unique representation of
$F_n$ in the form : $x^2+2\cdot y^2$ , where $\gcd(x,y)=1$ , $x,y \geq 0$ .

Assertion :
For every Fermat number $F_n$ , $(n \geq 2)$ it is true that : $F_n \equiv 1 \pmod 8$ .
Theorem :
Odd prime $p$ is expressible as : $p=x^2+2\cdot y^2$ iff
$p \equiv 1 \pmod 8$ , or $p \equiv 3 \pmod 8$ .

So , it follows that every Fermat prime $F_n$ , $(n \geq 2)$ is expressible as :$F_n=x^2+2\cdot y^2$
Question : How to prove uniqueness of this representation ?
Answer: Based on tests on first $5$ Fermat numbers, I found the following simple identity:
$F_n=2^{2^{n}}+1=(2^{2^{n-1}}-1)^2+ 2 \times (2^{2^{n-2}})^2$.
Thus, take $x=(2^{2^{n-1}}-1)$ and $y=(2^{2^{n-2}})$ and you have $F_n=x^2+2y^2$.
Then I found out this is already known as a recurrence relation satisfied by Fermat numbers.
http://en.wikipedia.org/wiki/Fermat_number
Comment: I do not see that the original question of primeness or otherwise of $F_n$ is made any easier from this viewpoint. I see no obvious way of simplifying whether $F_n$ has another expression of the form $x^2 + 2y^2$ without checking all possiblities for $y$ up to the integer part of $\sqrt{\frac{F_n}{2}},$ except that $y$ must be even.
Comment: So, in fact, the original question is equivalent to asking whether $(2^{2^{n-1}} -1) + 2^{2^{n-2}}\sqrt{-2}$ is a prime in the Euclidean ring $\mathbb{Z}[\sqrt{-2}]$ (see my answer).
Comment: yes, maybe. I say 'maybe' because I don't know abstract algebra.
Comment: @GeoffRobinson I am thinking of a way to prove uniqueness but have failed so far. Can you please think of one that is 'elementary', in that it does not use group theory etc.?
Comment: Primality or otherwise of $F_n$ is a different issue. I think that even if we prove the thing for all Fermat numbers,$2^{2^{n}}+1$, it should be ok. And, as you said, there ain't a simpler way to prove the thing anyway :)
Comment: Bellarkyar : But the point is that if $F_n$ is NOT prime, then the exprssion of $F_n$ in that form is definitely not unique, as my answer below indicates.
Comment: yes, I was checking this thing on sage and the non-prime representations aren't unique indeed.
Answer: The uniqueness follows because $R = \mathbb{Z}[\sqrt{-2}]$ is a Euclidean domain whose only units are $\pm 1.$ As you correctly observe, no rational prime $p$ congruent to $1$ or $3$ (mod 8) remains prime in $R.$ Then there is a prime $z$ in $R$ such that $z \overline{z} = p,$ and the only other primes $w \in R$ with this property are $-z, \overline{z}$ and $-\overline{z}.$ Hence if $z = a + b \sqrt{-2}$ for rational integers $a$ and $b,$ then $p = a^2 + 2b^2$ is the unique expression of $p$ in the form required with $a$ and $b$ positive. The conjecture is true. If $q$ is any prime which divides $F_{n}$ for $n >1,$ then we certainly have $q \equiv 1$ (mod $8$). If $F_n$ is divisible by more than one rational prime, it is a easy matter to combine the corresponding primes from $R$ and their complex conjugates in different ways to produce more than one representation  of $F_n$ in the form $c^2 + 2d^2$ for rational integers $c$ and $d.$ If $F_n$ is a power higher than the first of a single rational prime, a similar argument can be applied.
Comment: Although the conjecture is correct, it is not clear that it provides any further insight into checking whether $F_n$ is prime.
Comment: ,I wrote primality test in Maple based on this conjecture but it doesn't seem to be practical because computation time is large...


My function doesn't return an entire sentence

Question: So I'm trying to learn python better and i've been using this website http://www.learnpython.org/
I'm on to functions right now, heres the code
#Add your functions here (before the existing functions)

def list_benefits():
    myList = ['More organized code','More readable code','Easier code reuse','Allowing     programmers to share and connect code together']
    return myList

def build_sentence(info):
    addMe = " is a benefit of functions!"
    for i in info:
        meInfo = i + addMe
    return meInfo

def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print build_sentence(benefit)

name_the_benefits_of_functions()

the output being

e is a benefit of functions!
e is a benefit of functions!
e is a benefit of functions!
r is a benefit of functions!

What am i missing to return the whole scentence
Comment: There's no OOP in your question.
Comment: Was going to fix it but tMC got it for me, thanks tMC
Answer: Inside  def build_sentence(info):
No need to loop over info since you'll get character by character.
def build_sentence(info):
    addMe = " is a benefit of functions!"
    return info + addMe

Also
In this part:
for i in info:
        meInfo = i + addMe
    return meInfo

You are setting up meInfo every time in the loop constantly changing that value.
At the end you are just returning the last value you got from the loop
Answer: Your build_sentence() function iterates over the string passed to it, and binds each letter plus the other string in turn to meInfo. After it finishes with the last letter, it returns the value. The fix is to stop iterating over the string and instead just add the whole thing and return.
Comment: could you explain that to someone who doesn't understand the lingo quite well?
Comment: `>>> for c in 'foo!': print c`
`... `
`f`
`o`
`o`
`!`
Answer: When you write:
def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print build_sentence(benefit)

you call build_sentence() with a string argument.  build_sentence then iterates over the characters in the string, with the effect that you see.
Instead, call build_sentence passing the entire list.  This will iterate over the list, attaching the extra text to each item in the list (not each character in a string).
def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    print build_sentence(list_of_benefits)

Also, inside build_sentence, you create and then throw away the text created from each list item, returning only the last item and extra text.  If you want to print each one you can either move the print statement inside the build_sentence() function (and probably rename it to print_sentence() or you can create a list inside that function and return the list:
def build_sentence(info):
    addMe = " is a benefit of functions!"
    result = []
    for i in info:
        result.append(i + addMe)
    return result

Answer: The problem you're running into here is that your build_sentence() is taking an argument (each call is with a single string) but iterating over that and only returning the last result (thus it returns a sentence containing the last character of the string with the rest of the statically defined sentence).
If you iterate over a string then you'll be handing each character of the string.
Something like:
def build_sentence(benefit):
    '''Returns a sentence from a template filling in benefit as the subject'''
    return "%s is a benefit of functions!' % benefit

... will work with the rest of your code.
Alternatively you could have a build_sentences() function like:
def build_sentences(*benefits):
    '''Returns a list of sentences from a template touting each benefit'''
    results = list()
    for each in benefits:
        results.append("%s is a benefit if functions!" % each)
    return results

... and then simplt call that function one with a list of the benefits like:
build_sentences('More organized code','More readable code','Easier code reuse','Allowing programmers to share and connect code together')

... or
build_sentences(*myList)

This particular form (using *benefits as the parameters for the function definition, an either supplying a variable number of arguments to the function call, or using the *myList form to expand the contents of my list, applying that list into the "varargs" argument list is a little more advanced.  (It's also not strictly necessary for this case, you could remove the * prefix from both the function's parameter definition and the function's calling arguments.  In that case when calling the function with a literal list of benefits you'd have to wrap the literal string argument in [...] to make them into a literal string:
def tout_benefits(benefits):
    '''Given a list of benefits tout them using a template'''
    return [ "%s is a benefit of functions!" % x for x in benefits ]

tout_benefits(['More organized code','More readable code','Easier code reuse','Allowing programmers to share and connect code together'])
# Notice called with `[ ..., ..., ... ]`

Also notice, in this last form, I reduced the for ... loop into a more compact "list comprehension" ... and expression returning a list.  I could have used that form in the previous example as well; but wanted to introduce it separately from making the point about varargs (variable parameter/arguments) handling.
Also note that you could use + expressions in place of "%s ..." % for all of these examples.  However, the "string formatting" operator gives you considerably more control of exactly how values are interpolated into your template/strings and allows for multiple values, types, numeric precisions, and a number of other features far beyond simple string concatenation (using +).
Answer: Modify this function to return a list of strings as defined above:
def list_benefits():
    return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"

def build_sentence(info):
    return "%s is a benefit of functions!"% (info)

Modify this function to concatenate to each benefit - " is a benefit of functions!":
def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print build_sentence(benefit)

name_the_benefits_of_functions()


How can I search across Excel sheets?

Question: I want to transfer data automatically from 2 sheets to one single combining one. That means I have 2 different export sheets (called 'Te_open' and 'Te_closed') that contain both the columns "Problem" (in different positions, can vary always). I have one sheet, that represents an overview of the data from the two other export sheets. So when I have for example the value "Te1" in the cell A2 of my overview sheet, I want Excel to search in the two export sheets the value "Te1" and give back the value in the same row as "Te1" but of the column "Problem", so that I can fill the cell B2 where I want to have the Problem type. So I thought I might need the "MATCH" formula, to let excel know I want to search the column with the headline "Problem" in the export sheets, to fill the column "Problem" in my overview sheet.
The problem that I see is that I have to search TWO sheets and I don't know in which one the "Pm1" will appear. Furthermore I don't know in which column of the sheet "Problem" will appear.
Can you please help me? I would preferably like to solve the problem with a formula, not a macro. Thank you very much in advance.
Kind regards,
question
Comment: Is the value that you're searching for (e.g. 'Te1' in your example) always in column A, but it could be in column A of 'Te_open' or column A of 'Te_closed'? How do you identify 'the columns "Problem" (in different position, can vary always)' - do you mean the column you want to refer to has the text 'Problem' in row 1?
Comment: Exactly, I always search for the column with the test 'Problem' in the first row. @nekomatic
Answer: To find the index of the first column in one of your sheets that is headed 'Problem', you can use (e.g.):
=MATCH("Problem",Te_open!$1:$1,0)

Let's assume we place that formula in a cell somewhere and name the cell open_col. To find a value in column A of Te_open and return the corresponding value from the 'Problem' column, you can then use:
=VLOOKUP(A2,Te_open!$A$2:$Z$999,open_col)

Note that you'll have to define the search range to include the largest range that your data on Te_open could occupy. If the search value is found this will return the corresponding value from the 'Problem' column, otherwise it'll return #N/A. So if you've also set up a cell called closed_col to get the column index for the Te_closed sheet, you can do:
=IF(ISNA(VLOOKUP(A2,Te_open!$A$2:$Z$999,open_col)),VLOOKUP(A2,Te_closed!$A$2:$Z$999,closed_col),VLOOKUP(A2,Te_open!$A$2:$Z$999,open_col)

That gets the result from the correct column of Te_open if the search value was found there, otherwise it gets the result from the correct column of Te_closed. If neither sheet contains the search value it'll return #N/A.

How can I search across Excel sheets?


What is the reasoning behind standardization (dividing by standard deviation)?

Question: Why does dividing a dataset by sigma make the sample variance equal to 1? Assuming a zero mean for simplicity.
What's the intuition behind this?
Dividing by the range (max-min) makes intuitive sense. But standard deviation does not.
Comment: The zero mean assumption isn't necessary. You can take this as three separate statements: dividing by SD gives an SD of 1; the variance is the square of the SD; and the square of 1 is 1.
Comment: When people say intuitive, I translate that as "familiar to me", and most of the time it fits. Reasons for not dividing by the range are practical rather than theoretical. The range can be highly labile. Also, often the range of all values is enormously larger than the that of the bulk of the values, so the results wouldn't be very helpful. Income illustrates both points: the observed maximum may vary capriciously and values divided by the range would often be concentrated near 0.
Answer: This stems from the property of variance. For a random variable $X$ and a constant $a$, $\mathrm{var}(aX)=a^2\mathrm{var}(x)$. Therefore, if you divide the data by its standard deviation ($\sigma$), $\mathrm{var}(X/\sigma)=\mathrm{var}(X)/\sigma^2=\sigma^2/\sigma^2=1$.
Comment: that helps, thanks. Do you have an intuitive approach?
Answer: Standardizing is is just changing the units so they are in "standard deviation" units. After standardization, a value of 1.5 means "1.5 standard deviations above 0". If the standard deviation were 8, this would be equivalent to saying "12 points above 0".
An example: when converting inches to feet (in America), you multiply your data in inches by a conversion factor, $\frac{1 foot}{12 inches}$, which comes from the fact that 1 foot equals 12 inches, so you're essentially just multiplying your data points by a fancy version of 1 (i.e., a fraction with equal numerator and denominator). For example, to go from 72 inches to feet, you do $72 inches \times \frac{1 foot}{12 inches}=6feet$.
When converting scores from raw units to standard deviation units, you multiply your data in raw units by the conversion factor $\frac{1sd}{\sigma points}$. So if you had a score of 100 and the standard deviation ($\sigma$) was 20, your standardized score would be $100 points \times \frac{1 sd}{20 points}=5sd$. Standardization is just changing the units.
Changing the units of a dataset doesn't affect how spread out it is; you just change the units of the measure of spread you're using so that they match. So if your original data had a standard deviation of 20 points, and you've changed units so that 20 original points equals 1 new standardized unit, then the new standard deviation is 1 unit (because 20 original units equals 1 new unit).
Comment: Some of your answer needs an extra assumption that you have subtracted the mean, but you don't mention that.  The thread question is equivocal here too, as in statistics subtracting the mean is the default, but it asks only about dividing by the SD.
Comment: OP mentions in the question the assumption of mean being zero
Comment: I don't think my answer requires that assumption if we're defining standardization as just dividing by the SD (which OP does). I'm just talking about a change of units, not with reference to the center of the data. E.g., for a scale with a mean of 50 and an SD of 10, I'm saying a score of 20 would have a standardized score of 2, not -3. Subtracting the mean (centering) is a separate issue.
Comment: Fair point. I don't think defining standardization as merely dividing by the SD is at all standard, so to speak, but granting your definition that value / SD $=: z$, say, then all data points that are positive are then above 0 on the standardized $z$ scale and only points that happen to be negative are below 0 on the $z$ scale. Whether that is as useful a standardization as (value $-$ mean) / SD is open to question.


How many times has Shoaib Akhtar bowled 160 kmph or faster?

Question: How many times has Shoaib Akhtar bowled faster than 160 kmph?
During the England vs Pakistan match in the 2003 World Cup, he delivered at the speed of 161.3kmph. Is this the only occasion?
Answers providing records of domestic matches are also welcome.
Comment: For a moment, I thought we were talking about lawn bowling or ten-pin bowling, and I enjoyed the mental visuals of 160kmph bowling in either of those sports. :)
Comment: No problem at all.  If you include the sport in the title, your question will perform better in search engine results, thus making it easier for others to find. :)
Comment: @RockPaperLz-MaskitorCasket I am not sure whether I should approve your edit because I have tagged cricket already and any cricket fan would at least know Akhtar's name. I leave that upon the mods :)
Answer: As per official records that is only time he has crossed the 100 mile per hour mark (which is 161kmph), Brett Lee and Shaun Tait being the only other cricketers to do so.
In local or other tournaments weren't recorded with that detail while Aktar was playing. I don't know with certainty that this is the only time he ever reached that mark in his career. On the other hand this is the only time he crossed it in international stage.
Comment: Could you please add a reference to the "official records" you are referring to here?


Can every open set of a polish space be expressed as a countable union of compact sets?

Question:
Let $X$ be a polish space and $A \subset X$ be an open subset. Can we find a sequence of compact subsets $(K_n)_{n \in \mathbb{N}} \subset X$ such that $A= \cup_{n \in \mathbb{N}} K_n$?

I read a post where the following conditions were mentioned: "In fact the statement holds in all hereditarily Lindelöf locally compact Hausdorff spaces...".
But there are polish space which are not locally compact. What is the reason for this disparity.
Answer: $C[0,1]$ with the usual sup norm is counter-example. This is Polish and the whole space is an open subset. If it is written as a countable union of compact sets, then Baire Category Theorem  would show that one of those compact sets must have an interior. But this makes the space finite dimensional, a contradiction.
[ If a compact set $K$ contains an interior point then some closed ball of (some postive radius)  is contained in $K$.  By transaltion, this makes the closed ball around $0$ compact. But this cannot happen in an infinite dimensional normed linear space].
$C[0,1]$ can be replaced with any separable infinite dimensional Banach space.
Comment: Thanks for your answer! I just don't understand the last argument: why follows from the fact that one of those compact sets has a non-empty interior that the space is finite-dimensional?
Comment: @JorisWk I have added some details.
Comment: thanks for your help!


Chrome, Safari, Firefox outputs XML differently

Question: I have this curious question. I was looking at XML files and so I did this twitter search:
http://search.twitter.com/search.atom?q=basketball
The output for Chrome looks like this:

The output for Firefox looks like this:

Then, the output for Safari looks like this:

My question is, what is going on? How can I get the browser to display it in different forms. In other words, if I want to output the <?xml ..., how can I do that?
Comment: What do you want it to look like?
Comment: The XML is exactly the same in all 3 browsers. They each implement their own way of natively displaying it. If you wanT it to look the same on all 3, you're gonna have parse and format it manually. There's no way to force all 3 browsers to display exactly the same unless you do that.
Comment: I suppose I was worried that the browsers append additional html into the page. So, it seems like there's some formatting, etc... going on. If I were to create a web service, I just want the pure xml instead of anything else appended to it.
Comment: If you're creating a web service, this won't matter, since the browser isn't involved. In that case you shouldn't follow my suggestion below; you should just leave it as-is.
Answer: If you want the browser to output the <?xml ..., send a header that makes the browser think it's a text file, not an XML file:
Content-Type: text/plain

Comment: If I do this, all browsers will output <?xml if I wanted them to instead of converting it into something else correct?
Answer: Some browsers will render XML with a namespace that they recognize. You can always 'view source' to see the text.
Answer: You most likely never want your end-users to look at raw XML anyway. Different browsers decorate raw XML as they wish to make it easier to find stuff in them, but it's still useless as a presentation format.
You should instead link your XML file with an XSLT file to transform it into HTML for presentation purposes.
Answer: Well, this is is not just any XML, but an Atom file (Atom is a standard for feeds, like RSS). The browsers (except for chrome) recognize it as such, and format it according to how they format feeds. If you want to view the XML source, just use your browser's View Source function (usually found at the right-click menu).


Can the Domino HTTP task serve content from another Domino server?

Question: Is there any way or trick to open some database resource that resides on ServerB by sending the request to the HTTP task running on ServerA?
Of course, both servers are in the same org, and have proper access rights...
Comment: @EEAA, I believe Domino is very good. I've tried other different technologies, and I still feel that working with Domino & Notes is a good investment :)
Comment: This is not about redirection. My question is about asking the HTTP task on ServerA to connect to ServerB over NRPC, read some content, and return it directly to the requestor, without redirecting to ServerB (which might not have the HTTP task running).
Comment: I have no answer, but rather just wanted to comment that 1) I had no idea that Domino was actually still a thing and 2) I am *so* sorry you have to deal with it.
Answer: Creating a db link on ServerA that points to the db on ServerB works fine.
From the Domino Administrator this is not possible. So, on ServerA create a text file in the data directory (or a sub directory of that), fill it up with ServerB/Domain!!Path\DBName.nsf and rename it to mydbname.nsf.
Now when http://ServerA/mydbname.nsf is requested, Path\DBName.nsf will get served from ServerB over NRPC to ServerA, then HTTP will hand it to the browser.
Comment: Of course! Great solution.


ExtJs in a ASP.NET web application

Question: I would like to understand if it is possible to use ExtJs as is (without any modification) in a web application built with asp.net server technology.
practically I would like to develop a Web application with ASP.NET using ExtJs as is, but I don't know if I can use it without problems of licensing.
Thanks in advance
Luke
Answer: If you are asking about it from the technical perspective, see my answer here.
If you are asking about licensing specifically (and I'm assuming you're asking about GPL) you can use it as long as your application is compatible with GPL.  If you have any doubts you should email email@example.com.  See also this question for some insight about Ext + GPL.
You should also look into Ext.NET if you haven't already -- they are the official Sencha .NET partner and offer the same dual licensing model as Ext JS.
EDIT: Any answer you get here will just be someone's opinion -- it will not be a basis for you to defend against an infringement claim by Sencha that you have violated their licensing.  You really should contact the company if you have any doubts -- see my answer here, including the comments.
Comment: Thanks a lot for your answer.
Actually my problem is concerning license of ExtJs and specifically GPL.
Let's say in another way: Is it a web application developed with ASP.NET compatible with GPL license?
Since an ASP.NET application has a server part binary files,in C# for example, I can imagine this part is a closed-source software, right?
So the server side binary files are part of my web application and if I didn't distribute them with source code, I would violate GPL, obviuosly using ExtJs.
Please tell me if I am arguing well.

ExtJs in a ASP.NET web application


Take value from on input to an input on the next page?

Question: I have an input field in a form - lets say:
<form action="/subscribe">
  <input type="emailadress" id="emailme" value="Email Address" />
  <input type="submit" value="Subscribe" class="cat_button" />
</form>

Then on the next page (subscribe.html) I have a full form.
What I'm trying to do is have the user enter their email address then press subscribe.
It takes you to subscribe.html
When you get to that page, your email address is already pre-filled.
EDIT : I don't have access to server side programming - only Javascript, HTML and CSS.
I'm looking into HTML5 session storage but have had no luck.
Is this possible?
Comment: This is very simple in php.  Are you open to a solution like that, or are you strictly after html5 storage?
Comment: You are creating too much work for you and the potential user. Why not create a link "subscribe" and have the user fill everything on the next page?
Comment: @Mike unfortunately PHP is not an option in this case as it's a closed system without access to PHP language.
Comment: @Joseph - its not my choice :)
Comment: If you don't have any server side programming language... what do you plan to do with the form once it's complete?  Print it off?
Comment: The second form is a MailChimp newsletter form so it will run off to them.
Answer: This is certainly possible. If you want an entirely client-side solution, one approach might be to capture the click event using a Javascript click listener, select the two elements in the form and read their values, and place those values into the session store. In the Javascript for the subscribe.html page, be sure to read out the values from the session store and fill in the appropriate input elements in the subscribe.html page.
Javascript + jQuery for first html page
$(document).ready(function() {
("myform").click(function() {
    var useremail = ("selector_for_email").val();
    sessionStore.setitem("useremail", useremail);
    // Don't preventDefault, allow form POSTing
});
});

Javascript + jQuery for the second html page
$(document).ready(function() {
        var useremail = sessionStore.getItem("useremail");
        ("input_elem").val(useremail);
    });

If you're open to a solution that involves the client and server, simply allow the user to submit the form (sending a POST message). In the route handler for subscribe, read out the POSTed data and populate the elements in the view template with the input values.
Python Back-end
@app.route('/subscribe')
def subscribe():
    if request.method == 'POST':
        useremail = request['name_attr_of_email_input']
        return render_template(subscribe.html, email=useremail)

Comment: Your first set of Javascript + Jquery at the top got me where I needed to be. Thanks for the help.
Answer: To do this with php, all you'd need to do is submit the form you've created (after appending a 'method="post"' to the form element, and giving your text input a name of, say, "emailme").
<form action="/subscribe.php" method="post">
  <input type="emailadress" name="emailme" id="emailme" value="Email Address" />
  <input type="submit" value="Subscribe" class="cat_button" />
</form>

From there, you'd change subscribe.html to a .php file, and do something like this on subscribe.php:
<?php
$email_address = $_POST['emailme'];

echo '<input type="emailadress" name="emailme2" id="emailme2" value="' . $email_address . '" />';
?>

Or:
<?php
$email_address = $_POST['emailme'];
?>

<input type="emailadress" name="emailme2" id="emailme2" value="<?php echo $email_address; ?>" />


rails 3.1.3: trying to run locally in production, asset pipeline not working

Question: My app runs fine in development mode.
When I run in production mode using RAILS_ENV=production rails s none of my .css or .js files get loaded. (I did precompile assets, using RAILS_ENV=production bundle exec rake assets:precompile.)
The webrick log shows:
ActionController::RoutingError (No route matches [GET] "/assets/application-a73ce43be7bf75953cd0c60b2b4a7eb0.js"):
and
ActionController::RoutingError (No route matches [GET] "/assets/application-986dd79830088c416c1632c12999ec69.css"):
The files were compiled (according to the log\production.log file) and my public/assets directory does show those files with and without the fingerprint:
ls public/assets
application-986dd79830088c416c1632c12999ec69.css
application-986dd79830088c416c1632c12999ec69.css.gz
application-a73ce43be7bf75953cd0c60b2b4a7eb0.js
application-a73ce43be7bf75953cd0c60b2b4a7eb0.js.gz
application.css
application.css.gz
application.js
application.js.gz

Answer: Rails doesn't serve static assets in production mode by default. If you want to disable this and serve the static assets, update your config/environments/production.rb file with this:
config.serve_static_assets = true

The reasoning behind Rails' default configuration is that it assumes you'll be running behind a standard web server in production mode (Apache, Nginx, etc.) which will then proxy the requests to your Rails app. Since the assets are precompiled, Apache/Nginx/etc. can directly serve them without needing to talk to your Rails processes.
Comment: @Dylan Just ran into the same problem - thanks for the awesome explanation!


Checking the type of a link in Sitecore

Question: I have a 'General Link' field in one of my pages in Sitecore. This field basically specifies the link of a video file which is used to play a video.
Now, what I am trying to do is, check if the type of this link, whether the user has uploaded a link as an internal link, media or an external link. I need this info as, depending upon the type of the link, I need to perform some actions accordingly.
Is there a way to do check the type of a link in Sitecore?
Answer: 1st you need to get the field off of your item.
Sitecore.Data.Fields.LinkField field = Sitecore.Context.Item.Fields["FIELD_NAME"];

Then, you can inspect various properties of your field.
bool isInternal = field.IsInternal;
bool isMedia = field.IsMediaLink;
string linkType = field.LinkType;

The various LinkType values are internal, external, media, anchor, mailto, and javascript
Answer: Let me state something additional please. In your case you want to have some additional action based on linktype. In the sitecore documentation you can find some more info about this. To help you on this see the code underneath:
public static string GetUrl(this Sitecore.Data.Fields.LinkField LinkField) {

        string url = "";

        switch (LinkField.LinkType) {
            case "internal":
            case "external":
            case "mailto":
            case "anchor":
            case "javascript":
                url = LinkField.Url;
                break;
            case "media":
                MediaItem media = new MediaItem(LinkField.TargetItem);
                url = Sitecore.StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(media));
                break;
            case "":
            default:
                break;
        }

        return url;

    }

This way you can get some method up that will always return you the correct url based on the link type. Good luck with it!

Checking the type of a link in Sitecore


Check whether this matrix exist or not

Question:
Does there exist a non zero $2 \times 2$ matrix $A$ such that $A^2 \neq 0$ and $A^3=0$, where $0$ is the $2 \times 2$ zero matrix?
Comment: Welcome to MSE! For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: @Vipra: Interrelate nilpotence and cayley Hamilton!
Answer: If such a matrix exist,$f(x)=x^3$ is an annihilating polynomial for $A$. Since minimal polynomial divides annihilating polynomials, $m(x)=x$ or $x^2$. Note that  $m(x)\neq x^3$, since the characteristic polynomial is of degree  $2$. If $m(x)=x$,we have $A =0$ and if $m(x)=x^2$,we have $A^2 =0$.
Hence such a matrix doesn't exist.

Check whether this matrix exist or not


Proof of standard normal by CDF

Question: Berger and Casella's Statistical Inference shows that given a random variable X ~ N($\mu, \sigma^2$), a random variable Z = (X - $\mu$) / $\sigma$ is distributed standard normal N(0, 1) by comparing expressions for the cumulative distribution functions. They say this fact is "easily established by writing":
$$
\begin{align}
P(Z \le z) &= P \left(\frac{X-\mu}{\sigma} \le z\right) \\
&=P(X \le z\sigma + \mu) \\
&=\frac{1}{\sqrt{2\pi}\sigma}\int^{z\sigma+\mu}_{-\infty}e^{-(x-\mu)^2/2\sigma^2}dx \\
&=\frac{1}{\sqrt{2\pi}}\int^{z}_{-\infty}e^{-t^2/2}dx\qquad
\left(substitute\, t = \frac{x - \mu}{\sigma}\right)
\end{align}
$$
Can somebody please expand on the last step here? The transition to $-t^2/2$ in the exponent is a clear consequence of substituting $\frac{x-\mu}{\sigma}$ for $t$, but how does $z\sigma+\mu$ tranform to $z$ in the upper limit, and where does the $\sigma$ in the constant go? I think I'm missing a straightforward piece of calculus, or something even simpler ...
Answer:
how does zσ+μ tranform to z in the upper limit

If x=zσ+μ, what's t?
That's how substitution always works with limits; the limit is now in terms of the new variable.

where does the σ in the constant go? I think I'm missing a straightforward piece of calculus

You seem to be forgetting the Jacobian. What's "dx" in terms of "dt"?
It might pay to go back and revisit the basics of transformation in integrals.
https://en.wikipedia.org/wiki/Integration_by_substitution#Definite_integrals
Comment: Indeed, I was just forgetting my substitution rules!

Proof of standard normal by CDF


Apache Jmeter Concurrent Users Performance Testing

Question: I want to test 400 Concurrency Users Which allow us to pass our load testing scenario as I am using below configuration setting in Apache JMeter which will through us lots of errors.
Number of Thread (Users): 400
Ramp-Up Time: 1
Loop Count: Forever Until ( Period of 1 minutes )
Answer: We are not telepathic enough to tell what's wrong with your setup without seeing the configuration and the nature of errors.
Several generic hints:

Run your test with 1-2 users/iterations to ensure it works fine and does what it is supposed to be doing. Check requests and responses details using View Results Tree listener
Make sure to run your test in command-line non-GUI mode and disable all the Listeners while your test is running.
It is better to increase and decrease the load gradually so consider using longer ramp-up time and increase test duration accordingly. I.e.

During the first minute virtual users arrive
They then hold the load for another minute
During the last minute virtual users leave

This way you will be able to tell what was the load when the errors started occurring, what is the maximum number of users your application can support, where is the saturation point, does it recover when the load gets back to normal, etc. See JMeter Ramp-Up - The Ultimate Guide article for more details.
It might be the case you found the bottleneck, i.e. your application fails to support 400 concurrent users, now you need to find the reason which may be in:

incorrect middleware configuration (wrong web server, database, load balancer settings)
your application simply lacks resources (CPU, RAM, Network, Swap, etc.). You can check this using JMeter PerfMon Plugin
if infrastructure configuration is OK and there is enough headroom for the application to operate most probably the reason is in the application code, you need to inspect what it is doing using APM or Profiler tools and report the issue.


SSL errors - .well-known

Question: I am seeing lot of SSL errors after enabling SSL for my site.
Following is the common error related to the SSL configuration:
<code>AH01797: client denied by server configuration: /var/www/xxxxxx/.well-known
</code>
Is this something related to any settings in our Drupal folder like creating ".well-known" folder or adjusting .htaccess settings or is it related to the Apache settings?
Answer: That folder is needed by LetsEncrypt and is nothing to do with Drupal. For some details elsewhere on the SO network see https://serverfault.com/questions/796745/letsencrypt-do-i-need-to-keep-well-known-accessible-for-certificate-renewal
Comment: Ok. So, Can I ignore those error messages or if I create that folder in my root Drupal installation, what files should I add in that folder?
Comment: Please keep this site for questions about Drupal only, there are other resources out there for unrelated questions. Thanks

SSL errors - .well-known


Log4net parou de mostrar os logs

Question: Meu console parou de mostrar os logs do nada, já compilei várias vezes e nunca me aconteceu isso, só agora
Código:
    public static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

log.Info("Hello World")

O Hello World não aparece, mas se eu fizer Console.WriteLine("Hello World") aparece no console, oque pode ser? Queria que voltasse a aparecer o log.Info.
Será que pode ser algum bug?
Algumas vezes aparece só os log.error:
Comment: Deve estar faltando alguma configuração aí no seu app, coloquei detalhado na minha resposta.
Answer: Tem 3 itens que você precisa checar.
1- App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="ConsoleAppender" />
    </root>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>

  </log4net>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

2- Assemblyinfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

3- Seu Programa:
    public static class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            log.Error("Hello World");
            log.Warn("Hello World");
            log.Info("Hello World");
            Console.ReadLine();
        }
    }

Pronto :)

Código fonte do meu teste:
https://github.com/thiagoloureiro/Log4Net
Comment: não entendi.. o que tem o seu Edit ? a data? aí é o formato que voce define nas configurações do log..
Aqui oh
Comment: Eu queria que fosse igual ao meu edit, teria como?

Log4net parou de mostrar os logs


Can a goalkeeper chip the ball to the head of a teammate from a goal kick to circumvent the backpass restriction?

Question: If you've been following the 2019 International Champions Cup, you've certainly not missed Benfica's unorthodox goal kick against Milan (clip on Twitter). If you can't see the video, just know the goalkeeper had a defender stay very close to him, so he could flick the ball to his centre-back, who then headed it back to him so he could pick it up with his hands and resume play more easily.

Now, I originally thought this would not be allowed, as Law 12 punished whoever uses a trick to circumvent the backpass rule, and the fact there are two offenders instead of just one shouldn't change anything, especially in a case like this where the intent of circumventing the law is clear as day (Law 12.3).

There are different circumstances when a player must be cautioned for unsporting behaviour including if a player (...) uses a deliberate trick to pass the ball (including from a free kick) to the goalkeeper with the head, chest, knee etc. to circumvent the Law, whether or not the goalkeeper touches the ball with the hands

However, it appears that several people have contacted the IFAB following this situation, and surprisingly enough they have stated this kind of goal kick is legal. But while it's obviously up to them to decide what constitutes unsporting behaviour (so I can't really complain there), what truly puzzles me is their explanation as to why this should be allowed.
According to many people, including Dale Johnson (link to his tweet), the IFAB said this is legal because "[n]o handling backpass Law was designed to prevent time-wasting and actions here are clearly not to waste time". This is also confirmed by other tweets which provide screenshots of emails written by David Elleray himself (Technical Director of the IFAB), that again mention the fact that "no law [was] broken", and that "game [was] restarted quickly" (link to tweet, image below).

Now, let's consider that sentence from Law 12 again, the one that punishes trickery; it's considered unsporting behaviour, meaning that something about it is against the spirit of the game. This "something" can only be one of these two things:

the unfair action is trying to circumvent the Laws, OR
it is specifically going against the spirit of the backpass law.

Now, if the correct answer were the first one, this means that any attempt to circumvent a rule could result in a yellow card (remember that the list of unsporting behaviour offences is a mere list of examples, which could be expanded to include any other act or behaviour the referee deems to be just as unfair), which would then clearly include this situation as well. Yet the email in that screenshot clearly states that "no Law [was] broken", which means this can't be the correct interpretation; I've heard the IFAB also likened this situation (but sadly I have no screenshots of this) to kicking the ball at an opponent while taking a free kick in order to replay it, which could be seen as a way of circumventing the rules, but is instead—as we all know—permitted by the Laws themselves.
This leaves us with only one possible option: the unfair action behind the no-trickery rule is specifically going against the spirit of the backpass rule—and thanks to the first tweet (but it's also hinted in the email in the screenshot) we know what that spirit is: to prevent time-wasting.
But then, doesn't it mean that goalkeepers are able to handle most backpasses now?
Very rarely do goalkeepers feel the need to handle a backpass during a tiki-taka situation: this offence is more often than not called when a defender has no other choice but to kick the ball back to the keeper because he's being pressed by the opponents, and the GK accidentally picks it up with his hands. Yet there's no time-wasting ploy in the situation I just described, is there? It's just a defensive scheme, especially if the goalkeeper immediately throws the ball with his hands like the Benfica GK in the video above. Whistling for a foul here would mean going against the spirit of the law.
And the situation gets even more absurd when you think that if the defender flicked the ball up to his own head and then headed it back to the keeper under the very same circumstances, then the GK could legally pick it up according to this new interpretation because they weren't trying to waste time! Which means that if we punish the foul we're applying a rule outside of the scope it was originally intended for, and therefore we're encouraging players to circumvent it in situations where the spirit of the law would not be broken, in which case we're actualy told not to intervene because it would be legal for them to circumvent it!
What do you think of all of this? How should the referee deal with these offences after this groundbreaking new interpretation by the IFAB?
Comment: While the question about whether this is a trick for the purpose of a USB caution in LOTG, this question as written is just seeking to start a discussion and opinion poll, and therefore should be closed.
Comment: Really, @Nij? The very last sentence is "How should the referee deal with these offences after this groundbreaking new interpretation by the IFAB?", that's a pretty legitimate question in my opinion.
Comment: And the question immediately before it is "What do you think of all this?" And the majority of the body is irrelevant to the question of legality.
Comment: It's not irrelevant, @Nij. I included those considerations of mine to prevent people from just saying "No, handling backpasses isn't allowed because the Laws say it's an offence". This isn't opinion-based: I'm asking people if I can indeed logically deduce (from the Laws of the Game and Elleray's statements) what I deduced in the body of the question. Seems like something that would have a definite answer to me.
Comment: It isn't logically deductable at all if the two premises are contradictory, and since one is itself an opinion, the answer to whether they contradict or agree is itself also of opinion.
Comment: While now unwieldy, the title did not match the body of the question, which has [confused at least one new user](https://sports.stackexchange.com/a/22916/3526). I've made an edit, please feel free to re-edit or rollback if this is not an improvement.
Answer: The IFAB issued a clarifiying statement on the matter.

There has been much debate about whether, at a goal kick, the goalkeeper is permitted to 'lift' the ball to a team mate to head or chest it back to the goalkeeper to catch and then put into play. The views of technical and refereeing experts about whether this is within the 'spirit' of the Laws is divided so the matter will be discussed by The IFAB. Until then, this practice should not be permitted nor should it be penalised. If it occurs the referee should order the goal kick to be re-taken (but without any disciplinary action).

Apparently, the IFAB is having the same discussion as you. Until further notice, the goal kick shall be re-taken without yellow card. Therefore, this move is illegal, as of the writing of this post.
Comment: I was at a referee meeting yesterday evening and this same clip was shown. Much debate and the message is that whilst it is not illegal refs are recommended to have the goal-kick be retaken. Apparently this is an official IFAB standpoint.
FWIW my opinion was that this is illegal as it gives the goalkeeper much more options than the original goal-kick.


Nevin's problem 1.4.10

Question: If anyone can offer any guideline on how to start this type of problem, I'd be really thankful. It's a home-work problem, so please just offer some hints not entire solutions.
Thank you.
Let L be a set of n elements. Count the number of ordered pairs (A,B) of subsets such that
$ \varnothing \subseteq A\subseteq B \subseteq L$. Let c(j,k) denote the number of such ordered pairs for which A contains j elements and B contains k elements. Show that:
$\sum_{}^{0\leqslant j\leqslant k\leqslant n} c(j,k) \cdot x^j \cdot y^k = (1 + y + yx)^n$
Answer: The left side is just the generating function for $j$ elements of $A$ and $k$ elements of $B$. We'd like to come up with a combinatorial explanation for the right hand side. Notice that $x$ is attached to $A$ and $y$ is attached to $B$.
There are $n$ elements. Each of these elements are in neither $A$ nor $B$ (corresponding to $1$), are in $B$ but not in $A$ (corresponding to $y$), or are in both $A$ and $B$ (corresponding to $xy$). Since there are $n$ elements and you're just counting them, these possibilities are given by $(1 + y + yx)^n$.
Your goal is to understand this and make it rigorous (or at least as rigorous as you think is necessary to connote understanding).
Comment: ahhh! it does make more sense!! thank you :)

Nevin's problem 1.4.10


Interpretation of the coefficent on an interaction effect in a linear-log model

Question: Hi I have the following regression model:
\begin{align}y=\beta_0 +\beta_1x_1+\beta_2x_2 +\beta_3 \ln(x_3)+\beta_4[\ln(x_3)\times x_1] + \mu_{ti} \end{align}
How would you interpret $\beta_4$?
My own thinking is that it is the $\frac{\beta_4}{100}$ is the ceteris paribus partial effect of a 1% increase in $x_3$ on the partial effect of $x_1$  on $y$. Is this in any way correct?
Answer: Your interpretation is correct.
Differentiating the expected value of $y$ with respect to $x_1$ yields
$$\frac{\partial y}{\partial x_1} = \beta_1 + \beta_4 \cdot \ln x_3$$
This is the change in expected $y$ (in units of $y$) associated with a one-unit change in $x_1$. It's a function of $x_3$.
How does this function behave when you change its argument? Differentiate it with respect to $x_3$:
$$\frac{\partial y}{\partial x_3 \partial x_1} =\beta_4 \cdot \frac{1}{x_3}$$
Bring $x_3$ over to the left to get:
$$x_3 \cdot \frac{\partial y}{\partial x_3 \partial x_1} =\beta_4$$
You can (approximately) rewrite that as
$$\frac{\frac{\Delta y}{\Delta x_1}}{100\cdot \frac{\Delta x_3}{x_3}} =\beta_4$$
The numerator is the change in expected $y$ for 1 unit change in $x_1$. The denominator is $1\%$ change in $x_3$.
If I can be picky, this is for expected $y$, since regression models the conditional mean of $y$, not $y$ itself.
Comment: Amazing, thank you for your response!


What chords can be played on an accordion?

Question: I've looked into how an accordion works and I want to play one in the music school. A piano accordion with 6 rows of buttons on the left hand, to be precise.
Now, I've been brainstorming about playing some songs and I wonder if some special chords might be playable on the accordion with the left hand. I know that there can be major, minor, dominant 7 and diminished, but I'm wondering about something else. Here are my chords:
(Note: English is not my main language so most of the things regarding music will have a big language barrier. Please help me correct my terminology.)
<code>In Eb major and C minor key:
BASS: Bb; CHORD: Bb Eb (F)G  - Sustained 64 (from classical harmony) on Bb major
BASS: F ; CHORD: F  Ab C  Eb - F minor minor 7 with
BASS: F ; CHORD: F  Ab (C)D  - 2nd inversion of D diminished optionally mixed with F minor
BASS: Ab; CHORD: F  Ab Bb D  - 2nd inversion of Bb dominant 7
BASS: Eb; CHORD: Bb D  Eb G  - 2nd inversion of Eb major major 7
BASS: D ; CHORD: D  F  G  B  - 2nd inversion of G dominant 7
BASS: C ; CHORD: C  D  Eb G  - C minor with an extra major 9th
BASS: D ; CHORD: G  B  Eb    - 1st inversion of Eb augmented
</code>
Do you know if these chords can be played only with the left hand while the right hand plays a melody?
Comment: "I know that there can be major, minor, major 7"

That should be "dominant 7", not "major 7".  (Most people take "C major 7", for example, to mean C, E, G, B, but the accordion row is for dominant 7 chords like C, E, G, Bb.)
Answer: Generally, the accordion standard bass is rather uninterested in inversions, less so than even the guitar.  In almost all registrations, the respective chord notes sound in several octaves simultaneously and the chosen inversion is not determined by the player but by the layout of the chord reed banks.
The chords are "grounded" by playing an appropriate bass note (usually in an accompaniment pattern that alternates between bass notes and chords).
So basically forget about inversions: you get to choose your bass notes, but the chords have a fixed inversion and the octaves of both bass note and chord are determined by the registration and the reed bank layout and are usually rather fuzzy through the use of multiple octaves.  Bass notes are usually coupled into both bass and chord reed banks, making their octave relation even fuzzier.  Mostly Italian instruments may even have different octave breaks for different reed banks: an Excelsior I have here starts octaves in the bass at A1 and A2, and in the chords with F#3, C4, C5 so if you register "Master", scales in the bass (which use all reed banks) have several different octave breaks in the result.
Apart from that, chord buttons may be combined.  This is helped by diminuished chords never having a fifth, and by seventh chords almost never having a fifth (with the exception of some older mostly German instruments).
Since many jazz chords are actually "stacked" triads, one can often play them using two buttons (exception: suspended chords which you can only approximate by deliberately tolerating some non-chord notes).
For example c+em yields cmaj7, c+am yields am7, c+gm yields c9, and so on.  Of course, once you stack chords, the "no inversions, single octave" deal of the standard bass becomes more of a nuisance and it becomes more important to "ground" the chords with suitable bass notes.  It is sufficient to alternate them with the resulting complex chords: this is less mushy than playing all of once, needs less air, sounds more interesting and the result is psychoacoustically still rather firmly connected to the bass note.
Answer: Here a like to the usual Stradella layout for a piano accordion (and the bass of many button accordions.) https://en.wikipedia.org/wiki/Stradella_bass_system
The columns go by fifths up (and thus fourths down). The bass rows are simple.
The fifth row is the bass line. There is a indentation on the C bass button. The sixth row is a major third above the bass row, so that button plays an E.
The next column up has a G and a B and the next column down has an F and an A respectively in the fifth and sixth rows.
The chords are a bit more complex. The fourth row the major chord with root in the bass, so C,E,G for the C column. The next row is the associated minor chord is C,Eb,G.
The second row is called the dominant seventh row; it is the dominant seventh with the fifth missing (so it's an Italian sixth in another key.) For the C row the notes are C,E,Bb (it the Italian sixth for E-major or E-minor). The first row is the diminished seventh chord with the fifth missing, C,Eb,A.
The fifths are omitted for two reasons (suggested by Stradella so the layout got his name): first, all chords have three notes and the weight between the tones are balanced, and second, one gets the augmented sixth chords easily.
What I do is play the chord of interest and sometimes add missing things (like ninths or sixths) in the right hand below the melody.
Answer: I use this page to find out how to get some fancy chords from a standard bass accordion: https://accordionchords.com/all-chords/
You can find chords charts for all these chords:

6th
7b5
7b9
7th
9/11
9th
Dim
min6
Maj7
Maj7/9
Major
min(Maj9)
min7
min7b5
min9
Minor


Why this code doesn't send an email with drupal_email()?

Question: I am developing a Drupal 6 module that should send an email after a form is submitted. So far, I wrote the following code.
function mailform_mail($key, &$message, $params) {
  $headers = array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
  );

  foreach ($headers as $key => $value) {
    $message['headers'][$key] = $value;
  }
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

/**
 * Form submission handler.
 */
function mailform_form_submit($form, &$form_state) {
  $valid_email = $form_state['values']['email'];
  $subject = $form_state['values']['Subject'];
  $body = $form_state['values']['body'];
  $params = array(
    'email'=> $valid_email,
    'body' => $body,
    'subject' => $subject,
  );

 // The first argument of drupal_mail() function must match the first part of the hook_mail function.
 // Therefore the first argument is  'mailform_form' and the the mail hook is 'mailform_form_mail'
 // For more infoormation see:
 // - http://api.drupal.org/api/function/drupal_mail/6
 // - http://api.drupal.org/api/function/hook_mail/6
 if (drupal_mail('mailform','reply', $valid_email, language_default(), $params, $from, TRUE) {
    drupal_set_message('An email has been sent to ' . $valid_email);
  }
  else {
    drupal_set_message('There was an error sending your email');
  }
}

Using this code, I can get the values after a form is submitted, but the mail is not sent out.
Is there anything wrong with the code? The module machine name is mailform.
Comment: You need to clear the cache after renaming the hook function
Answer: The answer's in your comments
//Therefore the first argument is  'mailform_form'

But you're using the string mailform as the first argument.
If your module is called mailform_form as your comments suggest, use this code:
drupal_mail('mailform_form','some_mail_key', $valid_email, language_default(), $params, $from, TRUE)

If it's named mailform, use your original call to drupal_mail, but change the name of your hook function to the correct one:
function mailform_mail($key, &$message, $params) {

Comment: @Clive.I have changed my code and executed after form submission its shows blank page.
Comment: Check your server logs for PHP errors
Comment: @Rahman And clear the cache, since Drupal caches the list of hooks implemented by a module. If you edit the code of an enabled module you need to clear the cache to let Drupal notice the code change.
Answer: The first argument of drupal_mail() is the module machine name, not the first part of the name for the function calling drupal_mail().
Since in the shown code there is a mailform_mail() function (which a hook_mail() implementation) and a mailform_form_submit() function (which is a form submission handler), I take the module machine name is mailform. Therefore, those function names are correct, and the email isn't sent because other issues.
For example, mailform_form_submit() is called as form submission handler if the form has a submission module and the form builder is mailform_form(). Otherwise, the submission handler won't be called and the email won't be sent.
To verify which is the module machine name, look at the name of the file that has .module as extension.
If that file is mailform.module, the code is correct.
If that file is mailform_form.module, the code needs to be changed, since:

All the hook implementations for that module needs to have a name starting with mailform_form_. Instead of mailform_mail(), it must be mailform_form_mail().

mailform_form() as form builder should be avoided, as the function name would only contain the machine name. For example, I would call the form builder mailform_send_form() and the form submission handler mailform_send_form_submit().

The code sending the email should use drupal_mail('mailform_form','reply', $valid_email, language_default(), $params). I omitted the last two parameters, as:

The default value of the last parameter is TRUE; it's useless to use that value
$from hasn't been initialized; it's like passing NULL for the sixth parameter, which uses that value as default one


Installing a module on a separate database

Question: I currently have a Drupal 7 site with a big database. I have to install the Drupal Commerce module and I would like to install the module using a separate database.
I know I have to setup the second database in the settings.php file, but I don't know the next steps I should follow.
How can I tell Drupal to use a different database for a module I am installing?
Comment: First of all why? What exactly are you trying to achieve in the end? And have you already heard of multisites? You should probably better provide a new multisite instance.
Comment: What does 'install to another database' mean? Modules are registered as items of configuration.
Comment: Nope, i don't know about multisites.
The reason why I want to have two databases is not to mix the commerce section with the the rest of the site.
I fear that having the commerce tables in the same database may affect overall site performance.
Comment: Setting Drupal to use a different database for some tables is possible, but if the task is using a different database for all the tables used for a module, that is different. I would agree that a multi-site instance is probably the better solution.
Comment: The question seems clear, to me. It's possible to answer it with an answer that isn't too long, even if explaining how to setup a multi-site instance could use a link to Drupal documentation.
Comment: Even creating another multi-site instance has its cons, anyway: It's another instance of Drupal that runs under a different domain/directory, with its own database tables (e.g. its owns sessions, user data).
Answer: Drupal can be configured to use a different database for some of the tables. For example, with the following database settings, I would tell Drupal to use the db2 database for the users table.
<code>$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'db1',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => array(
    'users' => 'db2.',
  ),
);

$databases['default']['db2'] = array(
  'driver' => 'mysql',
  'database' => 'db2',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => '',
);
</code>
It doesn't actually work for PostgreSQL because a bug in Drupal core, and it works for those database engines for which using a different schema means using a different database.
Doing so for every table used for a module is more problematic, since the prefix must be explicitly set for all the tables used for that module, which means:

You need to know which tables are used for that module, including the tables Drupal creates for that module
If a new version of the module uses tables the previous version didn't use, the prefix must be explicitly set before updating the module
If a new version of Drupal uses tables for that module the previous version didn't use, the prefix must be explicitly set before updating Drupal
If you plan to install another module that store data related to that module, the prefix for the new tables must be explicitly set before installing the new module

Furthermore, for data related to that module that are stored in a table that contains data from all the installed modules, storing that data in a separate table only for a module is probably impossible.
Using two multi-site instances—Drupal installations that use the same code base, are accessible from different URLs (for example, https://example.net instead of https://example.org, or https://example.com/commerce instead of https://example.com), and use different databases (which could also use different database engines)—where one of the instances has the Drupal Commerce module installed, you would resolve the problem to put all the Drupal Commerce tables in a different database.
You would not need to set which database is used for the Drupal Commerce module, as that is already set for each multi-site instance. This means that any change in the tables used for the Drupal Commerce module (which are created from the module itself, Drupal core, or any third-party module) would not require changes to the Drupal database settings. Even updating the Drupal Commerce module or Drupal core would not require extra work to change the Drupal database settings.
It would work for any database engine supported by Drupal or from third-party modules.
Since the multi-site instances don't normally share any data, in the same way two different Drupal sites don't share any data, if you want that users with an account on the multi-site instance without the Drupal Commerce module are able to access also the multi-site instance with that module without creating an account, or be logged-in when they already logged in into the first instance, you need to implement SSO on both the multi-site instances.
There would be other data duplicated between the two multi-site instances, but those data would probably be less than all the data stored for the Drupal Commerce module.


Drush unable to untar Drupal 8

Question: Something has happened to my Drush and I've run out of ideas.
It is unable to untar drupal-8.0.6.tar.gz. I discovered this while trying to update a site but it's nothing to do with the site because it happens when I try to download drupal into an empty directory.
The weird thing is that it works with Drupal 7. I'm running Ubuntu 14.04. Drush is installed globally with Composer.

ross@ross-laptop:~/drush-test$ drush --version
 Drush Version   :  8.0.5

ross@ross-laptop:~/drush-test$ drush -v dl drupal
Loading version_control engine.                                                                                [notice]
Loading package_handler engine.                                                                                [notice]
Executing: wget --version
Loading release_info engine.                                                                                [notice]
Downloading release history from https://updates.drupal.org/release-history/drupal/8.x                                                                            [notice]
Executing: wget --version
Executing: wget -q --timeout=30 -O /tmp/download_filec9M7oQ https://updates.drupal.org/release-history/drupal/8.x
Downloading project drupal ...                                                                                [notice]
Executing: wget -q --timeout=30 -O /tmp/download_fileW1T2nI https://ftp.drupal.org/files/projects/drupal-8.0.6.tar.gz
Downloading drupal-8.0.6.tar.gz was successful.                                                                                [notice]
Md5 checksum of drupal-8.0.6.tar.gz verified.                                                                                [notice]
Executing: tar  -C /tmp/drush_tmp_1460638235_570f921b1a52f -xzf drupal-8.0.6.tar.gz
Unable to untar /tmp/drush_tmp_1460638235_570f921b1a52f/drupal-8.0.6.tar.gz.                                                                                [error]
Error downloading drupal                                                                                [notice]
Command dispatch complete                                                                                [notice]
ross@ross-laptop:~/drush-test$

Now trying Drupal 7

ross@ross-laptop:~/drush-test$ drush -v dl drupal-7
Loading version_control engine.                                                                                [notice]
Loading package_handler engine.                                                                                [notice]
Executing: wget --version
Loading release_info engine.                                                                                [notice]
Downloading release history from https://updates.drupal.org/release-history/drupal/7.x                                                                            [notice]
Executing: wget --version
Executing: wget -q --timeout=30 -O /tmp/download_file9HXrRX https://updates.drupal.org/release-history/drupal/7.x
Downloading project drupal ...                                                                                [notice]
Executing: wget -q --timeout=30 -O /tmp/download_filelb2ETq https://ftp.drupal.org/files/projects/drupal-7.43.tar.gz
Downloading drupal-7.43.tar.gz was successful.                                                                                [notice]
Md5 checksum of drupal-7.43.tar.gz verified.                                                                                [notice]
Executing: tar  -C /tmp/drush_tmp_1460638348_570f928cdd995 -xzf drupal-7.43.tar.gz
Executing: tar -tzf drupal-7.43.tar.gz
Executing: svn info /home/ross/drush-test
Executing: bzr root /home/ross/drush-test
Project drupal (7.43) downloaded to /home/ross/drush-test/drupal-7.43.                                                                                [success]
Project drupal contains:                                                                                [success]
 - 3 profiles: minimal, testing, standard
 - 4 themes: garland, stark, bartik, seven
 - 47 modules: drupal_system_listing_compatible_test, drupal_system_listing_incompatible_test, toolbar, simpletest, image, openid, trigger, path, search,
forum, translation, statistics, locale, color, rdf, syslog, contact, menu, book, update, help, php, blog, filter, file, tracker, profile, block, dblog, poll,
overlay, taxonomy, shortcut, comment, user, number, field_sql_storage, options, list, text, field, node, system, contextual, field_ui, dashboard, aggregator

Command dispatch complete                                                                                [notice]
ross@ross-laptop:~/drush-test$

It successfully updated a module on my D8 site. The problem just seems to be with D8 core. I've checked permissions. The user I'm logged in as can create files and directories in /tmp.
Answer: Well, that's a tough one. I just downloaded Drupal 8.0.6 successfully on my machine; it untarred just fine. I can't think of anything that could explain why Drupal 8 wouldn't download, but Drupal 7 would. Well, I can think of one thing -- when I first tried this, Drush told me it was "retrieved from cache".  I ran drush cc drush and tried again, and it downloaded from drupal.org and untarred just fine. I might guess that the file was somehow corrupted on download, but (a) Drush checks the checksum, and (b) your debug output above shows that you're getting a fresh download.
Try running drush -v dl drupal --select --all and pick some other versions of Drupal 8.  Is it only 8.0.6 that will not untar, or are other releases also broken?
(Sorry for the long non-answer, but this didn't fit well in a comment.)
Comment: Thanks. I know this is weird. I had already tried a few other 8 versions but not quite enough. I followed your command and it works up to  8.0-alpha12. It fails on anything more recent. I've done everything I can think of to make things "clean". I've uninstalled drush by removing from the composer.json, deleted my ~/.drush directory and reinstalled drush. The results are consistent. It stops working for anything more recent than 8.0-alpha12.  This worked a few months ago when I upgraded from rc1 to rc2. I've installed and removed a few things since then but nothing that seems related to this.
Comment: I think I've found it. I'm almost out of disk space on / where /tmp is.
Comment: Ouch! Running out of disk space is tough. It would help if tools gave better error messages when this happens; Drush is not alone in needing improvement in this area.
Answer: Oops...
My laptop is almost out of disk space on the partition where /tmp is.  :-)
It downloads successfully but fails when it tries to copy. Each version of Drupal is a bit bigger than earlier versions.

Drush unable to untar Drupal 8


I have an "UnassignedReferenceException" error and my script and I don't how to fix it?

Question: I keep on getting the error

UnassignedReferenceException: The variable player of EnemyAI has not
  been assigned. You probably need to assign the player variable of the
  EnemyAI script in the inspector.

I am kind of new to all this scripting stuff, and I tried to check other forums, and they didn't help at all, but made me more confused. Here's the script:
using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

    public Transform player;
    public float playerDistance;
    public float rotationDamping;
    public float moveSpeed;

    //Use this for initialization
    void Start () {

    }

    //Update is called once per frame
    void Update () {

        playerDistance = Vector3.Distance (player.position, transform.position);

        if (playerDistance < 15f) {
            lookAtPlayer ();
        }
        if (playerDistance < 12f) {
            chase ();
        }

    }

    void lookAtPlayer()
    {
        Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
        transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * rotationDamping);

    }

    void chase()
    {
        transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}

}

Any Ideas?
Answer: Your variable player, which is of type Transform is used at
Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);

before assigning any values to it. I believe Transform is another class in your project and player is an object of that kind. You probably want to instantiate the object before trying to use it.
Something like
player = new Transform(...);

Comment: Unity components should not be created using constructors, and a `Transform` component is always added automatically to game object upon creation and can not be added.
Answer: In C#, references (such as your EnemyAI reference) can be set to Null, meaning that they are pointing nowhere. This leads to a lot of NullReferenceException errors, when your code tries to run some methods on an null reference.
I suspect that Unity created a special mechanism to prevent this errors from happening to you. Public fields of Unity's MonoBehaviours are used to set up MonoBehaviour's instances in the editor, before the game is even run. MonoBehaviours are typically not created from scratch, in 99% they are deserialised from instances that were edited and saved in the editor.
So, with this error, Unity warns you that you didn't assign any value to this particular instance of MonoBehaviour. To fix this, open editor, select the object that this error refers to (usually, you can just click the error in console and the object will get selected), set the reference to something, and the error will be fixed.
However, judging from context of your script, you may choose a different path. Most likely you have only one player in the scene, and at the same time you may have hundreds of enemies — you don't want to assign their references to the player a hundred of times! And if you'll want to use prefabs, you won't even be able to. So, instead of making this a public field, make it private, and assign it to this field at the initialisation, using Start method. FindGameObjectWithTag("Player") is one possible way to do that; however, in my experience, relying on tags (and strings in general) is sub-optimal in a strong, statically typed language such as C#, and I would use a Singleton or Service Locator patterns to find the player instead.


Prove that $\mu^* (F \setminus E) = 0.$

Question:
Let $\mathcal A$ be an algebra of subsets of a set $X$ and $\mathcal S (\mathcal A)$ be the $\sigma$-algebra of subsets of $X$ generated by $\mathcal A.$ Let $\mu : \mathcal A \longrightarrow [0,+ \infty]$ be a measure on $\mathcal A.$ Let $\mu^*$ be the outer measure induced by $\mu.$ Let $E \subseteq X$ and $F \in \mathcal S (\mathcal A)$ be such that $E \subseteq F$ and $\mu^* (E) = \mu^* (F) < + \infty.$ If $\mu^* (G) = 0,$ $\forall$ $G \in \mathcal S (\mathcal A)$ with $G \subseteq F \setminus E$ then show that $\mu^* (F \setminus E) = 0.$

I have proved that the outer measure $\mu^*$ on $\mathcal P(X)$ induced by $\mu$ can be equivalently defined in terms of the restriction $\bar \mu$ of $\mu^*$ to $\mathcal S (\mathcal A)$ as follows $:$ $$\mu^* (A) = \text {inf}\ \left \{\bar {\mu} (B)\ |\ B \in \mathcal S (\mathcal A), A \subseteq B \right \}.$$ Can it help anyway? I hardly believe that this result will hold. But how to find a counter-example?
Thanks in advance.
Comment: Shouldn't $\mu$ be a *pre-measure* since it's only defined on an algebra, not a $\sigma$-algebra?
Comment: I can show that $\mu^* \left ( (F \setminus E)^c \right ) = \mu^* (X).$
Comment: Can anybody give me some hint?
Comment: @md2perpe in my book, a measure is defined as a countably additive set function over a collection of subsets of a set $X$ containing the empty set $\varnothing.$
Comment: For more information you can go through the second edition of the e-book *An Introduction to Measure and Integration* by Inder K. Rana published by *American Mathematical Society* which is available online in pdf format.
Comment: I forgot to mention that measure of the empty set $\varnothing$ is considered to be $0.$
Answer: The claim to prove is wrong, as shows the following example.
Let $X=[0,1]$, $\mu$ be the Lebesgue measure on $X$, and
$\mathcal A=\mathcal S(\mathcal A)$ be a $\sigma$-algebra of Lebesgue measurable subsets of $X$.
Let $E\subset X$ be an arbitrary set such that $E\not\in\mathcal A$. For instance,
$E$ can be a Vitali set.
Let $F\in\mathcal A$ be a set such that $E\subseteq F$ and $\mu(F)=\mu^*(E)>0$.
Clearly, for all $G \in \mathcal S(\mathcal A)$ with $G \subseteq F \setminus E$
we have $\mu^*(G) =\mu(G)=0$. But if $\mu^*(F \setminus E) = 0$ then
$F\setminus E\in\mathcal A$, ans so $E\in\mathcal A$, a contradiction.
Comment: how did the author miss that? He claimed that in his book.
Comment: @mathmaniac. Maybe because the claim is formulated in too general and too abstract form.

Prove that $\mu^* (F \setminus E) = 0.$