Music and time, "natural" time

Question: To play music rhythm in time it was always something difficult to me, with a metronome also. Basically I can not count time. On the other hand I have some intuition to compose simple music, and when I do it I don`t care for time and just concentrate myself in "how it sounds", if it sounds good, like I want, I memorize, and I am not thinking if it is a "triplet" or not. Notation is artificial. I would like to understand both systems, but it seems just to function my natural way. What should I do?

Abandon Music;
Forget notation and play by ear (develop ear skills);
Compose and improvise and forget interpretation of the others work.
Comment: If you can't count time, it will be more difficult for you to be able to play in a band with other musicians. If all you want to do is play music by yourself, this is not as much of a problem.
Answer: Do whatever you want!
I know a man who, when handed a guitar, will perform Rod Stewart's I Don't Wanna Talk About It. He sings beautifully. He gets a nice tone out of his guitar. His bars last as long as he pleases - 4 beats, 5 beats, 7 beats, 6 beats.
Now, I find it quite uncomfortable to listen to - I want to sing along, quietly - but he comes in a beat early, or a beat late, every time. But it doesn't bother everyone, and many people very much enjoy his performances.
Play what you think sounds good. That might be enough for you. Other people may or may not like it; you need to decide whether you care what they think.
However, as Wheat says in his comment, keeping to a rhythm is almost essential when playing in a group with other musicians. If you played piano and I played bass, and I wasn't able to predict when your next note would come, or when you would change chord, we wouldn't manage to make any music worth hearing.
Music that deviates from a strict time signature is challenging for band musicians - for example I sometimes play with a set up beginner-intermediate guitarists, and certain Crowded House songs slip a 3/4 bar into a 4/4 song - it takes a few practice runs to get it right.
Answer: Music notation is more or less a unified way to describe and record music so that it can be repeated by other musicians. More broadly theory is just a way to understand why music "works". It's a set of "rules" that explain why one thing sounds good and another doesn't.
You don't need to know any of that to write or perform music, so certainly don't let it limit you creatively. But on the other hand music theory in particular can be be a very helpful tool in composition.
If an important part of your goal is documenting your music, then yes, you probably want to put some time into learning notation and theory. But don't stress about it for now.
All things can come in time with patients and practice.
Answer: You don't need to count to play in rhythm. You just need to "feel" the rhythm. Counting can distract you. You should know that your mind always counts when you listen to music. This is why 4/4 is nice and 7/8 can sound a little weird. Try tapping your foot when playing instead of counting. Also give rhythm the priority over technique and hitting the right notes. That's how I play, I never loose the beat, even if I had to skip a note, or hit a bad note.
As a beginner, I always tried to play all the notes without missing or skipping any. So I played with bad rhythm because I thought I would focus on it after I had memorized the notes better. I think this is a common attitude among all beginners and you should avoid it. If you can't play or improvise at a given tempo, slow down, but keep the temo steady.
Short Answer

You don't have to count or read music. You'll probably focus on it later as you improve.
Counting is distracting, instead of counting tap your foot.
Sacrifice some notes if you risk loosing the rhythm.
Practice at a comfortable tempo.
Answer: Counting becomes almost automatic with practice. I count music all the time. It's necessary for any complex dancing or for playing most "classical" (or "art") music. After some time counting along with the playing, it's almost subconscious.

Music and time, "natural" time


Concurrent access to list: what happens if objects are removed or the list is set to null?

Question: I have a List with objects List<> my_objects. Several threads can change this list. Let's suppose that I do not have any locking mechanism for controlling the access to the list.
What happens, if I'm working with an object of the list and suddenly another thread sets the array to null?
    MyObject o = my_objects[i];

    //now a second thread has set my_objects to null
    o.myMethod();

Will a NullPointerException occur?
Furthermore, what happens if a second thread removes the considered object from the list while I'm working with it in the first thread?
   //second thread:
   //y = i
   MyObject o2 = my_objects[y];

   my_objects.Remove(o2);

Comment: You'll most likely get an `InvalidOperationException` with the message "Collection was modified after the enumerator was instantiated."
Comment: Is it an array or a list? They're not the same thing.
Comment: Look into the System.Collections.Concurrent namespace objects... you could have a direct drop in that would be thread safe.  That doesn't answer a question, just thought I would point that out.
Answer:
What happens, if I'm working with an object of the list and suddenly another thread sets the array to null?

Nothing, if you've already copied the reference in question to a local variable.
You'll get an exception if another thread sets my_objects to null before this line:
MyObject o = my_objects[i]; // my_objects must be non-null

The value of o is just a reference to the object. It has no knowledge of the list or array you happened to get it from. The collection could be garbage collected, anything could happen - neither the reference nor the object itself is affected.
(The removal of the element from the list could cause problems, as Henk says - List<T> is not thread safe - but that's a different matter from the one I understand you were asking about.)
Comment: @curiosity: In both cases nothing about the variable `o` or its value changes.
Comment: thank you. I'm interested in both cases (setting to null and removal of the object).
Answer: In both cases, you've already got a reference to the object, and changing the list has no effect on the object itself. You won't get any exceptions because of the state of the object itself (e.g. NullReferenceException).
However you may get other exceptions because of the concurrent access to the List<T>. You should either use locking when accessing the list or, even better, take a look at the classes in the System.Collections.Concurrent namespace.
Comment: Not true. `my_objects[i]` is only safe when other threads read simultaneously. When they also write (mutate) all bets are off.
Comment: @HenkHolterman the way I read the question, the OP is concerned about list changes _past_ that line of code.
Answer: MyObject o = my_objects[i];

//now a second thread has set my_objects to null, and/or invoked my_objects.Remove(o)
o.myMethod();

That's fine. The variable my_objects holds references to objects, not the objects themselves. When you make a new variable o, it holds a second reference to the same object. Then you clear my_objects, which means you can't refer to the actual object through my_objects anymore. But that doesn't change the fact that you still have o, and you can still refer to the actual object through o. (And that in turn implies that the object itself still exists. C# is a garbage-collected language, which, to a first approximation means that objects are guaranteed to stick around until you're done with them. Non-managed C++ is different in this respect, and Objective-C is different in yet a third way. Not that you asked.)
Effectively, in this respect, references to MyObject behave just like primitive types like int. If I have an array of int, and I do
int oi = my_ints[i];

then I can do whatever I want with my_ints (clear it, remove items from it) and that won't change the fact that oi still exists.
The thing about reference types like MyObject, and the reason you got confused enough to ask this question, is that with MyObject both variables (o and my_objects[i]) still refer to the same actual object, so if you mutate the object via my_objects[i].gainSpiderPowers(), you'll see the effects of that mutation no matter whether you're looking via my_objects[i] or via o.
Answer: Consider using a ReadOnlyCollection.  It is located in the System.Collections.ObjectModel namespace.


sudo: unable to create sockets: Cannot allocate memory

Question: On a VPS run by OVH (apparently OpenVZ-based, given /proc/user_beancounters exists), with relatively few processes running, trying to sudo gives me the error in the title.
Here is a sample transcript:
ekleog@ekleog:~$ sudo echo a
[sudo] password for ekleog:
sudo: unable to create sockets: Cannot allocate memory
ekleog@ekleog:~$ free -h
             total       used       free     shared    buffers     cached
Mem:          8.0G       212M       7.8G         0B         0B        43M
-/+ buffers/cache:       168M       7.8G
Swap:         128M         0B       128M
ekleog@ekleog:~$ sudo echo a
sudo: unable to create sockets: Cannot allocate memory

As you can see, there is no problem forking, as the shell forks to run free, but sudo seems to be unable to open a socket. In the same domain, thunderbird is unable to open an SMTP connexion, but ssh keeps tunneling new requests without any issue.
The fact that the issue originates from too many sockets open seems confirmed by the fact that, when closing Thunderbird (which keeps something like 50 connexions to monitor all my IMAP folders) the problem vanishes. Besides, when reopening it, the issue does not prop back, so there must be a resource leak somewhere?
I am currently having a single user (me), so I hope OVH's restrictions are not that serious.
Finally, during the "crisis", I tried running netstat (not really used to its use, so I may be wrong):
ekleog@ekleog:~$ netstat -a | wc -l
608
ekleog@ekleog:~$ cat /proc/sys/fs/file-max
1627524

It seems strange to me that sudo would block.
Do you have any idea how to stop having this? It comes up from time to time (approx. once every other day), and is getting pretty annoying.
Apparently the problem comes from OpenVZ settings, as in /proc/user_beancounters I have numothersock with a huge failcnt.
Trying to reduce the number of open sockets being dependent on each individual program, I will ask separate questions.
Comment: Is this an OpenVZ VPS?
Comment: Half my sockets were due to postfix ; the other half to dovecot. ATM I cut down on postfix (mainly by removing unwanted lines in master.cf) ; it is enough to make my server work. If I reach the limit again, I'll go and look towards dovecot!
Comment: Find out which processes are using the most memory.  ps --sort -rss -eo rss,pid,command | head
Comment: `free -h` indicates 7.8G free, with only 212M used; is that not enough to start a process? Anyway I'll run this command next time the server starts blocking.
Comment: It seems to be: `/proc/user_beancounters` exists. Updating the post to reflect this; I will also on next time it bugs have a look at the content of this file, to check whether the limits defined inside are reached.
Comment: EEAA, if you would turn your comment into an answer I'd accept it: pointing me to OpenVZ restrictions made me understand exactly which limit blocked me. Thanks!
Comment: I was wondering, how did you eventually come through this? I have exactly the same problem.
Answer: I am going to share my findings in this answer, hoping that will help someone in the future. These findings would be impossible without the prompt observation in @EEAA's comment.
Indeed the restriction comes from the OpenVZ software. The numothersock restriction can be seen in /proc/user_beancounters and according to the documentation: 'UBC resources in Parallels Virtuozzo Containers for Linux':

numothersock - maximum number of non-TCP sockets (local sockets, UDP, and other types of sockets).

You can check the amount of sockets with ss:

ss is used to dump socket statistics.

ss -xa | wc -l

To identify which process binds each socket:
sudo ss -xap

For my specific case it turns out that more than 25% of my restriction in sockets was due to postfix, so I cut down the default_process_limit parameter in /etc/postfix/main.cf (relevant question here).
Answer: (Synonymous answer but adding some diagnostic info and search keywords.)
Symptoms
The issue at hand is that no new non-TCP sockets can be created, which means mostly Unix domain sockets used for inter-process communication in the system. It may not be reproducible always, as sometimes a few sockets are deleted, opening up a few options to create new sockets below the limit.
Symptoms are not restricted to sudo use but will affect most or all websites running on your server and using MySQL via a socket connection. Error messages would be like these:
PDOException: SQLSTATE[HY000] [2001] Can't create UNIX socket (12) in […]
PDOException: SQLSTATE[HY000] [2002] Can't connect to local MySQL server
    through socket '/var/run/mysqld/mysqld.sock' (12) in […]
PHP Warning:  mysqli_connect(): (HY000/2001): Can't create UNIX socket
    (12) in […]
PHP Warning:  mysqli_connect(): (HY000/2002): Can't connect to local MySQL
    server through socket '/var/run/mysqld/mysqld.sock' (12) in […]

In addition, sending and fetching e-mails via a postfix resp. dovecot server will probably also fail, at the login stage. Error messages include:
mailq: fatal: inet_addr_local[getifaddrs]: getifaddrs: Cannot allocate memory

The common element in these errors is error code 12, which means "OS error code  12:  Cannot allocate memory" as per perror 12 [source].
Solution
Look at the output of cat /proc/user_beancounters, which shows the OpenVZ virtualization environment limits of your VPS. In all probability, you will see a huge number of fails for the numothersock resource limit there (>10,000 for me). This means software tried to create a socket but was prohibited by OpenVZ from doing so because the maximum number of non-TCP sockets already existed.
To see the number and use of all sockets counted into this numothersock resource limit, look at the output file generated by:
ss --processes --all --socket=udp,unix,unix_dgram,unix_stream > results.txt

In my case, it showed that about 80% of sockets were related to postfix and dovecot processes. Postfix related sockets can be reduced to about 10% by limiting the number of concurrent connections from default 100 to a reasonable 10 – see the instructions. After applying that solution to postfix (default_process_limit = 10) and restarting it, my sockets in use went from ~1020 to ~520 immediately. Problem solved for now.


View Clipped with resolution 1080 X 1920 phones

Question: In my project have custom view has fixed width.The width is specified in values->dimen
<dimen name="layout_width">75dp</dimen>

The issue is that in some device(eg:Pixel) with resolution 1080 X 1920 this view is Clipped. However some other devices(eg:Pixel2) with same
resolution everything works fine.
Have tried using different dimension files as in this post .Both these device are picking from same dimen files
Code
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="21dp"
    android:gravity="center"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="55dp"
        android:layout_height="55dp"
       >

        <ImageView
            android:id="@+id/icon"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_centerInParent="true"
            tools:background="@drawable/icon" />
    </RelativeLayout>

    <TextView
        android:id="@+id/title"
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_marginTop="20dp"
        android:gravity="center"
        />
</LinearLayout>

Comment: post some screenshot with expected result and actual result
Comment: Where are you using `75dp` value?
Comment: You mentioned `width=75dp`. As I can see in your code it's the width of your TextView, not image. Please attach some screenshots from your pixel/pixel2 to understand what's the difference and what's cropping there
Comment: can you post your XML
Comment: <TextView
        android:id="@+id/title android:layout_width= @dimen/ayout_width
Comment: Cn you put a screenshot of the same and also you are not using the dimen resource in your layout. Try using the same. Also, does the text looks bigger in the device in which it is clipping?
Answer: Inside your imageView, experiment with different scaleTypes to see if any fit your use case.
    <ImageView
        android:id="@+id/icon"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_centerInParent="true"
        android:scaleType="fitCenter"
        tools:background="@drawable/icon" />

Other acceptable scaleType values are  FIT_XY, FIT_START, FIT_CENTER, FIT_END, CENTER, CENTER_CROP
Comment: It works only for ImageView. I think @Nikhil was asking for a solution which works for different types of Views.
Answer: This happens due to different screen dpi of devices.
like normal 1080*1960 devices v/s nexus 5x (which has higher dpi with same resolution)
Another example can be of Samsung galaxy edge S6 (it has much higher dpi as 577dpi with xxxhdpi resolutions).
The most consistent and reliable solution would be not to use static height width, instead arrange layouts in such a way using wrap_content and match_parent properties and relative layouts
Comment: As mentioned in question, phones were Pixel and Pixel2: [compare phones](https://www.gsmarena.com/compare.php3?idPhone1=8346&idPhone2=8733). Both have the same ppi and resolution: 1080 x 1920 pixels, 16:9 ratio (~441 ppi density)
Comment: can you post required layout screen shot here


need an advice with orientation change iphone

Question: my problem might be simple to some of you but i can't find a solution. I have a method where a create my views automatically (text fields, labels and text views). It's like a registration form. The problem is that when i change the screen to landscape mode, i want to change the views width. To do that i used [self.view removeFromSuperview] and created the views again. The problem is that the views won't get recreated with the landscape width. I can't use IB to autosize the views at orientation change. The views are created in viewDidLoad and removed and recreated in - (void) adjustViewsForOrientation:(UIInterfaceOrientation)orientation {} I don't know why they don't get recreated after being removed. If there was another solution that you could share with me i would appreciate it.
Here's how i create the views:
-(void)createViews:(int)width
{
for(int i = 0; i < numberOfTextfields; i++) {
        textfieldPadding = textfieldPadding+40;//set some space between the text fields
        labelPadding = labelPadding+40;//set some space between the labels

        UITextField *field = [[UITextField alloc] initWithFrame:
                              CGRectMake(10,i*textfieldHeight+textfieldPadding+firstTextfieldHeight+10,width, textfieldHeight)];
        field.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        //field.backgroundColor= [UIColor cyanColor];
        field.placeholder = [labels objectAtIndex:i];
        field.borderStyle=UITextBorderStyleRoundedRect;
        field.returnKeyType = UIReturnKeyDone;
        [field addTarget:self action:@selector(doneButton:)

        forControlEvents:UIControlEventEditingDidEndOnExit];

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, i*labelHeight+firstLabelHeight+labelPadding-20, width, labelHeight)];

        label.text = [labels objectAtIndex:i];
        //label.backgroundColor = [UIColor brownColor];
        [scrollView addSubview:field];
        [scrollView addSubview:label];

        [textfields addObject:field];
        [labels addObject:label];
        [field release];
        [label release];
    }
}

Here's where i wanted to remove them and recreate them:
- (void) adjustViewsForOrientation:(UIInterfaceOrientation)orientation
{
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight)
    {
        [self.view removeFromSuperview];
        [self createViews:landscapeWidth];
    }
    else if(orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        [self.view removeFromSuperview];
        [self createViews:portraitWidth];
    }
}

Thanks in advance!
Comment: you dont need to recreate view right ? instead you can change frame accordingly when orientation changes....
Comment: can you post code?so that we can see what you are doing
Comment: check out the edits. I put some code.
Comment: you can add a method in your code where you will change frame of all subviews by getting their tag and changing..let -(void)createViews:(int)width called only once..you dont need recreate everytime. change only frame depending upon orientation .add a method newly to change orientatin alone .
Comment: Between your existing code and Narayanan's suggestions you'd be writing an awful lot of code you really don't need. Just let the `autoresizingMask` do it's job, it's what it's there for.
Answer: Instead of removing, resizing and then re-adding as you currently are why not just set the appropriate autoresizingMask (link) when you create the view initially?
UITextField *myTextField = [[UITextField alloc] initWithFrame:someRect];
// the following will automatically resize the width on orientation change
myTextField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[myView addSubview:myTextField];
[myTextField release];

Comment: It won't work because you are not allowing the masks to do their job as you are removing the views. **Seriously, you don't need to remove any views**. Delete the method `adjustViewsForOrientation` and then you should see the desired effect.
Comment: Sorry, it didn't worked because in the `adjustViewsForOrientation` i only removed the `removeFromSuperview` method but i was still creating the views again. I removed the two methods and it's working. Thanks a lot!


How the attribute field of a HttpServletRequest maps to a raw HTTP request?

Question: In Java, the attribute field of a HttpServletRequest object can be retrieved using the getAttribute method:
String myAttribute = request.getAttribute("[parameter name]");

Where the HttpServletRequest attribute data is stored in a raw HTTP request? Is it in the body of the request?
For example, I'm trying to create a raw GET HTTP request that will be sent to my servlet using some client program. My servlet.doGet() method would be something like this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
     String myAttribute = request.getAttribute("my.username");
     ...
}

Where should I put the 'my.username' data in the raw HTTP request so that the 'myAttribute' String receives the value "John Doe" after the attribution?
Answer: Just to be clear as I think @Jon's answer doesn't make it perfectly clear. The values for getAttribute and setAttribute on HttpServletRequest are not present on what is actually sent over the wire, they are server side only.
// only visible in this request and on the server
request.getAttribute("myAttribute");

// value of the User-Agent header sent by the client
request.getHeader("User-Agent");

// value of param1 either from the query string or form post body
request.getParameter("param1");

Answer: To add to @gid's answer, attributes are not present in any way in the HTTP request as it travels over the wire.  They are created (by your code) when processing the request.  A very common use is to have a server set (aka create) some attributes and then forward to a JSP that will make use of those attributes.  That is, an HTTP request arrives and is sent to a Servlet.  The Servlet attaches some attributes.  Additional server-side processing is done, eventually sending the page to a JSP, where the attributes are used.  The response is generated in the JSP.  The HTTP request and the HTTP response do not contain any attributes.  Attributes are 100% purely server-side information.
When a single given HTTP request has completed, the attributes become available for garbage collection (unless they are persisted in some other location, such as a session).  Attributes are only associated with a single request object.
Answer: I think what he is really asking is "how do I get parameteres into my program", not attributes. If that is the question, then send parameters in the GET request as part of the URL (after a question mark, http://myhost.com/myapp?name=joe&age=26) then retrieve them using request.getParameter("name") and request.getParameter("age"), or whatever you need.


Após reverter um merge de um repo para o fork, o git não permite fazer outro (already up-to-date)

Question: Boas galera!
Tenho pouca experiência com GIT (por isso, trabalho principalmente com o Github Desktop mais do que com a linha de comando), e hoje tive alguns problemas com um fork do repositório de um tema phpbb que eu venho trabalhando.
O primeiro deles na verdade começou há uns 16 dias. Tive dúvidas específicas de desenvolvimento do estilo e precisava compartilhar o código do repositório aqui no stack. O problema é que o fork é privado, presumo que seja pelo fato do repositório original também ser (já que eu não tenho conta premium no github). Então eu tentei duplicar o repositório em outro público, conforme esse tutorial do próprio site.
Porém eu não prestei atenção que após realizar esse procedimento os meus commits estavam indo parar no repositorio-clone, e não mais no original (o fork privado).
Eu só fui notar isso hoje, quando tentei fazer fazer um update to repositório pai para o fork (via github desktop) e ele não processava a ação. Depois de procurar vários tutoriais na internet eu acessei ambos os repositórios via web e notei a ausência de commits depois dessa data no fork e todos os meus commits no repo clone, incluindo o merge que o github desktop acusou como falho.
Consegui resolver esse problema repetindo o tutorial acima só que com os repositorios "invertidos": copiei do clone para o fork. Aparentemente o problema estava resolvido.
Eu então recomeçei a desenvolver e percebi que esse merge embaralhou várias coisas na estrutura do código, e percebi que precisaria reverter esse merge. Aí é que começou o pior problema (e o principal dessa pergunta).
Inicialmente tentei pelo Github Desktop, que exigiu que eu o fizesse via linha de comando (a explicação que eu encontrei foi pois esse tipo de merge tem 2 commits parent, e eu precisava referenciar qual eu queria reverter, no caso o último commit da minha fork) usando git revert -m. Aparentemente ele conseguiu reverter.
Porém, após conseguir reverter esse merge via esse tutorial, o github agora me insiste em dizer que o fork está atualizado com o repo original (tanto na linha de comando quanto no Github GUI), e com isso eu não consigo trazer as mudanças de novo do repo pai para o fork, para resolver corretamente os conflitos.
Esse é um comportamento normal do GIT/Github, é um bug e o principal: é possível sincronizar novamente ou seria necessário esperar um commit novo lá do repo pai, e se for necessário isso, ele vai pegar TODAS as diferenças de 16 dias pra cá ou vai pegar só as commits criadas depois da minha tentativa fracassada de merge?
Segue a imagem da network pelo site do github, a seta vermelha que eu coloquei aonde a linha azul (que representa o repo original) juntando-se à linha preta (meu fork) é o merge que eu dei e depois reverti (o próximo ponto após essa junção). Os pontos à frente destes são commits que eu tentei dar pra forçar um update, sem sucesso.

Um forte abraço a todos!
Answer: Consegui resolver o problema.
Tive que dar, na linha de comando, um git reset --hard <ultima commit antes do merge> e logo depois um git push --force para forçar a alteração no servidor.


Prove cancellation law for inverse function

Question: Trying to do an exercise from Analysis I, Tao.
edit: The paragraph introducting/defining inverse:
If $f$ is bijective, then for every $y \in Y$, there is exactly one $x$ such that $f(x)=y$ (there is at least one because of surjectivity, and at most one because of injectivity). This value of $x$ is denoted $f^{-1}(y)$; thus $f^{-1}$ is a function from $Y$ to $X$. We call $f^{-1}$ the inverse of $f$.
(The paragraph stands alone, but I assume $f:X \rightarrow Y$)
Exercise 3.3.6.
Let $f:X\rightarrow Y$ be a bijective function, and let $f^{-1}:Y \rightarrow X$ be its inverse. Verify the cancellation laws $f^{-1}(f(x))=x$ for all $x \in X$ and $f(f^{-1}(y))=y$ for all $y \in Y$. Conclude that $f^{-1}$ is also invertible, and has $f$ as its inverse (thus $(f^{-1})^{-1}=f$).
My attempt at a proof:
(1) Let $y \in Y$. Since $f$ is bijective, we have exactly one $x \in X$, denoted $f^{-1}(y)$, such that $y=f(x)=f(f^{-1}(y))$.
(2) Now let $x \in X$. Then $f(x)=y$ for exactly one $y \in Y$. Furthermore, since $f$ is bijective we have exactly one $x_0 \in X$, denoted $f^{-1}(y)$,  such that $y=f(x_0)$. Thus $x_0=x$, and so $x=f^{-1}(y)=f^{-1}(f(x))$. Observe that we have shown that for all $x \in X$, there is exactly one $ y \in Y$, namely $y=f(x)$, such that $f^{-1}(y)=x$, thus $f^{-1}$ is invertible and has $f$ as its inverse.
$\blacksquare$
I'm not sure if the proof is correct. I believe that (1) proved the cancellation law $y=f(f^{-1}(y))$.
I believe that (2) proved the cancellation law $x=f^{-1}(f(x))$ and also that $f^{-1}$ is onto and one to one, thus invertible.
I'm not sure if the last claim (that $f$ is the inverse of $f^{-1}$) was properly justified.
Comment: I must say that actually the exercise makes no sense to me. This because  in my optics - if $f^{-1}$ is defined to be the inverse of $f$ then **by definition** we have $f^{-1}(f(x))=x$ and $f(f^{-1}(y))=y$. How is "inverse function" defined in your material?
Comment: @Vera I added the paragraph where function inverse was discussed.
Answer: The definition of $f^{-1}$ in the first paragraph is $f(f^{-1}(y)) = y$.
If we let $y = f(x)$ we get $f(f^{-1}(f(x))) = f(x)$. Since $f$ is injective we
have $f^{-1}(f(x)) = x$.
To show that $f^{-1}$ is bijective, note that if $f^{-1}(a)= f^{-1}(b)$, then applying $f$ to both sides yields $a=b$, hence $f^{-1}$ is injective. Furthermore,
$f^{-1}(f(x)) = x$, hence $f^{-1}$ is surjective.
If $g$ is the inverse of $f^{-1}$, then, as in the first paragraph of the question, we have
$f^{-1}(g(y)) = y$, and applying $f$ to both sides yields $g(y) = f(y)$ and
so $(f^{-1})^{-1} = f$.


In Yosemite not able to generate the styles folder, I upload the project in a ubuntu test server, and it works

Question: I know this is a question related to permission. The only thing I have changed in my environment is that I upgrade to Yosemite, I check apache everything is working fine.
This question has been asked in here and in others. I checked every possible solution. Here is what I have done:

Change the permission in every possible way  even to 777 in local environment. It still gives the error
Change the apache user to my username and staff group, and make sure I have the set the right user and group
Clear the cache every time that I make a change
Use drush to flush the image as recommended in here

I have uploaded my site to a ubuntu server. It generates the files perfectly there without any trouble. Any ideas what it is happening in my local machine that it is not generating the styles folder and give an access denied error? I can upload files btw, it is just not able to create the folder styles and its files.
Answer: Probably not a permissions problem: the default php GD library on yosemite comes without png support, so drupal can't generate png images (like the default sample.png). You can very easily install another version of php.
Comment: Ah yes, the "run shell scripts over the internet -- I swear we won't do anything bad to your PC" ... while this is a valid answer, I believe Drupal has an error message in the Status Page if PNG support is not found. If an end-user can't figure this out by themselves -- why expose them to such a dangerous tool as this `install.sh` file linked in your answer?
Comment: I could not find it any message. However, after installing another version of php it worked for me...I did not check the link my bad, tenken. :( I requested the link to be removed.
Answer: Looks like a PHP issue.
I use Acquia Dev Desktop for my local environment, and things were working fine until the upgrade to Mac OS X 10.10.2 yesterday, when similar things started occurring.
From what it looks like, there were system level changes that affect local MySQL setups (my Apache runs fine). PHP version seems to be irrelevant (have tried three).
For the moment, it looks like Guardian's post above to run Vagrant (a Linux VM running on your system) may be your best bet.
Answer: Yosemite is no fun when it comes to your local dev environment.
I have had a lot of similar issues when upgrading to Yosemite.
The first thing that comes to mind here is to check the PHP version on your ubuntu server and your local dev environment.
That might also be what is causing your problem here.
Another workaround is to give Vagrant a try.
You can find all the info you need on Vagrant on https://www.vagrantup.com/
Comment: ??? I had exactly one problem when upgrading to Yosemite (pgsql related, easily fixed). Have people not heard of Homebrew? :)
Comment: I love homebrew but got an error Warning: You have an outdated version of /usr/bin/install_name_tool installed. I just have to accept that this was not my weekend for upgrading yosemite. I guess I have to reinstall everything.
Answer: If the problem is your local environment. I would recommend to used a VM with Lazy Dubuntu. If you still want to use Yosemite for your local environment you should try MAMP or Acquia Dev Desktop.
Answer: Run MAMP or AMPPS, http://www.ampps.com or install another PHP, MAMP is nice since you can switch PHP versions anytime and set per project etc. I'd only run a VM if I were working in a team and we all had to run the same environment.


Between any 2 distinct real numbers, does there exist a real number such that its decimal expansion terminates in base 10?

Question: Between any 2 distinct real numbers, does there exist a real number such that its decimal expansion terminates in base 10?
Also, does this result hold in any natural number base? Thank you.
Comment: This isn't difficult to prove, however ... what have you tried?
Comment: A real number has a decimal expansion that terminates in base $10$ if and only if it is a rational number and its denominator, when written in least terms, is of the form $2^a5^b$ with $a,b$ natural numbers. For base $b$, the expansion terminates if and only if all prime factors of the denominator divide $b$.
Comment: I was thinking of taking of taking $a,b\in \mathbb{R}, 0 < a <b$ and considering the sequence of finite decimal expansions for $a$ and $b$, $a_n$ and $b_n$ respectively, which each converge to $a$ and $b$. Since $a \neq b$, I think that $a_n$ and $b_n$ need to disagree at some finite position $i$. $a_i$ should then be the desired construction.
Comment: @Brothersquid You should have written that in your question. My answer below is essentially a waste of time if you knew that already.
Comment: Well, I appreciated the input nonetheless.
Answer: Of course. Imagine being given two infinite decimals (or any base $b$ expansion) and trying to prove that one is bigger than the other.

First you look at the digits in the most significant position. If one is bigger than the other (where missing digits count as leading 0s), then that's the bigger number.
Otherwise, you look at the second most significant digits. Are they different? If so, you have a bigger number. If not...
continue forever. If the numbers are different, you will eventually find a position where they differ.

If you understand this procedure, it is obvious that there is a terminating decimal that is at most as big as the bigger number. Can you prove the rest?


How to nest imagemagick commands in node.js gm library?

Question: Using Imagemagick in node.js through the gm library (https://github.com/aheckmann/gm):
var gm = require('gm').subClass({ imageMagick: true });

I am able to flatten pictures, like this:
convert img1.png img2.png img3.png -flatten out.png

with this js code:
gm().command("convert").in("img1.png").in("img2.png").in("img3.png").in("-flatten").toBuffer('PNG' ...

but now I want to tint one of the images, like this:
convert img1.png \( img2.png -fill green -colorize 50% \) img3.png -flatten out.png

but I had not succeed, I tried:
.in("(img2.png -fill green -colorize 50% )")
.in("\(img2.png -fill green -colorize 50% \)")

what is the proper way to pass nested commands?
Comment: GraphicsMagick is not the same as ImageMagick. They separated and went there separate ways a long time ago. Sorry, I do not know GraphicsMagick or Node.js
Comment: thks @fmw42! I just edited the question to highlight that the javascript's gm library is actually using ImageMagic.
Answer: I really was not able to solve the issue with gm, as far as understood checking the doc and source code, it is not possible in a single step with the current status of the library. then I found the Jimp library: it is pure javascript and even less featured, it was quite straightforward to implement the desired behavior. work well with node.js in AWS Lambda.  applying tint in one buffer and then mixing all together looks like this:
//each skin_buffer[attr] is a Jimp object build like this:
     Jimp.read(data.Body, function (err, image) {
        skin[type] = image;
        cb(err);
      });

//this is how the tint effect is applied in Jimp:
  skin_buffers.hair.color([
    { apply: 'mix', params: [ '#00D', 50 ] }
  ]);
//.. and this is the composite step. skin is just another jimp object
  skin.composite(skin_buffers.hair, 0, 0);
  skin.composite(skin_buffers.legs, 0, 0);
  skin.composite(skin_buffers.shoes, 0, 0);
  skin.composite(skin_buffers.torso, 0, 0);
  skin.composite(skin_buffers.edges, 0, 0);
  skin.composite(skin_buffers.face, 0, 0);
  skin.getBuffer( Jimp.MIME_PNG, function(err, buffer){
    cb(err, buffer);
  });

note: jimp.mix is too slow! for a single 1024x1024 image took 13 seconds!:
[skins_create]got all the assets!
TIMER: got assets from s3: 3.193 sg
[skins_create]["skin","face","hair","torso","legs","shoes","edges"]
 - SUBTIMER : jimp.mix: 13.002
 - SUBTIMER : jimp.composite hair: 0.14
 - SUBTIMER : jimp.composite legs: 0.145
 - SUBTIMER : jimp.composite shoes: 0.15
 - SUBTIMER : jimp.composite torso: 0.147
 - SUBTIMER : jimp.composite face: 0.146
 - SUBTIMER : jimp.get buffer: 0.45
TIMER: processed buffers: 14.185 sg
TIMER: stored in s3: 4.21 sg

Comment: I was able to implement a faster version of Jimp.mix.. the issue is that Jimp uses callbacks per pixel, and create objects within each callback, plus calling yet more callbacks from the tinycolor2 library.. just creating a plain function, by copying code of tinycolor2 and jimp, with no callbacks, it speed up to 0.03 sg, instead of 14 :)


PHP Object access with class constant

Question: Is it possible in PHP to access a member of an object where the name of the member is specified by a class constant?
Consider this example:
class X{
    const foo = "abc";
}

class Y{
    public $abc;
}

$y = new Y();

$y->X::foo = 23; //This does not work

The parser doesn't accept the last line but this is what I want. I want to access the field with the name stored in the class constant X::foo. Is there a syntax to achieve that?
Comment: @MarkusMalkusch as variable variables have been part of PHP since god knows how long they're supported just fine by major IDEs like PhpStorm.
Answer: Use variable variables, either via a temp or directly:
$name = X::foo;          // Via temp var
$y->$name = 23;          // Access the member by the string's content
var_dump($y->{X::foo});  // Dumps 23

Working sample here.
Answer: You should write your code like this
$y->{X::foo} = 23;

Hope it helps

PHP Object access with class constant


Creating UIView in xib, interface builder and without using UIViewController to attach it to the window

Question: I'm new to views and view controllers.....i was wondering if there is a way to create a view(UIView) using xib (i.e, I have all three files .m, .h and .xib of the UIView) and I attach it to the window like [window addSubview:myView];??
all the examples I have seen till now have used UIViewController to load the view using xib.
Answer: Not sure why you want to do this, but here is what you can do:
In -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions from AppDelegate class, load your custom view
CustomView *view = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:nil options:nil] objectAtIndex:0];

Then add view to the window
[self.window addSubview:view];

That's it.
Comment: It works and i get the ObjectAtIndex thing.....but why does owner set to nil does the job? shoudnt the owner be the view.m?
Comment: if you set view's 'custom class' from the xib, then 'loadNibNamed' doesn't require a owner, so you can pass nil.


Problem dealing with two correlated Random Variables

Question: Here is a problem and my solution to it. I ran some simulations in R, and I
concluded that I am wrong. I am hoping that somebody can tell me where I
went wrong.
Thanks, Bob
Problem:
Let $X$ and $Y$ be two independent normally distributed random variables
with $u = 0$ and $\sigma = 1$. Let $Z = \frac{1}{2}X + \frac{1}{2}Y$. What is
the correlation between $X$ and $Z$?
Answer:
\begin{eqnarray*}
\rho_{xz} &=& \frac{cov(X,Z)}{var(X) var(Z)}\\
cov(X,Z) &=& \frac{1}{2}cov(X,X) + \frac{1}{2}cov(X,Y) \\
cov(X,X) &=& 1 \\
cov(X,Y) &=& 0 \\
cov(X,Z) &=& \frac{1}{2}(1) + \frac{1}{2}(0) = \frac{1}{2} \\
\rho_{xz} &=& \frac{\frac{1}{2}}{1(1)}\\
\rho_{xz} &=& \frac{1}{2} \\
\end{eqnarray*}
Answer: The error is that the variance of $Z$ is not $1$.  This is because if $Z = (X+Y)/2$, the variance of $Z$ is a quarter of the sum of the variances of $X$ and $Y$; i.e., $\operatorname{Var}[Z] = 2/4 = 1/2$.  Now, the other problem is that the correlation is not defined as you have it:  it is $$\rho_{XZ} = \frac{\operatorname{Cov}[X,Z]}{\sqrt{\operatorname{Var}[X]}\sqrt{\operatorname{Var}[Z]}}.$$  Intuitively, you should know that the variance of a sample mean of IID variables will be less than the variance of any individual observation.


How to integrate aws device farm into Java code like browserstack

Question: I want integrate aws device farm into Java code like browserstack with webdriver .
Answer: I'm not so familiar with browser stack but with device farm you should need to provide the basic capabilities such as device name or app as they're entered on our behalf.
There are some sample web app test packages for python and Java here.
https://github.com/aws-samples?utf8=✓&q=Device+farm+web&type=&language=
Could you let me know of these help answer the question?
Comment: Thanks for answer but I want to automate manual steps like we upload apk file and zip dependency in aws account project. I want to do these steps through Java code. Is there any support provideto do this?
Comment: Yes, you can use the Java sdk to upload and schedule the tests. For examples of what that would look like you can follow the Jenkins plugin example here
https://github.com/awslabs/AWS-device-farm-jenkins-plugin


What is wrong with my proof of Law of Large Numbers?

Question: Need help in deriving variance for LLN, but am getting something wrong here, can you help point out where I'm going wrong?
Thanks a ton!
For i.i.d random variables $X_1,X_2,\ldots,X_n$ with mean $\mu$ and variance $\sigma^2$.
Let $X=\frac{1}{n}\displaystyle\sum_{i=1}^nX_i$ and it's mean be $\mu$(from LLN) then
\begin{align}
\operatorname{var}(X)& =E[(X-\mu)^2]\\[10pt]
& =E[X^2]-\mu^2\\[10pt]
& =E\left[\left(\frac{1}{n}\sum_{i=1}^nX_i\right)^2\right]-\mu^2\\[10pt]
& =E\left[\frac{1}{n^2} \left( \sum_{i=1}^nX_i\right)^2\right]-\mu^2\\[10pt]
& =\frac{1}{n^2}E\left[\left(\sum_{i=1}^nX_i\right)^2\right]-\mu^2\\[10pt]
& =\frac{1}{n^2}E\left[\sum_{i=1}^nX_i^2+\sum_{i,j=1,i\neq j}^{i,j=n} X_iX_j\right]-\mu^2\\[10pt]
& =\frac{1}{n^2}\left(\sum_{i=1}^nE[X_i^2]+\sum_{i,j=1,i\neq j}^{i,j=n}E[X_iX_j]\right)-\mu^2\\[10pt]
& =\frac{1}{n^2}(n\sigma^2+(n^2-n)\mu^2-n^2\mu^2)\\[10pt]
& =\frac{1}{n^2}(n\sigma^2-n\mu^2)\\[10pt]
& =\frac{\sigma^2-\mu^2}{n}
\end{align}
Comment: How is this a proof of LLN???
Answer: $$E[X_i^2]\ne \sigma^2$$
But should be
$$E[X_i^2] = \sigma^2+\mu^2$$
Comment: ah! right argh, thanks!
Answer: You say "from LLN", but you are not using LLN anywhere.
Moreover, it's much easier to do this:
$$
\text{Var}\left(\frac{1}{n}\sum X_{i}\right)=\frac{1}{n^{2}}\sum\text{Var}\left(X_{i}\right)=\frac{n\sigma^{2}}{n^{2}}=\frac{\sigma^{2}}{n}.
$$
Comment: No need to apologize, I was just clarifying for your benefit :-)
Comment: Yes, agree but I went down that rabbit hole and something wasn't making sense. I used "from LLN" for assuming mean of X to be the same as mean of any $X_i$
Comment: The LLN is about the limit of averaged sums as $n\rightarrow \infty$. There are no limits in your question. All you need to assume is that $X_1, X_2, \ldots$ are i.i.d. with finite variance $\sigma^2$.
Comment: Now I see where I was wrong in quoting LLN, I never took $n\to\infty$, I should've just stated it as sum of i.i.d random variables. Apologies, I came across this while heading to LLN.


Dual vector bundle in differential geometry

Question: I am a graduate student in control theory. The entity "vector bundle" appears oftentimes. For instance, the tangent vector bundle $TM$ is the set of local tangent vector spaces at coordinate $x$ of a certain manifold $M$. It utilizes the "vector bundle" $\xi$ with total manifold $E_\xi$ (belonging to which I do not grasp) in the case of a fiber $\xi_p$, for coordinate $p \in M$ and a section $\Gamma(\xi)$, as the name recalls, the applications around the neighborhood of certain coordinate $p$ belonging to fiber $\xi_p$.
I do not comprehend, however, what a dual vector bundle means. The article available on here on page 140, says the following, in german:
Let application $X \in \Gamma(TM)$ and $s \in \Gamma_p(\xi)$. Then, for each vector $v \in T_p M$, there is an element $\nabla_v s \in \xi$ unequivocally defined by equality $\nabla_v s := (\nabla_X s)_p$, for $X_p = v$. Let $\xi^*$ be a $\xi$ dual vector bundle, so there is for each $\omega \in \Gamma_p(\xi^*)$ and each $v \in T_p M$ exactly one element $\nabla_v \omega \in \xi_p^*$ with:
$v \cdot \langle \omega, s \rangle = \langle \nabla_v \omega, s \rangle + \langle \omega, \nabla_v s \rangle$.
Comment: The dual bundle $\xi^*$ is the bundle where for each $p \in M$, the fiber $\xi^*_p$ is the dual vector space (in the usual linear algebra sense) to $\xi_p$.
Answer: The total manifold of the bundle is just the underlying manifold to the vector bundle, forgetting the projection and the base.
If you assume for a second that your vector bundle $\xi$ as a sub-bundle of a trivial bundle $U\times M$ the total manifold of $\xi$ is just
$$\{ (v,p) \in U \times M \mid v \in \xi_p \}$$
The dual bundle to $\xi$ is the vector bundle deduced from $\xi$ by replacing each fibre $\xi_p$ by its dual $\xi'_p$, the vector space of linear forms on $\xi_p$. Other canonical constructions made "fibre by fibre" yield more fibre bundles: taking cartesian products, symmetric or exterior powers, or looking for the zero hyperplan of a linear form, for instance.
A difficulty to begin in this topic is that the "synthetic" approach used in the article summons a great many different notions. All of them are really needed, and in the end, it is much easier than the "coordinates" approach, since it allows to reason geometrically rather than to reduce everything to a coordinate computation.  If that helps, it is useful to translate "in coordinates" for a while — and that is most of the time mandatory to work out examples.
Suggested reads: Michael Spivak, Jacques Lafontaine (Introduction to differential Manifolds), but really speak with your professor before spending a long time in the books, so that they can help you to make an appropriate use of them, especially regarding the balance between understanding the vocabulary of differential geometry and bee-lining to the topic you are actually interested in.
Comment: I thank deerly (since you help me avoid bee-lining) for the explanation. I was advised to read Spivak as you mention, complementar to Burke and Manfredo Perdigão. If you are literate in german, I recommend the article.
Answer: In the standard basis in $\mathbb{R}^n$, we have $\partial_i=\frac{\partial}{\partial x^i}$ (ith directional derivative/ coordinate vector), dually we have $\partial^i = dx^i$ (ith component function/ increment). They interact via natural pairing:
$$\partial^i(\partial_j) = \delta^i_j = \bigg\{\begin{matrix}1&&\text{ if i=j}\\0&&\text{otherwise}\end{matrix}.$$

For example:
Let $v = \partial_1+2\partial_2$ and suppose $\omega = -\partial^1+4\partial^2.$
Then:
$$\omega(v) = (-\partial^1+4\partial^2)(\partial_1+2\partial_2) = -\partial^1\partial_1 -2\partial^1\partial_2 +4\partial^2\partial_1+8\partial^2\partial_2 = -1 - 0 + 0 + 8 = 7.$$

Now, suppose $X\in \Gamma(TM)$ (i.e. $X$ is a vector field) and $\omega\in \Gamma(T^*M)$ (i.e. $\omega$ is a dual vector field), then at each point, $p\in M$ we have a chart $\varphi:U_p\to \mathbb{R}^n$ such that the pullback of $\omega_p$ through the inverse and the pushforward of $X_p$ interact as in the above example (down in $\mathbb{R}^n$):
$$(\varphi^{-1})^*(\omega_p)\bigg(\varphi_*(X_p)\bigg).$$
Alternatively, if we induce coordinate frames on the bundles (or otherwise just have them from context), we may write out the interaction over the manifold itself: $\omega_p(X_p)$ and evaluate according to the kronecker-delta expression ($\delta^i_j$) between the frames.

This was in attempt to illustrate how duality works in basic differential geometry (involving tangent and cotangent vector bundles). The idea should be roughly the same for other vector bundles and their duals. I hope this edit helps!
Comment: It seems an advanced topic, which I may stumble into later on. The concept presented as chosen answer suffices for me. I do not comprehend, however, what does pullback means. I will post another question.
Comment: The $\Gamma(\cdot)$ stands for "sections of ($\cdot$)", where the variable is a vector bundle. Sections are fields essentially. They are poorly named imo. You take a point on the manifold and associate an object of type specified by the bundle. So for example: $"X:p\mapsto X_p"$ and $"\omega: p\mapsto \omega_p$" only technically speaking the pair is kept in the image: $p\mapsto (p,v)$. This makes the section/projection pair one sided inverses ($\sigma \circ \pi = Id_{VB}$). John Lee's "Introduction to Smooth Manifolds" is a good text for this.
Comment: The book you mention is on its way to my home at this moment. Mind-reading is a richly named term for this phenomenon. According to the article from Dombrovski on original post, Sections are applications (maps) on elements of a vector bundle, oftentimes the tangent bundle.
Comment: Yes, at one point it's a matter of convention between a speaker and their audience. Since it's a beginner's questions I wanted to explain the terminology "section" and how "field" collides with other important terminology, especially in a context where the two notions are used together.
Comment: You prefer a physics explanation, which in my and Grothendieck's opinion is careless and irresponsible to your reader's comprehension. I think you should read the answer I marked as the proper one.
Comment: This is what duality means in the linear algebraic sense at the level developed in charts. This is actually used to evaluate tensor and tensor field components. The excerpt includes covariant derivative identities, which are not necessary for understanding duality?
Comment: I do thank you for answer improvement. I understand $\Gamma(\cdot)$ as the applications on certain vector bundle. You utilize, for instance, $X$ and $\omega$. What is your understanding about this geometrical concept?
Comment: @KevinS The $\Gamma(X)$ denotes *global sections* of $X$, it is also customary to denote local sections over an open space $U$ with $\Gamma(X,U)$. When $U$ is small enough so that the restriction of $X$ above $U$  is trivial, sections above $U$ are actually sections (or cross-sections) of the trivialisation. There is at least two reasons why they don't call them fields: First is that the name is already taken and used in a context where bundles and sections are pervasive (algebraic geometry). Second is that sections are not only for vector bundles but also for sheaves, fields are very remote.
Comment: @MichaëlLeBarbier $\v{C}$ontext should specify algebraic field vs. physical. It's a matter of opinion at this point, write whatever you feel comfortable with!


Derive the bias and MSE of the estimator $\hat{\beta}$

Question: Let $Y_1, Y_2, \ldots, Y_n$ denote a random sample of size $n$ from a population whose density is given by
$$
f(y)=
\begin{cases}
      3\beta^3 y^{-4} & \beta \leq y \\
      0 & \text{elsewhere}
   \end{cases}
$$
where $\beta > 0$ is unknown. (This is a Pareto distribution) Consider the estimator $\hat{\beta} = \min(Y_1, Y_2, \ldots, Y_n)$.
a. Derive the bias of the estimator $\hat{\beta}$.
b. Derive MSE($\hat{\beta}$).
For part a
Since this is an estimator that is dealing with random variables, and I only need the minimum, then I can represent this as ordered statistics. Namely, $\hat{\beta} = Y_{(1)}$.
Using the formula for ordered statistics, the pdf is:
$$
g_{(1)}(Y_{(1)}) = n(1-F(y))^{n-1}f(y)
$$
My first question arises here, I am not sure how I am supposed to find $F(y)$ (and I am assuming that $f(y)$ is the given distribution above).
Checking against the solution, I know that the pdf is supposed to be:
$$
g_{(1)}(Y_{(1)}) = 3n\beta^{3n}y^{(-3n-1)}
$$
After solving getting the pdf of $Y_{(1)}$, I can then use it in the bias formula.
$$
Bias(\hat{\beta}) = E[\hat{\beta}] - \beta \\
Bias(\hat{\beta}) = E[3n\beta^{3n}y^{(-3n-1)}] - \beta
$$
My second question arises here. I'm not really sure how I am supposed to find the expectation. Namely, I don't know how I am supposed to treat the $y$ variable. I think that the $\beta$ variable is supposed to be treated the same way as a random variable, and that $n$ is supposed to be treated as a constant.
After solving for the expectation, I should be able to get the Bias.
For part b
$$
MSE(\hat{\beta}) = Bias(\hat{\beta})^2 + Var(\hat{\beta})
$$
The bias part of this formula should follow from part a. This would leave just the variance to calculate. I would expect to use the variance formula:
$$
Var(\hat{\beta}) = E[\hat{\beta}^2] - E[\hat{\beta}]^2
$$
And I would also expect that both expectations in this formula could be calculated using the same methods in part a. Is this correct?
Answer: I got this question recently. This question is from Mathematical Statistics - Wackerly - Exercise 8.1.

Let $Y_{1}, Y_{2}, \ldots, Y_{n}$ denote a random sample of size $n$ from a population whose density is given by
$$
f(y)=\left\{\begin{array}{ll}
3 \beta^{3} y^{-4} & , \quad \beta \leq y \\
0 & , \text { en cualquier otro caso }
\end{array}\right.
$$
where $\beta>0$ is unknown. (This is one of the Pareto distributions introduced in Exercise 6.18.) Consider the estimator $\hat{\beta}=\min \left(Y_{1}, Y_{2}, \ldots, Y_{n}\right)$

This my approach:
a.
Considering distribution function from Pareto distribution we have:
$$F(y)=\begin{cases}0,& y<\beta\\1-\left(\frac{\beta}{y}\right)^\alpha, & y\geq \beta \end{cases}$$
Which density function (derivative) is:
$$f(y)=\begin{cases}0,& y<\beta\\
\alpha \beta ^\alpha y^{-(\alpha +1)}, & y\geq \beta \end{cases}$$
We proceed to calculate $Y_{(1)}$ density function (with $\alpha=3$, our problem):
\begin{align}
\begin{split}
    g_{(1)}(y)&=n\left[1-F(y)\right]^{n-1}f(y) \\
              &=n\left[1-\left( 1-\left(\frac{\beta}{y}\right)^3 \right)\right]^{n-1} 3 \beta ^3 y^{-(3+1)}\\
              &= n\left[\beta^{3(n-1)}y^{-3(n-1)}\right]3 \beta ^3 y^{-(4)}\\
              &= 3n\beta^{3n}y^{-(3n+1)}, \qquad y\geq \beta
\end{split}
\end{align}
Now, we'll check this definition:

Let $\hat{\theta}$ be a point estimator for a parameter $\theta$. Then $\hat{\theta}$ is an unbiased estimator if $E(\hat{\theta})=\theta$. If $E(\hat{\theta})\neq \theta$, $\hat{\theta}$ is biased.

\begin{align*}
    E(Y_{(1)}) &= \int_{\infty}^{\infty} y f_{(1)}(y) \ d y\\
               &= \int_{\beta}^{\infty} y 3n\beta^{3n}y^{-(3n+1)} \ dy\\
               &= 3n\beta^{3n}\lim_{h\to \infty}\int_{\beta}^{h} y^{-3n} \ dy\\
               &= 3n\beta^{3n}\lim_{h\to \infty}\left[\frac{y^{-3n+1}}{-3n+1}\right]_\beta^h\\
               &= 3n\beta^{3n}\left[-\frac{\beta^{-3n+1}}{-3n+1}\right]\\
               &= \left(\frac{3n}{3n-1}\right)\beta
\end{align*}
So we know, by definition, $\hat{\theta}$ is a biased estimator. Now we were asked to find the bias, which is easily to calculate considering this definition:

$$B(\hat{\theta}) = E(\hat{\theta})-\theta$$

Therefore:
\begin{align*}
    B(\hat{\beta})&=E(\hat{\beta})-\beta\\
                   &= \left(\frac{3n}{3n-1}\right)\beta - \beta \\
                   &= \left(\frac{1}{3n-1}\right)
\end{align*}
b.
We proceed to calculate $E(\hat{\beta}^2)$ (which later will be necessary):
\begin{align*}
E(\hat{\beta}^2)= E(Y_{(1)}^2) &= \int_{\infty}^{\infty} y^2 f_{(1)}(y) \ d y\\
               &= \int_{\beta}^{\infty} y^2 3n\beta^{3n}y^{-(3n+1)} \ dy\\
               &= 3n\beta^{3n}\lim_{h\to \infty}\int_{\beta}^{h} y^{-3n+1} \ dy\\
               &= 3n\beta^{3n}\lim_{h\to \infty}\left[\frac{y^{-3n+2}}{-3n+2}\right]_\beta^h\\
               &= 3n\beta^{3n}\left[-\frac{\beta^{-3n+2}}{-3n+2}\right]\\
               &= \left(\frac{3n}{3n-2}\right)\beta^2
\end{align*}
Finally, we have:
\begin{align*}
    MSE(\hat{\beta})&=E[(\hat{\beta}-\beta)^2]\\
                    &= E[\hat{\beta}^2-2\hat{\beta}\beta +\beta^2]\\
                    &= E(\hat{\beta}^2)-2\beta E(\hat{\beta})+ E(\beta^2)\\
                    &= E(\hat{\beta}^2)-2\beta E(\hat{\beta})+ \beta^2\\
                    &= \left(\frac{3n}{3n-2}\right)\beta^2 -2\beta^2\left(\frac{3n}{3n-1}\right) +\beta^2\\
                    &= \left(\frac{3n}{3n-2}\right)\beta^2 -\left(\frac{3n}{3n-1}\right)\beta^2\\
                    &= \left(\frac{3n}{3n-2}-\frac{3n}{3n-1}\right)\beta^2\\
                    &= \left(\frac{2}{(3n-1)(3n-2)}\right)\beta^2
\end{align*}
A nicest version of this problem (in Spanish) is at this repository on Github: Parcial 3 - Estadística Matemática.


go to next field automatically html5 form

Question: I am using following html5 form.
<form>
 <input type="text" name="orderno" />
 <input name="picture" id="img" type="file" accept="image/*" capture="camera" />
 <input class="btn-success" type="submit" name="submit" value="Upload" />
</form>

When I open this page in my mobile phone, I want that When I fill first input text, there should be a button called "NEXT" in my keyboard but currently it shows "GO" button directly. Any Help please?
javascript function document.getElementById('img').focus(); is not opening camera automatically.
I want the facility to launch camera on phone automatically when clicked "NEXT" or "GO" in keyboard.
Comment: Possible duplicate of [HTML: Why does Android browser show "Go" instead of "Next" in keyboard?](http://stackoverflow.com/questions/6545086/html-why-does-android-browser-show-go-instead-of-next-in-keyboard)
Comment: Edited my question with specific requirement. Please check out now.
Comment: So is your question how to get Next instead of Go, or is your question how to launch the camera after Next or Go is clicked?
Answer: For Security concerns, most browsers do not allow direct access to file uploader or image capture trigger. User has to click on the corresponding field to upload file or capture photograph. you can define focus after each has been addressed.
Answer: In first input have tabindex='1' in second input have tabindex='2' and so on.


Perform AFHTTPClient request, in background, with NSOperationQueue chronologically

Question: I have an HTTPClient request as follows :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:urlStringMain]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        //parameters
                        nil];

[self beginBackgroundUpdateTask];

[httpClient postPath:postPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

    //id results = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONWritingPrettyPrinted error:nil];

    //completion code

    [self endBackgroundUpdateTask];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    //failure code

}];
[httpClient release];

The background task is executed in :
- (void) beginBackgroundUpdateTask{

[operationQueue addOperationWithBlock:^{

    NSLog(@"started upload process as a background job");

    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}];

}

And ended in :
- (void) endBackgroundUpdateTask{

NSLog(@"complete upload process as a background job");

[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

where self.backgroundUpdateTask is a UIBackgroundTaskIdentifier object, and operationQueue is an object of NSOperationQueue (public member), initialized in viewDidLoad:
operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];

Now what I want to do is, perform these requests chronologically, in the background, such that pushing/popping from the viewController does not affect the request. It should also not be affected if the application goes into background. At times I post text, and at other times I post an image. Now, images take longer to upload, than text so if subsequent requests of text and images are made, texts are posted first, and images later. This breaks the chronology of the tasks, hence I wanted to use the NSOperationQueue. But being new to operation queues, I cannot seem to make it work. The chronology is still not being respected. How do I perform the task in the way I want to.
PS. Also, as you can see in the code, i have added [self endBackgroundUpdateTask] in both, the completion block of the httpClient request, and the beginBackgroundUpdateTask method. Now i understand this is not good. Where exactly should the endBackgroundUpdateTask method be called ?
Thank you.
Answer: The HTTPClient can handle the background task for you if you ask it to, simply set the appropriate flag (you need to create the operation and call setShouldExecuteAsBackgroundTaskWithExpirationHandler:).
Rather than change how the uploads operate, keep it simple. Send a date with the upload and use that to maintain your order information on the server.

If you really must execute your operations serially then you can get the operationQueue from the client and set it to only execute a single operation at a time.
In either case you shouldn't need to create your own operation queue.
Comment: That will not help. The server uses it's own clock to assign a timestamp to all posts.


Saving External Resources (large file size)

Question: I have more than 1000 pictures and audio files, which are about 30G in total.  If I put them in Xcode resources, the app will be very large.  Where can I put them? And how can I get them in Xcode?
Comment: 30G? I guess you could save them in photo library and access them from there, same with audio files from music library. Of course you'd have to synch all these from iTunes or something. Couldn't you access them dynamically from web?
Answer: For such a large amount of media, most optimal compression is something you can't overlook.
Some ideas:

use jpegs with maximum acceptable compression that works best for the app
cut unnecessary resolution (ex. max 640x960 for retina devices)
compress audio as much as you can (cut sample rate, use different format, etc)
store some portion on a web-server, bundle some media with the app, so it can be started quickly, then have user download images/sounds in the background, on a per-screen basis...


Uncaught TypeError: Cannot read property 'format' of undefined

Question: I am trying to format numbers in chartjs chart. I am getting this error on my console and the numbers are not visible on the chart

Uncaught TypeError: Cannot read property 'format' of undefined

You can refer the fiddle here. Line 74 on the fiddle
for (var i = 0; i < firstDataSet.data.length; i++) {
                            var firstModel = firstDataSet._meta[Object.keys(firstDataSet._meta)[0]].data[i]._model;
                            var secondModel = secondDataSet._meta[Object.keys(secondDataSet._meta)[0]].data[i]._model;
                            var thirdModel = thirdDataSet._meta[Object.keys(thirdDataSet._meta)[0]].data[i]._model;
                            var fourthModel = fourthDataSet._meta[Object.keys(fourthDataSet._meta)[0]].data[i]._model;
                            var total = firstDataSet.data[i] + secondDataSet.data[i];
                            var total1 = thirdDataSet.data[i] + fourthDataSet.data[i];
   // Line below is causing the error

 ctx.fillText(formatter.format(Number(firstDataSet.data[i])) + " ", firstModel.x, firstModel.y + 20);

                            ctx.fillText((firstDataSet.data[i]) , firstModel.x, firstModel.y + 20);
                            ctx.fillText((secondDataSet.data[i] ) , secondModel.x, secondModel.y + 20);
                            ctx.fillText(total , secondModel.x, secondModel.y - 20);
                            ctx.fillText((thirdDataSet.data[i]) , thirdModel.x, thirdModel.y + 20);
                            ctx.fillText((fourthDataSet.data[i] ) , fourthModel.x, fourthModel.y + 20);
                            ctx.fillText(total1 , fourthModel.x, fourthModel.y - 20);
                            /*if (firstDataSet.data[i] >= secondDataSet.data[i]) {
                                ctx.fillText((firstDataSet.data[i] * 100 / total).toFixed(2) + '%', firstModel.x, firstModel.y + 30);
                            } else {
                                ctx.fillText((secondDataSet.data[i] * 100 / total).toFixed(2) + '%', secondModel.x, secondModel.y + 30);
                            }
                            */
                        }

var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  // the default value for minimumFractionDigits depends on the currency
  // and is usually already 2
});

Comment: Declare the `formatter` before `window.myBar = new Chart(ctx...`. Like so: [fiddle](https://jsfiddle.net/6j3L6p8s/)
Comment: Oh great.. that did it. If you can add it as an answer i can accept it
Answer: You have to declare the formatter before calling the new Chart constructor function, otherwise it will be undefined inside the options you are passing as the second parameter of new Chart.
var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  // the default value for minimumFractionDigits depends on the currency
  // and is usually already 2
});

window.myBar = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});


Linux router share internet between eth2 to eth3

Question: I am not a networking guy, so apologies in advance.
I have a small Linux (Ubuntu) box with 2 ethernet ports.

eth2 is connected to a cable modem that gives it a 192.168.1.x address + internet connection
eth3 I plug directly into, I was able to install isc-dhcp-server and configure it (config below). I am able to plugin a Windows laptop and get an IP in the 10.0.0.x range as configured.

How the heck do I get eth3 seeing the internet (like eth2 already does)? I'd like to be able to plugin a Windows laptop or an access point to eth3 and have it get an internet connection automatically.
I've tried pinging from eth3 and eth2 out to google.com and the results:
ping -I **eth3** google.com => destination host unreachable

ping -I **eth2** google.com => works!

Here is my config:
nano -w /etc/dhcp/dhcpd.conf
ddns-updates off;
option domain-name "example.local";
option domain-name-servers 18.104.22.168;
authoritative;

subnet 10.0.0.0 netmask 255.255.255.0 {
        interface eth3;
        default-lease-time 6000;
        max-lease-time 7200;
        range 10.0.0.100 10.0.0.200;
        option subnet-mask 255.255.255.0;
        option routers 10.0.0.254;
        option broadcast-address 10.0.0.255;
        option domain-name-servers 126.96.36.199;
}

nano -w /etc/default/isc-dhcp-server
INTERFACES="eth3"

nano -w /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

auto eth3
iface eth3 inet static
  address 10.0.0.200
  gateway 10.0.0.1
  netmask 255.255.255.0
  dns-nameservers 188.8.131.52

I have tried port forwarding:
sudo sysctl net/ipv4/ip_forward=1

Also tried bridging, but it kicks me out of the box as soon as I hit enter:
brctl addbr br0
brctl addif br0 eth2 eth3

Any advice or help would be appreciated. I've spent a good 8 hours fumbling through this and feel like an idiot!
Thanks!
Comment: Unexplained downvote compensated
Answer: You will need to either tell the default gateway on the network eth2 is connected to that 10.0.0.0/24 is behind that router by specifying a default route (i.e. on your cable modem which is apparently acting as a router also), or use source NAT on traffic outbound on eth2.
Double NAT is inadvisable and so if you are doing that you should find some way to get an internet-routeable IP on the router's internet-facing interface eth2.
The problem is that you have a broken return path; the traffic coming back to 10.0.0.0/24 is not routeable because 10.0.0.0/24 isn't routeable from the segment with the cable modem on it.
A bridge is not what you want here.  Bridges are layer 2 things.
Comment: Sorry, but can you please clarify. I'm sill unclear. Do I need to figure out how to set the routes like @ http://www.thegeekstuff.com/2012/04/route-examples/ or do you mean something else?
Comment: All you need to do is set a route on the device 10.0.0.1 is using as a gateway, so it knows where 10.0.0.0/24 is.


Limit $I=\lim_{n \to \infty } \sqrt[n]{\int_0 ^1 x^{\frac{n(n+1)}{2}}(1-x)(1-x^2)\cdots(1-x^n)d x}$

Question: Im a new participant in this mathematical forum, so this is one of that i couldn't solve it.
$$I=\lim_{n \to \infty } \sqrt[n]{\int_0 ^1 x^{\frac{n(n+1)}{2}}(1-x)(1-x^2)\cdots(1-x^n)d x}$$
I've tried to transform the product in a summation as function of a logarithmic function, and I wasn't been successful. Like $u=x^n$, $du=nx^{n-1}dx$
$g_n(u) = \sqrt[n]{\frac{ dx}{du} \cdot x^{\frac{n(n+1)}{2}} \cdot \prod_{k=1}^n(1 - x^k)}$
$g_n(u)=\sqrt[n]{\frac{1}{nx^{n-1}}} \cdot x^{\frac{n+1}{2}} \cdot e^{\frac 1n\sum_{k=1}^n \ln(1 - x^k)}$
Comment: Have a look at http://math.stackexchange.com/questions/1123621/how-to-compute-this-limit/1124080?sfb=2#1124080 for related techniques.
Comment: They are not exactly the same. The power of $x$ inside the integral differs.
Comment: Yes. By the way, since $x^k-x^{2k}$ is $\leq \frac{1}{4}$ on $[0,1]$, the limit here is $\leq\frac{1}{4}$.
Comment: Is this from a particular contest?
Answer: See if this converts to a Riemann sum which converges to an integral:
$$g_n(u)=\sqrt[n]{\frac{1}{nx^{n-1}}} \cdot x^{\frac{n+1}{2}} \cdot e^{\frac 1n\sum_{k=1}^n \ln(1 - x^k)}=\sqrt[n]{\frac{1}{nx^{1-1/n}}} \cdot u^{\frac{n+1}{2n}} \cdot e^{\frac 1n\sum_{k=1}^n \ln(1 - x^k)}\\\sim \sqrt{u}\exp\int_0^1\ln(1-u^t)dt=\sqrt u\exp\frac{\zeta(2)-{\rm Li}_2(u)}{\ln u}$$
The maxima seems to be $\approx0.185155$ at $u\approx 0.245254$ without possibly a closed form as wolfram says.
Comment: (+1) I agree. The limit is the value of $$\sqrt{u}\exp\frac{\zeta(2)-\operatorname{Li}_2(u)}{\log u}$$ in the first positive root of $$\zeta(2)-\operatorname{Li}_2(u) = \frac{1}{2}\log^2 u+\log u \log(1-u), $$ hence $u(1-u)$ for $u\approx 0.245254$.
Answer: As $$\sqrt{x^k(1-x^k)}\le\frac{x^k+(1-x^k)}2=\frac12\iff x^k(1-x^k)\le\frac14$$
So:
$$\lim_{n \to \infty } \sqrt[n]{\int_0 ^1 x^{\frac{n(n+1)}{2}}(1-x)(1-x^2)\cdots(1-x^n)d x}=\lim_{n \to \infty } \sqrt[n]{\int_0 ^1 \prod_{k=1}^nx^k(1-x^k)}\le\lim_{n\to\infty}\sqrt[n]{\int_0^1\left(\frac14\right)^ndx}=\frac14$$
So the limit is $\displaystyle\le\frac14$
Note that equality holds here not for a definite values but $\sqrt[k]2$ which are all less than $0.5$
Comment: I got it, nice one ! Thanks +1
Comment: @Vinisth no 1/4 is not the answer. I mean the answer is less than 1/4
Comment: Yes i got it, it can simplify the problem


iptables causing connection to stall

Question: We are having connection stall issues on many of our http servers. As a test I have created a script that connects to the webserver using curl and tries do download a txt file of about 3mb size.
Every now and then the speed goes down to 0 and the connection hangs.
When I disable iptables the problem resolves and everything works ok.
 iptables -vL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   28  2080 ACCEPT     all  --  any    any     anywhere             anywhere            state RELATED,ESTABLISHED
    0     0 ACCEPT     icmp --  any    any     anywhere             anywhere
    0     0 ACCEPT     all  --  lo     any     anywhere             anywhere
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere            state NEW tcp dpt:ssh
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere            state NEW tcp dpt:http
   17  1924 REJECT     all  --  any    any     anywhere             anywhere            reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 REJECT     all  --  any    any     anywhere             anywhere            reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT 15 packets, 1564 bytes)
 pkts bytes target     prot opt in     out     source               destination

There is couple of routers and firewalls in between.
Any ideas what this could cause?
Ah. I use Centos 6.3 Kernel  2.6.32-279.19.1.el6.x86_64
Iptables version is: iptables-1.4.7-5.1.el6_2.x86_64
Drop message
IPTables-Dropped: IN=eth1 OUT= MAC=00:50:56:a6:00:9e:00:16:9c:ff:20:00:08:00 SRC=xxx DST=xxx LEN=80 TOS=0x00 PREC=0x00 TTL=62 ID=55755 DF PROTO=TCP SPT=34787 DPT=80 WINDOW=1539 RES=0x00 ACK URGP=0

Comment: Anything in the nat table `iptables -vL -t nat`? Also, how do you disable iptables?
Comment: Nothing in the nat table as I don't do any nat. I disable iptables by shuting down the service . (service iptables stop)
Comment: Are these the iptables settings on the web server machine?
Comment: yes. it somehow fixed the issue by setting tcp_sack to 0 on the webserver. Not sure if this is whise or not or what the reason is that it works like that
Answer: Most likely, you are running out of connection tracking entries. Raise net.nf_conntrack_max. If this is due to an attack, you may need to raise it quite a bit and decrease some settings like net.netfilter.nf_conntrack_tcp_timeout_syn_recv.
You could just rewrite your rules without connection tracking -- you don't seem to need it. That might reduce your flexibility in the future though.
Comment: Hi. I was able to fix it by disabling tcp_sack. not sure what this does or if this is a whise idea. maybe this hint tells you more than me :)
Comment: @Chris: Are you sure that's the only change you made? That would suggest you have some kind of ancient firewall in the path or are under a [sack attack](http://serverfault.com/a/11002/91987).
Comment: yes. I can watch it live how the connection drops as soon as I enable this again... I am not aware on the firewalls in between but I have a meeting tomorrow with one of the network guys. anything I could ask them? By the way. This happens to all our webservers that are in that specific network zone
Comment: Ask them if there's anything unusual about the way that zone is connected to other networks. Report your findings and see if they believe you. ;)

iptables causing connection to stall


Useless error message using --zone-file-format

Question: Running (all versions, plain+alpha+beta) with the zonefile.txt downloaded from my current DNS provider
gcloud dns record-sets import --zone=some-zone-tld --zone-file-format ./zonefile.txt

fails with the error:
ERROR: gcloud crashed (AttributeError): 'SyntaxError' object has no attribute 'message'

any ideas to what that error-message means? Does anyone have a working example zone-file that I can look at?
I have tried this but it made no difference to the error message: https://stackoverflow.com/a/65204476/1151537
this is the zonefile:
$ORIGIN intellifinder.de.
;A records
*.intellifinder.de. IN  1h  A   188.8.131.52
mail.intellifinder.de.  IN  1h  A   220.127.116.11
www.intellifinder.de.   IN  1h  A   188.8.131.52
api.intellifinder.de.   IN  1h  A   220.127.116.11
cloud.intellifinder.de. IN  1h  A   22.214.171.124
intellifinder.de.   IN  1m  A   126.96.36.199

;MX records
intellifinder.de.   IN  1h  MX  10  intellifinder-de.mail.protection.outlook.com.

;SOA records
@   IN  1h  SOA ns3.dandomain.dk.   email@example.com 2021082300  1h  1h  2w  5m

Comment: I tried the gcloud feedback command, it opened a browser window with an error message: "Bad Request
Error 400"
Comment: How do you think anyone can help you without even seeing the zonefile you are attempting to use. There is probably a problem in it and then a bug in `gcloud` that is unable to format the error message properly.
Answer: This error message means that the syntax inside the text file is not well defined.
You can check more information about importing records here.
The issue might also be related to gcloud shell, to confirm that, try to import the files again but with the --verbosity flag on the command.
Have a look at this GitHub issue where the same error was reported.
Comment: --verbosity=debug pointed to TTL: "DNS TTL value is not well-formed". Tried different values to no avail. Tried exporting from GCP and found out the TTL goes before IN, not after. The zonefile I exported from my current provider was broken.


Only show block if View or nid has certain term referenced to it

Question: I have a tricky one here and looking for some suggestions.
I have a Page view which uses a contextual filter on the nid (which is in the URL).
These nodes have a term reference field which contain various terms.
I have a block which I only want to be displayed on this page if the node has this specific term referenced to it. Bare-in-mind this is not the actual node page, this a dynamically created page/view based on the nid in the url.
Comment: Are you using drupal 7?
Comment: yes Drupal 7 mate
Answer: Did you try php code? If you enable 'PHP filter' module, you can add php code under 'Pages restricted to certain pages' option in block configuration and write your code like
<code><?php
$relative_path = request_uri();
if (some condition)   {

    return TRUE;
   }

 else
    return FALSE;

?>
</code>
Answer: Please try below steps,

Crearte a hook for the block display alter,
hook_block_view_MODULE_DELTA_alter()    // To alter specific block
Inside the hook, render the view using below code,
$my_view = views_get_view($my_view_name); // To get related Taxonomy term for the node
Check if the Taxonomy term exists.
Manage display/hide for the block.


Angular 4.4 Date deserialization from REST-Service

Question: I am using Angular 4's new HttpModule to retrieve data from a REST-Service. The problem is, that the data contains a Date typed property. I've seen this thread but when I try the solution suggested in the thread, I get the following error: res.json is not a function
Here is my code:
getMarkets(): Observable<Christmasmarket[]> {
    let markets: Christmasmarket[];
    return this.http.get(this.apiUrl).map(this.extractData);

  }

  private extractData(res: Response) {

    let body = res.json().data;
    console.log(body);
    body.forEach((d) => {
      d.start = new Date(d.start)
      d.end = new Date(d.end);
    });
    return body.data || {};
  }

And here is the data from the service:
[
  {
    "id": 1,
    "name": "mein markt1",
    "start": "2017-11-14T23:00:47.838+0000",
    "end": "2017-12-14T23:00:47.838+0000",
    "postalCode": "1100",
    "city": "wien",
    "address": "test",
    "rating": 4.56,
    "ratingPrice": 1.2,
    "numberOfRatings": 10,
    "latLng": {
      "latitude": 48.208982,
      "longitude": 16.373213
    },
    "openingHours": [
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 0
      },
      {
        "open": true,
        "start": 660,
        "end": 1200,
        "dayOfWeek": 1
      },
      {
        "open": true,
        "start": 690,
        "end": 1200,
        "dayOfWeek": 2
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 3
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 4
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 5
      },
      {
        "open": true,
        "start": 600,
        "end": 1200,
        "dayOfWeek": 6
      }
    ],
    "extraordinaryOpeningHours": [

    ]
  }
]

Answer: You are probably using the new HttpClientModule, rather then the old HttpModule. With HttpClient, the deserialization from JSON is done automatically, so there is no response.json() method.
More about it in angular docs: https://angular.io/guide/http
Also note then with HttpClient, you can specify interface of the response, so it will automatically map it for you:
interface ItemsResponse {
  results: string[];
}

http.get<ItemsResponse>('/api/items').subscribe(data => {
  // data is now an instance of type ItemsResponse, so you can do this:
  this.results = data.results;
});

This should work also with Date type i guess.
Comment: @GreyBeadedGekk I tried it without the extractData function and no, it does not work. Somehow it does not map it as a date. When I'm calling start.getTime() I'm getting an error that there is not such a function - because it is a String.
Comment: Yes thank you, I did not quite get it that the extractData now takes my type as a parameter as well. Thanks!
Comment: What you actually missed is that you shouldn't need an extractData method at all - the  HttpClient does that for you.


Help in understanding this motivation for not completing the $\sigma$-algebra in the definition of measurable stochastic Process

Question: The definition 3.2.22 aluded to in the picture below is the definition of a (product space) $\mathcal{B}([0,\infty[)\times \mathcal{F} $-measurable Stochastic Process $X:[0,\infty[\times \Omega \rightarrow E$, where $(E,\Sigma)$ is a measurable space.

I'm not sure I understand the definition of $X$, and $X_{\omega}$ at the event they define in the last part of the remark.
Answer: $X$ is the function of two variables $(t,\omega)\mapsto X_t(\omega)$. If $T:\Omega\to[0,\infty)$ (thought of as a random time) is $\mathcal F$-measurable  then you can consider the function $X_T:\Omega\to\Bbb R$ defined by $X_T(\omega)=X_{T(\omega)}(\omega)$. In the specific case at hand, $T$ is the identity function on $[0,1]$ and $X_T(\omega) = X_{\omega}(\omega) =I_{\{\omega\in V\}}$. Thus, $[X_T]^{-1}(\{1\}) =V$, which in not $\mathcal F$-measurable, so $X_T$ is not a random variable.
I guess the author's point is that even though $X$ is measurable with respect to the completion of $\mathcal B[0,1]\otimes\mathcal F$, this is not enough to guarantee that compositions like $X_T$ are random variables. On the other hand, for each fixed $t\ge 0$, $X_t(\omega)=I_{\{t=\omega\in V\}}$ vanishes for all but one $\omega$, hence a.e. Because $\mathcal F$ is complete, $X_t$ is $\mathcal F$-measurable.
Comment: Thanks for the help, John. ;)


Matching HTML-style comments with lex/flex

Question: I wish to match COMMENT as  so:

It starts with
C - could be anything (including tabs, line breaks, etc.)

I got a problem with ending in the first -->
and thus obviously this solution doesn't work:
 COMMENT (\

I know that's a bit of a pain to read. It translates to:
An


Input dialog loop end early

Question: When the user enters nothing in an input dialog box it ends the loop below. I've debugged the code and name is indeed "" when the user enters nothing.
while(name == "" || name == null){
        name = JOptionPane.showInputDialog("Enter your name:");
    }

Also, When the window containing the input dialog is closed or cancelled, the program doesn't exit the loop.
Can anyone provide some insight for me?
Answer: Don't compare strings with name == "". Use "".equals(name) or in your case even name.isEmpty() (available since Java 6).
== is used to compare references, not value of objects. More info here.
Change your code to:
while(name == null || name.isEmpty()){
    name = JOptionPane.showInputDialog("Enter you're name:");
}

Answer: Never use == to compare Strings in Java.
Use the method equals(String).
See the following link
Answer: There is a big difference using "==" oder equals. Try also to use equalsIgnoreCase() to be sure
while(name == null || name.equalsIgnoreCase("")){
        name = JOptionPane.showInputDialog("Enter you're name:");
    }

Answer: Stop comparing strings and start using the Apache Commons Lang StringUtils class.  It handles nulls nicely and is well tested.  You will want to use StringUtils.isBlamk(name) or StringUtils.isEmpty(name)
Answer: The window closing not causing the program to exit the loop is because I needed to add a default close operation by calling JFrame's setDefaultCloseOperation with the parameter JFrame.EXIT_ON_CLOSE. This terminates the JFrame and prevents it from running in the background after the window is closed.

Input dialog loop end early


Crystal Report com LEFT JOIN e WHERE

Question: Estou com um problema para fazer um LEFT JOIN no Crystal Reports. Pelo que pesquisei, é um problema de SQL clássico quando se usa critérios WHERE cruzando com o LEFT JOIN. Tentei resolver de todas as maneiras, mas não consegui.
São 4 tabelas relacionadas:
[OrcHDR]
[OrdemProducao]
[ItemNota]
[NotasFiscais]
Estou interessado num relatório com todos os pedidos com OP, INCLUSIVE os que ainda não foram faturados, com exceção de alguns que estão especificados
Aqui está o SQL:
<code>SELECT
"OrcHdr"."SPreco",
"OrcHdr"."SCustosMat",
"OrcHdr"."SCustosMO",
"OrcHdr"."SCustosTerc",
"OrcHdr"."SCustosImpostos",
"OrcHdr"."SCustosComissoes",
"OrcHdr"."SCustosFin",
"OrcHdr"."SCustosVenOutros",
"OrcHdr"."NomeAgencia",
"OrdensProducao"."NumOrdem",
"OrdensProducao"."Descricao",
"OrdensProducao"."NomeCliente",
"OrdensProducao"."TipoProduto",
"ItemNota"."Fatura",
"ItemNota"."Devolucao",
"OrdensProducao"."DtEmissao",
"ItemNota"."ValorTotal",
"NotasFiscais"."NaturezaOperacao",
"NotasFiscais"."Situacao",
"OrcHdr"."NumOrcamento",
"ItemNota"."NumOrdem"

 FROM

(("TABELA"."dbo"."OrcHdr" "OrcHdr"

INNER JOIN

"TABELA"."dbo"."OrdensProducao" "OrdensProducao" ON
"OrcHdr"."NumOrcamento"="OrdensProducao"."NumOrdem")

LEFT OUTER JOIN

"TABELA"."dbo"."ItemNota" "ItemNota" ON "OrdensProducao"."NumOrdem"="ItemNota"."NumOrdem")

INNER JOIN

"TABELA"."dbo"."NotasFiscais" "NotasFiscais" ON "ItemNota"."ObjID_Nota"="NotasFiscais"."ObjID"

 WHERE

("ItemNota"."Devolucao" IS  NULL  OR "ItemNota"."Devolucao"<>'D') AND ("ItemNota"."Fatura" IS  NULL  OR "ItemNota"."Fatura"='F') AND
("NotasFiscais"."Situacao" IS  NULL  OR "NotasFiscais"."Situacao"='N') AND ("NotasFiscais"."NaturezaOperacao" IS  NULL  OR  NOT ("NotasFiscais"."NaturezaOperacao" LIKE 'doa%' OR "NotasFiscais"."NaturezaOperacao" LIKE 'reme%'))

ORDER BY "OrcHdr"."NumOrcamento"
</code>
O que de fato está acontecendo é que só obtenho as OPs que já foram faturadas, ou seja, que estão presentes nas tabelas [ItemNota] e [NotasFicais].
O que estou fazendo de errado?
Comment: Tem certeza que é AND mesmo, e não OR ? (tou chutando, faltam detalhes na sua questão do que você precisa que aconteça).
Comment: É AND mesmo, todas as condições devem ser atendidas ao mesmo tempo.

O que preciso é um relatório, em determinado intervalo de tempo, com informações de todas as "OrdensProducao"."NumOrdem", inclusive os que não estão presentes em ItemNota.
Comment: Pode ser o tipo de Join escolhido, não? Veja se isso ajuda: [Qual é a diferença entre inner join e outer join?](http://pt.stackoverflow.com/a/6448/70)
Comment: O Crystal Report entrou na história com Pilatos no Credo como dizem os antigos ...
Answer: Acabei resolvendo meu problema trocando as ordens de relacionamento das tabelas.
Antes estavam assim:
<code>[Orçamento]-[OrdemProducao] -> [ItemPedido]-[NotaFiscal]
</code>
Modifiquei para:
<code>[Orçamento]-[OrdemProducao] -> [ItemPedido]
                            -> [NotaFiscal]
</code>
E tudo funcionou.
Obrigado aos que colaboraram!
Comment: Cassiano, como você mesmo descobriu, a ordem importa sim. A regra é simples: primeiro os inner joins e depois os outer joins.

Crystal Report com LEFT JOIN e WHERE