how to get data from an event in another class in flash as3?

Question:
I have a class called socket.as and is responsible for socket connection etc. It has an event listener onSocketData, which is called whenever data is received. In my main class, Main.as, i have instantiated an object of socket class.
How can I get data from socket class?  Do i have to create a custom event in Main.as that should be triggered by socket class?
Thank you.
below is the event listener from socket class:

private function onSocketData(event:ProgressEvent):void

{
   //string sent over serial port.
   var data:String = _socket.readUTFBytes( _socket.bytesAvailable );

   var direction:int = 0;

   buffer += data;

 while((index = buffer.indexOf(EOL_DELIMITER)) > -1)
 {
  msg = buffer.substring(0, index-1);
  len = (buffer.indexOf(EOL_DELIMITER)) - 1;

  //remove the message from the buffer
  buffer = buffer.substring(index + 1);

  if ( msg != "off" )
  {
   button = parseInt(msg.substr(6, (len-8)));

   trace("Socket Data: " + msg + ", Button: " + button);
  }
 }
}
Answer: As you mention , you could create a CustomEvent that will be triggered by the Socket class or you could dispatch an Event from the Socket class , whenever data is available and use a getter to retrieve the variable.
I've answered a similar question here:
AS3 Passing data between objects/classes
Comment: in case someone is interested here is what i did (Kinda what PatrickS mentioned):   right after button = parseInt(msg.substr(6, (len-8))); i did   dispatchEvent(new Event("onSocketData")); And then in main i added an listener for it _socket.addEventListener("onSocketData", _socketData); Since i had a getter function i used that to get my data inside the listener.
Answer: Well, if you just want to get data out, you can store it in an array in your class, and then have a method that pulls it out.
If, instead, you want to push up an event to Main.as, then you will need to create a custom event.
The easiest way to do this is to derive your class from EventDispatcher.
Then, when you want to fire an event, you just call super.dispatchEvent(new CustomEvent(payload)) where CustomEvent is a class of yours that derives from Event.
The general pattern would look like this:
Create a custom event... unless an existing event class makes sense... then just reuse something else.
public class SocketEvent extends Event {
    public var payload:String;
    public function SocketEvent(payload:String, bubbles:Boolean=false, cancelable:Boolean=false) {
        super(Socket.EVENT_NAME, bubbles, cancelable);
        this.payload = payload;
    }
}

Then, the class that fires the event looks like this:
public class Socket extends EventDispatcher {
    public static const EVENT_NAME:String = "EVENT_NAME";

    private function fireTheEvent(payload:String):void {
        dispatchEvent(new SocketEvent(payload));
    }
}

Finally, to use it in Main.as, you would do this:
private var socket:Socket = new Socket();
socket.addEventListener(Socket.EVENT_NAME, actionHandler);

Note that this is NOT the only way to fire an event.  Another way would be to implement IEventDispatcher in terms of the static EventDispatcher methods... but that is a different example.
Comment: if i am using a getter function then i do not need to create a custom event class right?
Comment: plus don't we have to override the clone method if we are inheriting from Event class? Thank you
Comment: Right.  If you use a getter function, then there is no need for the event firing...  or, you can fire an `Event` with the name of "DataChanged" that tells the subscriber to call the getter.


Python script succeeds manually but fails on crontab

Question: So I'm currently trying to get a script working but it's behaving differently when I run it manually than when I run it from crontab.  Basically, I have a reverse ssh tunnel set up from one server to another, and in order to verify that my tunnel is up I:

SSH from server A to server B
Wget a test url from on server A from server B
if Wget succeeds, I disconnect and do nothing
if Wget fails, I disconnect and restart the tunnel

I know there are more elegant ways to verify ssh tunnels (like autossh and ServerKeepAlive), but for both policy and redundancy issues, I have to do things this way.  Anyways, here's the script:
from __future__ import print_function
from __future__ import absolute_import

import os, sys, subprocess, logging, pexpect

COMMAND_PROMPT = '[#$] '
TERMINAL_PROMPT = '(?1)terminal type\?'
TERMINAL_TYPE = 'vt100'
SSH_NEWKEY = '(?i)are you sure you want to continue connecting'
SERVERS = [{address':'192.168.100.10', 'connString':'ssh firstname.lastname@example.com', 'testGet':'wget http://192.168.100.11/test.html -t 1 -T 10', 'tunnel':'start_tunnel'}, {address':'192.168.100.12', 'connString':'ssh email@example.com', 'testGet':'wget http://192.168.100.13/test.html -t 1 -T 10', 'tunnel':'start_tunnel2'}]

def main():

    global COMMAND_PROMPT, TERMINAL_PROMPT, TERMINAL_TYPE, SSH_NEWKEY, SERVERS

    #set up logging
    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG)
    handler = logging.FileHandler('/home/user/tunnelTest.log')
    formatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s: %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)

    for x in SERVERS:

        #connect to server
        child = pexpect.spawn(x['connString'])
        i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password'])
        if i == 0:   #Timeout
             log.debug('ERROR! Could not log in to ' + x['address'] + ' ...')
             sys.exit(1)
        if i = 1:    #No key cached
             child.sendline('yes')
             child.expect(COMMAND_PROMPT)
             log.debug('Connected to ' + x['address'] + '...')
        if i = 2:    #Good to go
             log.debug('Connected to ' + x['address'] + '...')
             pass

        #Housecleaning
        child.sendline('cd /tmp')
        child.expect(COMMAND_LINE)
        child.sendline('rm -r test.html')
        child.expect(COMMAND_LINE)

        log.debug('Testing service using ' + x['testGet'] + ' ...')
        child.sendline(x['testGet'])
        child.expect(COMMAND_PROMPT)
        if 'saved' in child.before.lower():
            log.debug('Tunnel working, nothing to do here!')
            log.debug('Disconnecting from remote host ' + x['address'] + '...')
            child.sendline('exit')
        else:
            log.error('Tunnel down!')
            log.debug('Disconnecting from remote host ' + x['address'] + ' and restarting tunnel')
            child.sendline('exit')
            subprocess.call(['start',x['tunnel']])
            log.debug('Autossh tunnel restarted')

if __name__ == "__main__":
    main()

My crontab entry is as follows:
0,30 * * * * python /home/user/tunnelTest.py

So yeah -- this script runs fine when I do it manually (sudo python tunnelTest.py) and also runs fine on crontab unless a tunnel is down.  When a tunnel is down, I get the "Tunnel down!" and "Disconnecting from remote host 192.168.100.10 and restarting tunnel" messages in my log, but the script seems to die there.  The tunnel doesn't restart, and I get no messages in my log until the start of the next scheduled run.
The start_tunnel script is in /etc/init, the testTunnel.py script is in /home/user, the testTunnel.log file is in /home/user/logs, and I ran crontab -e as root.
Any insight into this matter would be greatly appreciated.
Thanks!
Comment: So it's having issues calling an external script from Cron? Have you tried giving the complete path to the external script, or logging the return code from the call to the external script?
Comment: Cron calls the script, but the script is dying (by the looks of it, on the subprocess call).  I added the full path to python as Shutupsquare suggested and I'm hoping that was my issue.
Comment: Yeah, I should have been a bit more verbose, I was asking if the script had the full path of the subscript. Either way, it would be useful to get the return code from the subscript call, and do some logging int he subscript as well.
Comment: I'm pretty sure it's dying on either the `child.sendline('exit')` or `subprocess.call(['start',x['tunnel']])` lines.  Added more debugging there to see what's up.
Comment: Figured it out!  I had to give absolute paths to `stop` and `start`.  Works fine now.
Comment: I like the suggestion that you add a line like  "* * * * * env > /tmp/env.txt" temporarily to your crontab so that you can see what environment variables are set up when a job runs within cron.  It really hammers home the differences if you compare it with your own login.
Answer: You need to use the full path to python eg
/usr/bin/python
you can find out the path with which python
So your crontab entry would look like
0,30 * * * * /usr/bin/python /home/user/tunnelTest.py
Comment: You alays have to keep in your head that the cronjobs are seeing diffenrent environment variables than an interactive prompt.
Comment: Thanks for the reply!  I made the changes and will wait and see.  It seems strange to me that this would be the issue though, since crontab runs the script, but the script is failing at a certain point.
Comment: @tparrott Sorry I read the title and seen the crontab entry and assumed that it wasn't running because in cron you usually have to use absolute paths unless you have setup some environmental variables. If your script is firing then yes adjusting the crontab entry would not help here. Although I would probably expect that you are having a environmental variable problem.
Comment: Yup, that turned out to be the issue.  I had to give absolute paths to `/sbin/start` and `/sbin/stop`.


Autoplay audio file on active div

Question: I'm terrible at JS and I've tried dozens of thing to make this work, but nothing seems to work for me.
I want AUDIO1 file to play and AUDIO2 file to pause automatically when certain div element has "elementor-active" class, and vice versa.
Any help appreciated.
Here's my code:

TAB 1

TAB 2

<audio id="AUDIO1" loop="loop">
<source src="http://localhost/test/wp-content/uploads/2018/06/audio1.ogg">
<source src="http://localhost/test/wp-content/uploads/2018/06/audio1.mp3" type="audio/mpeg">
</audio>

<audio id="AUDIO2" loop="loop">
<source src="http://localhost/test/wp-content/uploads/2018/06/audio2.ogg">
<source src="http://localhost/grad/wp-content/uploads/2018/06/audio2.mp3" type="audio/mpeg">
</audio>

Answer: For example:
var audio_one = new Audio('PATH_TO_AUDIO_1');
var audio_two = new Audio('PATH_TO_AUDIO_2');

var timerId = setInterval(function() {
  if ($('YOUR_BLOCK_SELECTOR').hasClass('active')) {
    audio_one.play();
    audio_two.pause();
  } else {
    audio_one.pause();
    audio_two.play();
  }
}, 250);

Autoplay audio file on active div


With strapi, how to display the markdown in my gatsby frontendë

Question: I use strapi as a CMS, and I return "rich text markdown" fields,
I can't formatë the markdown in my frontend with gatsby.
Do you have any solutions ? THANKS !
I tried modules like "react markdown" but it doesn't work with my version of gatsby which is in 2..
Answer:
First, installing the CKEditor 5 plugin in Strapi, followed by
rebuilding and restarting the Strapi app.
Once the app is running, navigate to the content builder in your
Strapi and modify the default rich text box to CKEditor 5 rich text
box (custom), adjusting the content according to your desired
structure (utilizing features such as bullets, text color, and text
indent).
In your frontend use this tag

you definetly get the format you want.this one is working for me.


Accepting two client sockets as a server for a one-on-one game; mistake in tutorial?

Question: I want to add network one-on-one support for my Battleship game, and found this tutorial regarding server-client network programming:
http://csharp.net-informations.com/communications/csharp-multi-threaded-server-socket.htm
The code I'm using is the following, more or less just taken from there with some adjustments:
  public class HandleClient
  {
    TcpClient clientSocket;
    string clientNumber;

    public void StartClient(TcpClient inClientSocket, string clientNumber)
    {
      this.clientSocket = inClientSocket;
      this.clientNumber = clientNumber;

      Thread clientThread = new Thread(DoChat);
      clientThread.Start();
    }

    private void DoChat()
    {
      int requestCount = 0;
      byte[] inBytes = new byte[10025];
      string dataFromClient = null;
      byte[] outBytes = null;
      string rCount;
      string serverResponse = null;

      while (true)
      {
        try
        {
          requestCount++;

          NetworkStream stream = clientSocket.GetStream();
          stream.Read(inBytes, 0, (int)clientSocket.ReceiveBufferSize);

          dataFromClient = Encoding.ASCII.GetString(inBytes);
          dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$$"));
          Console.WriteLine(" >> From client " + clientNumber + dataFromClient);

          rCount = Convert.ToString(requestCount);
          serverResponse = "Server to client " + clientNumber + ": " + rCount;
          outBytes = Encoding.ASCII.GetBytes(serverResponse);
          stream.Write(outBytes, 0, outBytes.Length);
          stream.Flush();
        }
        catch (Exception e)
        {
          Console.WriteLine(e.ToString());
        }
      }
    }
  }

and
  class BattleshipServer
  {
    static void Main(string[] args)
    {
      TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
      TcpClient clientSocket = default(TcpClient);
      int counter = 0;

      serverSocket.Start();

      while (true)
      {
        if (counter < 2)
        {
          counter++;

          clientSocket = serverSocket.AcceptTcpClient();
          Console.WriteLine("Client " + counter + " connected.");
          HandleClient client = new HandleClient();
          client.StartClient(clientSocket, counter.ToString());
        }
      }

      clientSocket.Close();
      serverSocket.Stop();
      Console.WriteLine(" >> " + "exit");
      Console.ReadLine();
    }
  }

However, I wonder about the last few lines just above this. Visual Studio complains about this code being unreachable, and I can see why. Is there any reason behind this code being there?
Also, I wonder what keeps counter from going up all the time? Is serverSocket.AcceptTcpClient() keeping the program "waiting" until another client connects maybe?
Thanks! And if you know of any other good sources to learn about this, I'll be glad to hear them :) Since I'd still have to adjust the above code by a good lot to make my game "wait" for data from the other player, restrict the player count, and so on.
Answer: The typo in the example (handleClinet()) may hint that the code was never reviewed; and you're right, the code won't leave the while block in this case.
The counter appears to serve as an identification of each client, as the introduction says "can handle multiple clients at the same time".
In your case, a one-on-one game, you probably want a single serverSocket.AcceptTcpClient and start the game after some basic information has been exchanged (ie. player names of both ends communicated), and you won't need that while loop there.
Comment: Thank you! I think I'll go the way of accepting two clients though, since the server is a separate console program. This may come in handy should I decide to generalize it to accept more people playing each other later. So the AcceptTcpClient() really "waits" for a connection then?
Comment: @Randal'Thor yes `AcceptTcpClient()` blocks until a client has connected.


StackExchange.Redis.RedisTimeoutException even after all suggestion done

Question: I am getting below mentioned error
My current settings are:
opt.SyncTimeout = 100000
opt.AllowAdmin = True
opt.KeepAlive = 300000
<processModel autoConfig="false" minIoThreads="200" minWorkerThreads="200" />

An unhandled exception of type 'StackExchange.Redis.RedisTimeoutException' occurred in StackExchange.Redis.dll
Additional information: Timeout performing KEYS, inst: 0, mgr: ExecuteSelect, err: never, queue: 2, qu: 2, qs: 0, qc: 0, wr: 0, wq: 1, in: 0, ar: 0, clientName: DESKTOP-4PP7624, serverEndpoint: Unspecified/localhost:6379, IOCP: (Busy=0,Free=1000,Min=4,Max=1000), WORKER: (Busy=5,Free=4090,Min=4,Max=4095) (Please take a look at this article for some common client-side issues that can cause timeouts: http://stackexchange.github.io/StackExchange.Redis/Timeouts)

Answer: It does not seem that your minIoThreads and minWorkerThreads worked based on your error log.
Also, Keys is a very expensive call - it is O(n). Maybe try increasing the sync timeout higher?


How would I count the time signature 3/4+3/8

Question: Right now our band director is conducting at 9/8 and we've just been counting the start of every measure but I want to know if there's a better way to do it.
Comment: Can you edit your question and post an example of the music you are talking about? Is it an ongoing rhythm or just one bar?
Comment: [Blue Rondo à la Turk](https://www.youtube.com/watch?v=j9GgmGLPbWU), maybe?
Comment: What's the connection between the band director counting 9/8 and your question about 3/4 + 6/8? And are you asking about how they wave their baton/hand, or how _you_ would count aloud/in your head?
Comment: What does your band director's conducting of 9/8 time look like? Does it look identical to their conducting of 3/4 time or not?
Comment: What's the tempo?  Is the conductor conducting nine beats per measure?  If not in 9, "normal" 9/8 is usually conducted in 3, but this would be confusing if the meter is grouped, as indicated, 2+2+2+3; the better choice there would be a 4 pattern where the fourth beat is 50% longer than the first three.  Which is your conductor doing?
Comment: Along with @JohnBelzaguy's comment, how it's counted can depend greatly on the actual rhythm of the music.
Comment: We need more context and info. My answer came from a misdirected angle!
Comment: Welcome! Please use the "edit" button to explain more, because it's not clear right now what you're facing. If possible, please include an image of the music, and tell more about how the director is conducting. If you mean that each measure contains 9 eighth notes of equal length, of which 6 are supposed to be grouped as duples and the last three as triples, then beating 3 large beats, each 3 eighth notes long, is a strange choice. Maybe it's inexperience, or maybe it's because of something happening in other parts. *If* this is the case, there's still a better way than just tracking downbeats
Comment: Voting to close for now as unclear; I'll retract my vote once it becomes answerable.
Comment: Sorry, I misread the question, for some reason I thought it was`3/4+6/8`, but it is really about `3/4+3/8`. What time signature is in the score, can you show an image of the music?
Comment: I don't think we can usefully address this question until you show us a page of this music.
Answer: I misread the question so I'm updating my answer, but I've left my original answer below.
The question title showing 3/4+3/8 had me confused whether additive meter or alternating meters were involved.
Normal 9/8 would be counted like...
  <     <     <
9 _____ _____ _____
8 | | | | | | | | |
  1 + a 2 + a 3 + a

...where the meter is compound and so the beat is subdivided by three and the beaming of notes groups by three visually.
Additive meter will use the same number of eighth notes per measure, but the time signature is written additively to show different groupings and accenting...
          <   <   <   <
(2+2+2+3) ___ ___ ___ _____
    8     | | | | | | | | |
          1 + 2 + 3 + 1 + a

The same grouping, beaming, and accenting could be achieved with alternating time signatures where two time signatures are given at the beginning and then the measures alternate with appropriate grouping, beaming, and accents...
    <   <   <   | <     | <   <   <   | <     |
3 3 ___ ___ ___ | _____ | ___ ___ ___ | _____ |
4 8 | | | | | | | | | | | | | | | | | | | | | |
    1 + 2 + 3 + | 1 + a | 1 + 2 + 3 + | 1 + a |

The rhythms using additive or alternating time signatures should have a noticeable rhythmic effect from plain 9/8. That effect is sort of like hemiola or syncopation, with a kind of beat/accent displacement, compared to the regular, even beats of 9/8.

How would I count the time signature 3/4+3/8

I'm sort of assuming when you say time signatures you are referring to what is notated in a score, and that would seem to be alternating time signatures.

Right now our band director is conducting at 9/8

That would not be the same as the alternating or additive time signature possibilities.

Below vertical lines are meant to be note stems, horizontal lines are note beams, < is the beat accent, and 3 is for a triplet figure. The bottom line of each of the five examples is how to count the rhythm aloud with one common scheme of syllables.
3 <   <   <
4 |   |   |
  1   2   3

  <   <   <
3 ___ ___ ___
4 | | | | | |
  1 + 2 + 3 +

  <     <
6 _____ _____
8 | | | | | |
  1 + a 2 + a

Above the eighth notes have the same duration in 3/4 and 6/8 but the accent of the beat is different, three beats versus two beats respectively.
To make 3/4 equal to 9/8 you could use triplets in 3/4, as below...
  <     <     <
3 __3__ __3__ __3__
4 | | | | | | | | |
  1 + a 2 + a 3 + a

  <     <     <
9 _____ _____ _____
8 | | | | | | | | |
  1 + a 2 + a 3 + a

... the eighth notes for triplets in 3/4 or 9/8 will have the same duration. But, if the tempo of all five examples is the same, the eighth notes in the second group of examples will move a bit faster than those in the first group.
Comment: My assumption is: The music wants 9 equal eighth notes, grouped 2 + 2 + 2 + 3, and the conductor, either because they're intimidated or for good musical reasons, says "Well, that's 9 total eighth notes; I'll just beat 9/8," and the player wonders how to map their music to the stick pattern. But we'll need clarification to know whether I'm right.
Comment: My count is 1 & 2 & 3 &  4 & a... where each symbol gets the same duration; the numbers get the internal accents. (Too close to this answer to be worth a comment. Counting 9/8 is different, it's 3/4 but in triplets, 1& a 2 & a 3 & a; the internal accents fall differently,
Comment: @AndyBonner. ah, I see it now! My eyes saw 3/8 but it registered to me as 6/8. I will try to revise my answer.
Answer: I don't understand why there are deleted answers that are correct and concise, nor why there are close votes on this question. With that out of the way:

Yes, there is a better way. Normally this would be conducted in four with a longer fourth beat, like this:
down & in & out & up & uh | down & in & out & up & uh |

I always count in the same pattern as the conductor/director conducts, so I would count this:
1 & 2 & 3 & 4 & uh | 1 & 2 & 3 & 4 & uh |

With that in mind, I suggest counting along with your director, so I would count 9/8 so I don't get lost, unless my part had strong rhythms that contradict 9/8. In that latter case... I'm not sure what I would do. Maybe practice with a metronome set to 9/8 so I can follow the conductor better.
Note that in more recent music, this meter would often be written as 9/8 with a notation above the first appearance of the meter of "(2+2+2+3)". Also 1/8 notes would be beamed to show those subdivisions. For an example, see the perusal score for Frank Ticheli's "Vesuvius" (starting at m. 47 on page 16).
Comment: It's because the way to conduct, and perform, depends on how the composer wanted the emphases to be placed.  The OP failed to do so much as name the piece in question.
Comment: @CarlWitthoft I'd always suggest counting in alignment with the conductor, no matter what the piece is. Otherwise you end up trying to follow something contradictory to how you're understanding the music.
Comment: I agree; my comment should have specified the conductor or group leader


When does the operator operand after the source address get used in an Access Control Entry

Question: During my Cisco networking class I noticed something that confused me pertaining to extended access lists.
In the Cisco NetAcademy curriculum it lists this example of the syntax for an extended access-list:
**access-list** acl_number { **deny | permit | remark** } {protocol_name | protocol_number} source [ source_wildcard ] [**operator operand** ] [port port_number_or_name] destination [destination_wildcard] [operator operand ] [port port_number_or_name] [established]

My question is this: in what situations would you use the operator operand that directly follows the source / source wildcard in this above ACE example?
I have looked around in various places to find an answer, but as of yet I have not found one.
Answer: This option is used when you need to compare tcp and udp port numbers.
Operator can be one of the following keywords:

lt (less than)
gt (greater than)
eq (equal)
neq (not equal)
range (inclusive range of values)

and operand is the value of the source or destination port for the specified protocol.
For example, the following ACE:
access-list 100 permit tcp any host 192.168.1.1 eq 22

allows connections from any host to tcp port 22 (SSH) on host 192.168.1.1
And this one:
access-list 100 permit udp any eq 750 host 192.168.1.2 gt 1023

allows udp traffic with source port 750 and destination port greater than
1023 that originate from any host and is directed to the address 192.168.1.2
Comment: Ok, that makes sense. So , here's a follow-up question.  In Packet Tracer when I set the following acl :
Comment: ip access-list extended DenyHTTP deny 172.16.64.0 0.0.63.255 eq 80 host 172.16.128.1 eq 80, Packet Tracer will allow the PC on the source network to contact the destination servers web page via the in program "web browser", but if I eliminate the eq 80 after the source wildcard the source network PC is blocked correctly. So, why does this happen like this? I would assume that if the source network PC is using a web browser that would fulfill the source eq 80 condition. Would appreciate a little more clarification on this.
Comment: When the web browser sends a packet to the server, the source port is selected randomly from the ephemeral range [http://unix.stackexchange.com/questions/65475/ephemeral-port-what-is-it-and-what-does-it-do] so the ACE `access-list extended DenyHTTP deny 172.16.64.0 0.0.63.255 eq 80 host 172.16.128.1 eq 80` doesn't match and the traffic is allowed. When you remove the option `eq 80` the traffic that originate from source network is denied, regardless of the value of the source port.
Comment: Ephemeral ports, that seems to be the missing piece to the puzzle. I may need to go back and review some old notes, but I think this is the first time I have heard that particular term. At least now I have that little mystery solved.


What day of the week will be $1993^3$ days from Sunday?

Question: Can anyone show me how to solve this problem in a simple way?

What day of the week will be $1993^3$ days from Sunday?

Here is what I did: $1993^3=7916293657.$ $7916293657$ is divisible by $7$, so the answer should be Sunday. First the answer is wrong, second there must be a better way to solve the problem.
Comment: Divide 1993 by 7 and take the remainder *before*. 1993 is not divisible by seven.  If has remainder 5.  So 1993^3 will have the same remainder as 5^3.  Note 1993 = 1400 + 593=1400+490+103=1400+490+70+33=140+490+70+35-2=7M-2.  (7M-2)^3= some monster multiple of 7 -8=smmo7 -7 -1=7N-1.  So the answer is saturday.
Answer: $$1993 \equiv 5 \mod 7$$
$$5^3 \equiv (-2)^3 \equiv -8 \equiv -1 \mod 7$$
Hence, it is a Saturday.


Add Web Api controllers to an existing ASP.NET 4 web application

Question: Following the steps from this question How to add Web API to an existing ASP.NET MVC 4 Web Application project? , I have added web api support to my application.
In my original scenario I have the following web mvc controller:
public class FranchiseController : Controller
    {

        public ActionResult List()
        {
            return View();
        }

        [DataContext]
        public ActionResult GetAllFranchises()
        {
            var franchiseInfoViewModelList = new List<FranchiseInfoViewModel>();

            var franchiseInfoList = _franchiseService.GetAll();

            foreach (var franchiseInfo in franchiseInfoList)
            {
                franchiseInfoViewModelList.Add(new FranchiseInfoViewModel(franchiseInfo, p => p.IsImportant));
            }

            var jsonNetResult = new JsonNetResult
            {
                Formatting = Formatting.Indented,
                Data = franchiseInfoViewModelList
            };

            return jsonNetResult;
        }
    }

When the user navigates to the List view, I am calling
 $.getJSON("/franchise/GetAllFranchises")
                .done(function (data) {

                });

to go to the GetAllFranchises action method and return the json data. So far so good.
I have created the following web api controller:
public class FranchiseController : ApiController
    {
        public IEnumerable<FranchiseInfoViewModel> GetAllFranchises()
        {
            var allFranchises = new List<FranchiseInfoViewModel>();

            var franchiseInfoList = _franchiseService.GetAll();

            foreach (var franchiseInfo in franchiseInfoList)
            {
                allFranchises.Add(new FranchiseInfoViewModel(franchiseInfo, p => p.IsImportant));
            }

            return allFranchises;
        }
    }

and I am trying to get to its action method like this:
$.getJSON("api/franchise")
                .done(function (data) {

                });

I am getting 404 error and the app is trying to reach the following url:
/Franchise/api/franchise

instead of api/franchise.
Global Asax:
protected void Application_Start()
        {
            Log.StartSession();
            ElmahExtension.SetCurrentApplication(this);

            ViewEngines.Engines.Add(new OmegaViewEngine());
            AreaRegistration.RegisterAllAreas();

            SerializerConfig.Register(GlobalConfiguration.Configuration);
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            Bootstrapper.Initialise();
            FluentValidationModelValidatorProvider.Configure();

        }

Default route:
public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

In my Controllers folder I have my web mvc controller:
Controller\FranchiseController

and I have made a new folder WebAPI to hold my web api controller
Controller\WebAPI\FranchiseController

What am I doing wrong ? Thanks!
Answer: I'm not sure if it's the right move to name "FranchiseController" both to the MVC Internet Application Controller and to the MVC Web API Controller (totally different things). After renaming one of them I think you should put the Web Api Controller in the root of the directory (Controller).


Do Gaussian process (regression) have the universal approximation property?

Question: Can any continuous function on [a, b], where a and b are real numbers, be approximated or arbitrarily close to the function (in some norm) by Gaussian Processes (Regression)?
Comment: @whuber Though the technicalities may be a little bit loose, I think the question essentially means "For an input function $f$, is there a realization of a particular GP which is arbitrarily close to $f$ (in some norm)?" Or perhaps, "As we observe infinitely many sample points from a function $f$, and perform standard GP inference with that data, does the learned posterior mean function approach the true function $f$ (in some sense)?" These two are of course different properties, but I'd consider them close enough to be answerable (and hence cast the fifth reopen vote).
Comment: The statement of "universal approximation" in this question appears to have little or nothing to do with the statement in the referenced Wikipedia article.  Indeed, it isn't even clear how one might approximate a *function* with a *process*.  Could you elaborate on what you're trying to ask?
Comment: Be more specific!
Comment: yes! Well, actually, it depends on the covariance function, but [for some of them they do](http://stats.stackexchange.com/a/222304/58675). Dustin Tran et al. also proved an universal approximation theorem in the Bayesian framework for the [Variational Gaussian Process](http://dustintran.com/papers/TranRanganathBlei2016.pdf), which is a more complex model because of the warping functions, but it's very closely related. I'll write an answer if the question gets reopened. PS note that universal approximation, as for Neural Networks, only holds over a compact set, not over all of $\mathbb{R}^p$.
Comment: Maybe, you want to prove convergence instead of approximation. Otherwise, the proof is simple: you can take the function as prior for the mean. It is not much more than $x=x$, but it works.
Comment: @whuber  There is a rigorous description of the property here: https://arxiv.org/abs/1910.03344
Comment: @Dougal the very fact you (and the rest of us) have to guess what is being asked provides convincing evidence for why this question should remain closed.
Comment: @Dougal, I agree with your both suggestions.
Comment: Re the edit: any continuous function is a possible realization of a Gaussian process. Please state, then, what you mean by "can ... be approximated by."  In its current form your question isn't much different than a slightly simpler but mathematically similar version: can any number be "approximated" by a Normal distribution?  Does that convey the sense in which your question may be meaningless or confusing?
Comment: @whuber, I'm trying to improve and to be more **precise**
Comment: I appreciate that--but before you can be precise, you have to state something meaningful.
Comment: @Flabby Thank you: very helpful.  That sense of "approximate" differs substantially from the ones I was imagining when this question appeared.
Comment: No worries hope it helped somewhat :)
Answer: As @Dougal notes, there are two different ways in which your question may be interpreted. They are closely related, even if it may not seem so.
The first interpretation is: let $X$ be a compact subset of $\mathbb{R}^d$ (compactness is fundamental for all of the following!!!), let $k(\mathbf{x},\mathbf{x})$ be a continuous covariance function (or kernel) defined on $X\times X$, and denote with $C(X)$ the normed space of continuous functions on $X$, equipped with the maximum norm $||\cdot||_{\infty}$. For any function $f\in C(X)$, can $f$ be approximated to a prespecified tolerance $\epsilon$ by a function in the RKHS (Reproducing Kernel Hilbert Space) associated to $k$? You may well wonder what an RKHS is, an what all this has to do with Gaussian Process Regression. An RKHS $K(X)$ is the closure of the vector space formed by all possible finite linear combinations of all possible functions $f_\mathbf{y}(\mathbf{x})=k(\mathbf{x},\mathbf{y})$ where $\mathbf{y}\in X$. This is very strictly related to Gaussian process regression, because given a Gaussian process prior $GP(0,k(\mathbf{x},\mathbf{x}))$ on the space $C(X)$, then the (closure of the) space of all possible posterior means which can be generated by Gaussian Process Regression is exactly the RKHS. As a matter of fact, all possible posterior means are of the form
$$f(\mathbf{x}) =\sum_{i=1}^n c_i k(\mathbf{x},\mathbf{x}_i)$$
i.e., they are finite linear combinations of functions $f_\mathbf{x_i}(\mathbf{x})=k(\mathbf{x},\mathbf{x_i})$. Thus, we're effectively asking if, given a Gaussian Process prior $GP(0,k(\mathbf{x},\mathbf{x}))$ on $C(X)$, for any function $f\in C(X)$ there is always a function $f^*$ in the (closure of the) space of all functions which can be generated by GPR, which is as close as desired to $f$.
The answer, for some particular kernels (including the classic Squared Exponential kernel, but not including the polynomial kernel), is yes. It can be proved that for such kernels $K(X)$ is dense in $C(X)$, i.e., for any $f\in C(X)$ and for any tolerance $\epsilon$, there is an $f^*$ in $K(X)$ such that $||f-f^*||_{\infty}<\epsilon$. Note the assumptions: $X$ is compact, $f$ is continuous and $k$ is a continuous kernel having the so-called universal approximation property. See here for a full proof in a more general (thus complicated) context.
This result is much less powerful than it looks  at first sight. Even if $f^*$ is in the (closure of the) space of the posterior means which can be generated by GPR, we haven't proved that it is the particular posterior mean returned by GPR, for a training set large enough, where of course the training set consists of noisy observations of $f$ at points $\mathbf{x}_1,\dots,\mathbf{x}_n$. We haven't even proved that the posterior mean returned by GPR converges at all, for $n \to \infty$! This is actually the second interpretation suggested by @Dougal. The answer to this question depends on the answer to the first question: if there isn't any function $f^*$ in the RKHS which is a "good approximation" to $f$, of course we cannot hope that the posterior mean returned by GPR converges to it. However, it's a different question. If you would like to have an answer to this question too, please ask a new question.
Comment: great answer! was the follow-up question ever asked?


How to detect double-byte numbers

Question: I have to check strings in Japanese that are encoded in double-byte characters (naturally the files aren't in Unicode and I have to keep them in Shift-JIS). Many of these strings contain digits that are also double byte characters, (123456789) instead of standard single-byte digits (0-9). As such, the usual methods of searching for digits won't work (using [0-9] in regex, or \d for example).
The only way I've found to make it work is to create a tuple and iterate over the tuple in a string to look for a match, but is there a more effective way of doing this?
This is an example of the output I get when searching for double byte numbers:
>>> s = "234"  # "2" is a double-byte integer
>>> if u"2" in s:
      print "y"

>>> if u"2" in s:
      print "y"

    y
>>> print s[0]

>>> print s[:2]
    2
>>> print s[:3]
    23

Any advice would be greatly appreciated!
Comment: convert the string to unicode, search with a unicode regex, do whatever it is you need with the string, convert back to shift-jis...
Comment: Like @isedev already said, make sure you always work in unicode in Python (not UTF8/16). You can then use the [`unicodedata`](https://docs.python.org/2/library/unicodedata.html) module to give you information about the characters, for example: `unicodedata.numeric(u'1')` => `1.0` or `unicodedata.name(u'1')` => `'FULLWIDTH DIGIT ONE'` or `unicodedata.digit(u'1')` => `1`
Comment: I've tried that before but with limited success. All of Shift-JIS can convert to Unicode but not the other way around. I'll try it again.
Comment: @Tensigh I think you're confusing Unicode and UTF encodings. You can't output Unicode from Python (or any language) to a file, the network, STDOUT, etc.. You only ever can output a bytestring, which will need to be encoded in an encoding like UTF-8.
Answer: First of all, the comments are right: for the sake of your sanity, you should only ever work with unicode inside your Python code, decoding from Shift-JIS that comes in, and encoding back to Shift-JIS if that's what you need to output:
text = incoming_bytes.decode("shift_jis")
# ... do stuff ...
outgoing_bytes = text.encode("shift_jis")

See: Convert text at the border.
Now that you're doing it right re: unicode and encoded bytestrings, it's straightforward to get either "any digit" or "any double width digit" with a regex:
>>> import re
>>> s = u"234"
>>> digit = re.compile(r"\d", re.U)
>>> for d in re.findall(digit, s):
...     print d,
...
2 3 4
>>> wdigit = re.compile(u"[0-9]+")
>>> for wd in re.findall(wdigit, s):
...     print wd,
...
2

In case the re.U flag is unfamiliar to you, it's documented here.
Comment: Oh, `shift_jis` is an *encoding*! For some reason I was under the assumption it was a JavaScript framework. Now I feel stupid :) Either way, great answer!
Answer: I had a similar problem when facing Japanese two-byte characters and one relatively easy way to deal with the characters that I found is to transform them using the simple Unicode numbers (at least for processing them, if you want to keep the document as it is):
ord("2")

will return
65298

which is 65248 points away from the one-byte characters 2. So converting back can be done using:
def convert_two_byte_numbers(character: str):
    if ord(character) in range(65296, 65306):
        return chr(ord(character) - 65248)
    else:
        return character

If, like me, you also need to convert two-byte letters, add the same thing for the ranges (65313, 65339) and (65345, 65371).

How to detect double-byte numbers


SSH attack by IP that is blocked

Question: I run a CentOS 5.7 64bit server which has a strange issue.
While I was watching my logs at /var/log/secure I noticed that one strange IP was trying to connect to ssh with a lot of strange usernames.
Output of the log: http://pastebin.com/raw.php?i=3uYjPrLL
I run fail2ban which had already blocked this IP, and I also blocked this IP again manually via iptables.
Running iptables -n -L I got this output:
Chain fail2ban-SSH (1 references)
target     prot opt source               destination
DROP       all  --  184.108.40.206       0.0.0.0/0
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

So the block is in place. Iptables is also running, and I have blocked many IP's via iptables already, and those blocks are all working fine.
But somehow this IP is able to get to my machine. Any idea how this is possible?
Comment: The top of the output is missing, so we can't be sure that it starts with rule 1.  Could you ensure that **all** the output of the iptables command makes it into your pastebin?  And can you confirm what port you're running sshd on?
Comment: Perhaps the `fail2ban-SSH` chain is never being invoked, or is invoked at the wrong stage of processing.  We'll need to see the output of `iptables -L -n -v` to say anything useful.
Comment: This is the output: http://pastebin.com/raw.php?i=kxYGc6Gs
Comment: I have updated the pastebin file, now shows full output. http://pastebin.com/raw.php?i=kxYGc6Gs its a couple thousand lines as I recently had to block a whole bot network that was flooding my site.
Comment: ssh is running on port 2222
Answer: The issue is that your fail2ban-SSH chain is being applied to traffic to port 22, which isn't where your sshd is listening.  So fail2ban picks up the failures from the auth logs, and correctly updates the refusal chain.  But ssh traffic is never sent to that chain, so your malfeasor, who is now blocked from talking to port 22, is still able to talk to sshd on 2222.
Assuming you're using standard CentOS /etc/sysconfig/iptables, you need to change the line in the filter section that currently says something like
-A INPUT -p tcp --dport 22 -j fail2ban-SSH

to say
-A INPUT -p tcp --dport 2222 -j fail2ban-SSH

As for your manual drop, you have added it after the lines that say
 689M  126G ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED

and
 0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:2222 state NEW

so it will simply never get invoked to limit new traffic to port 2222, or subsequent packets in any such connection, as those have already been permitted.  The order of rules is vital in iptables, because first dispositive match wins.
Comment: Thank you, I have changed the default ssh port in the jail.conf file, that worked.

SSH attack by IP that is blocked


Trocar cor de imagem ou imagem em loja virtual

Question: Colegas.
Tenho visto em algumas lojas virtuais que existe o recurso de mudar as cores do produto. Como eu faria para que ao clicar em uma determinada cor, o produto fosse alterado sem refresh? veja um modelo: lapupa.com.br/539sl
Answer: Podes fazer assim, tendo em conta que isto obviamente não é o mesmo produto nem cores, mas a lógica será esta:

const prod_colors = {blue: 'https://cdn.mensagenscomamor.com/resize/400x225/content/images/int/imagens_de_deus.jpg', green: 'http://cdn.mixme.com.br/wp-content/uploads/2016/01/disney5.jpg', red: 'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTQJ8oMypN2S5RyM1S9zKxO3AOBc1UNT_EanYOIRYWK1evZVaj5'}

    for(var color in prod_colors) { // adicionar dinamicamente as cores que temos à disposição ao nosso select
       $('.colors').append('

');
    }
    $('.colors div').on('click', function() {
      var img_cor = $(this).data('image');
      $('.img_dinamic').prop('src', img_cor);
    });
.colors div {
  width: 20px;
  height: 20px;
  float: left;
}

Comment: Obrigado pela resposta Miguel, mas na verdade gostaria de algo parecido com esse modelo: http://www.lapupa.com.br/539sl
Comment: @Fox.11 na verdade a lógica é a mesma mas vai ser no click de divs em vez de estar num select, podias ter posto essa especificação na pergunta, agora não tenho muito tempo para fazer essa alteração, talvez mais tarde consiga
Comment: Obrigado Miguel. Funcionou.
Comment: @Fox.11 de nada, ainda bem


Using Rails 5 and minitest, how can I access a record that was created in the test?

Question: I have this test that was passing before I switched the Note table to use UUID:
test "SHOULD create note AND redirect to Notes#index(SINCE null folder_id) WHEN only body is provided IF logged in as account:owner" do
  sign_in @user
  assert_difference('@user.account.notes.count') do
    post notes_url(@user.account.hash_id), params: { note: { body: @note_by_user_no_folder.body } }
  end
  assert_redirected_to notes_url(@user.account.hash_id, anchor: Note.last.id)
end

But after switching to UUID, I'm getting the following failure error:
Failure:
NotesControllerTest#test_SHOULD_create_note_AND_redirect_to_Notes#index(SINCE_null_folder_id)_WHEN_only_body_is_provided_IF_logged_in_as_account:owner [/Users/chris/Dropbox/Repositories/keepshelf/test/controllers/notes_controller_test.rb:117]:
Expected response to be a redirect to <http://www.example.com/11111111/notes#9dc409ff-14cc-5f64-8f5f-08e487f583ee> but was a redirect to <http://www.example.com/11111111/notes#34dac6b7-46af-4c5c-bff7-760ffa77edf6>.
Expected "http://www.example.com/11111111/notes#9dc409ff-14cc-5f64-8f5f-08e487f583ee" to be === "http://www.example.com/11111111/notes#34dac6b7-46af-4c5c-bff7-760ffa77edf6".

I take this as that since the UUID's do not follow an order, that the new Note I am creating in the "post notes_url(..." does not end up being the "last" one that Note.last.id finds.
How can I set the anchor: to record_that_was_just_created.id ?
Comment: IMHO, its time to take a step back and consider that may be your test is incorrect :) you shouldn't depend on increment IDs to verify results anyway. A better test would be to check the contents of the note you are writing and see if it appears on the note page. That being said, if you absolutely must, you can sort the notes by `created_at`  timestamp, get the ID and take it from there..
Comment: You can try finding the last created record using `created_at` (but in db it is rounded to seconds so a few of them might end up with the same time). Or you can pass in a uniq attribute and use `find_by` for that attribute.
Comment: thanks. doing Note.order(created_at: :desc).last.id is not being consistent (I assume for the reason you describe). i don't know how i would do a find_by without having access to the record that was just created.
Comment: When you call `post` in your test, do you not know what'll be in the params? Say  `{ body: "special body" }` and then just `find_by(body: "special body")`.
Answer: I figured this out. apparently there is a way to access the controller's instance variables in the test so I got it to work by changing the assert_redirected_to to
assert_redirected_to notes_url(@user.account.hash_id, anchor: controller.instance_variable_get(:@note).id)

Answer: Late answer here, I'm glad you got the result you need!
... in case anyone else reads this looking for the test practices ...
The short answer is - you should always know what data is being used in the test ... because you make it.  The most common 3 ways ...
In the setup method where you

Load a fixture @account = Accounts(:first)  (needs matching entry in yaml file)
Call factorybot gem (see thoughtbot's page for how to)
Explicitly write @account = @user.account.build(field: value, field2: value)

So, you have the literal answer to your question - it's bad practice to test against uncertain data - Shaunak was saying that too.
The above is probably enough - but your detail oriented testing should be in unit tests - where you are not calling against db & making your tests the slowest possible version.  Your integration level stuff should just test that creation was successful - you already know the data going in there works.
For the best experience you probably want unit tests something from the 3 methods above in setup & use @account in the test like so to test against the validations you are about to create ...
So the unit test would be ...
setup
  @account = @user.account.build  # avoid hitting db unnecessarily versus create
  @account.field = value
  @account.field2 = value2
end

def test_details_pass_activerecord_validations
  signin @user
  @account.test_specific_fields = value  # stuff not all the tests use
  assert @account.valid?  # trigger all the activerecord validations, but not db
end

From there your integration ...
test "SHOULD create note AND redirect to Notes#index(SINCE null folder_id) WHEN only body is provided IF logged in as account:owner" do
  # Your setup method above should have most of the intialization
  # ... basically @account = @user.account .note would be setup, but not inserted

  signin @user
  assert_difference('@user.account.notes.count') do
    post notes_url(@account), params: { note: { body: @account.note.body } }
  end
  assert_redirected_to notes_url(@account, anchor: @account.whatever_field)
end


proof/explanation of Mann-Whitney U calculation

Question: Brief example of Mann-Whitney U statistic. Imagine of having an series of As and Bs, e.g.:
A B A A B

This could represent the results of a race, where a member of Team A got the best result, a member of Team B second best, a member of Team A third best and so on. For this particular statistic, order is descendig, like so:
A B A A B
5 4 3 2 1 <-- worst result, 1 point
^
|
+----- best result, 5 points

U is then calculated as the number of wins in pairwise contests of members of Team A against Team B.
In this case, A-who-got-1st place beats 2 Bs, and As in 3rd and 4th position beat a single B respectively; hence the U statistic is 4.
Now, the wiki page introduces a second, much quicker method:
$$
{\displaystyle U_{A}=R_{A}-{n_{A}(n_{A}+1) \over 2}\,\!}
$$
Where $R_A$ is the sum of the ranks of $A$ (5+3+2=10) and $n_A$ is the size of $A$ (3). In this case:
$$
U_{A}= 10 - 6 = 4
$$
What is the way of deriving the quicker formula? I tried to pick up pencil and paper but failed, and each book on google books (plus the original paper) just writes it without any note/demonstration, as if it were obvious to even the most naive reader.
I suspect combinatorics is involved, but I cannot understand how.
Answer: Let $A_1<\cdots< A_{n_A}$ be the 'scores' of the $n_A$ members of team $A$, ordered from worst (lowest rank) to best (highest rank), and $B_1<\cdots<B_{n_B}$ be the scores of the $n_B$ members of team $B$, also ordered from worst to best.
One way to compute the rank of a given member of team $A$ is to take that member's rank within team $A$, and add the number of members of team $B$ who scored worse. For example the worst team member has score $A_1$ and has rank $1$ within team $A$, and we boost this within-$A$ rank by adding the number of  members in team $B$ who performed worse. If nobody in team $B$ did worse, then the rank stays at $1$. If one person in team $B$ did worse, then the rank increases to $2$, and so on.
Summing over each member of team $A$ gives the total sum of ranks of members of $A$:
$$
R_A = \sum_{i=1}^{n_A} \left( i + \sum_{j=1}^{n_B} I(B_j < A_i) \right)
$$
which simplifies
to
$$
R_A=\sum_{i=1}^{n_A}  i + \sum_{i=1}^{n_A}\sum_{j=1}^{n_B} I(B_j<A_i)
=\frac{n_A(n_A+1)}2 + U_A
$$
since the sum $\displaystyle \sum_{i=1}^{n_A}\sum_{j=1}^{n_B} I(B_j<A_i)$ is precisely the number of pairwise contests between $A$ and $B$ in which the $A$ member beats the $B$ member.
Comment: Ah! That was  clever. I guess I would like to know how you got the intuition, but I suppose those are things that cannot be teached.
Comment: @tofregato This was my thought process: When I read "the number of pairwise contests in which $A_i$ beats $B_j$" I think of the double sum $\sum_i\sum_j I(B_j<A_i)$; and the expression $n_A(n_A +1)/2$ is exactly the sum of integers $1,\ldots, n_A$. The tricky part is coming up with a story to explain why these two add up to $R_A$ :)


Proof that the composition of two contractions on the same metric space (X,d) is also a contraction

Question: I am required to prove that given the metric space $(X,d)$, a contraction  $T : X \to X$ and another contraction $S : X \to X$, the compositions $T \circ S$ and $S \circ T$ are also contractions.
I started by assuming $Ct$ and $Cs$ the constants of the contractions for $T$ and $S$ respectively.
 For $S \circ T = S\ Tx$:
$d(Tx, Ty) \leqslant Ct\cdot d(x,y)$. I know that now I have to apply $S$ to this inequality, but I'm kind of stuck here.
Any help would be much appreciated.
Thanks!
Comment: Hint: start with $d(STx, STy) \leq C_s d(Tx,Ty).$ Can you go on?
Comment: Yeah, I think you're right. If I start this way, I can go one step further with the inequality and say that  d(STx,STy)≤Csd(Tx,Ty)≤CsCt*d(x,y). Having C = CsCt in(0,1), now I have that d(STx,STy)≤C*d(x,y). And it should be done, right? Thanks a lot!
Comment: Yes, that's correct.
Answer: Indeed, for all $x,y \in X$: $d(S \circ T(x), S \circ T(y)) = d(S(T(x)), S(T(y)) \le C_s \cdot d(T(x), T(y))$ (applying the property for $S$ for $T(x)$ and $T(y)$) $\le C_s \cdot ( C_t \cdot d(x,y)) = (C_s \cdot C_t) \cdot d(x,y)$.
This shows that $S \circ T$ is a contraction with constant $C_s C_t < 1$ (if both $C_s, C_t < 1$).
The exact same constant can be found for $T \circ S$, applying, using the essentially same argument.


extremal problem-how to check istrong minima,maxima condition

Question: The functional $I[y(x)]=\int_{0}^{2}(xy^{'}+y^{'2})dx,y(0)=1,y(2)=0$
possess
a.strong minima
b.strong maxima
c.strong maxima but not weak minima
d.weak maxima but not strong minima
How do we show if the functiona is strong minima,maxima..how do we prove this?
what all we have to check?
Answer: It has Strong minima.
Legendre Condition: $F_{y'y'}$ (differentiate $F$ w.r.t $y'$ twice) $>0$ for every $y$ then strong minima and if$ F_{y'y'}<0$ for every $y'$ then Strong maxima.
for  $>0$ for some $y'$ close to $p=(dy/dx, y\text{ is extremal})$ weak minima and for $<0$ for some $y'$ close to $p=(dy/dx, y\text{ is extremal})$ weak maxima
Comment: @user30567692 I tried to edit your answer but the I could not understand the second half please try to use LATEX
Comment: In your example, Fy'y' = 2>0 for every y'. Therefore it is strong minima. Let us assume thet for some problem your Fy'y' = y'+x, Now its sign is not clear and it depend on sign of p=dy/dx (where y is extremal) and range of x, So it is definitaley week ( maxima or minima will depend on sign)


Versioned storage for large files (PSDs, FLVs etc)

Question: We're currently scouting for solutions to a versioning/storage problem for large creative works. The designers themselves seem to want SVN, but this seems like an inappropriate mechanism. Files are expected to be in the 10mb-200mb range, they will be revised several times during the course of a project, then the final copy archived and the revisions erased.
NOTE: We're required to use an external SVN provider for internal reasons, but this will not be the case for a solution other than SVN; we will need a local solution for this.
So, I would like to know, does anyone currently have an internally hosted solution for a creative/design department, and if so, what software/setup are you using?
Thanks guys, Ehtyar.
Answer: For a design house, Adobe Version Cue is probably ideal. It is designed to work with version controlling large images.
I'd recommend against SVN (or any other version control system) for large binary files because there is no expire option. Storage can become a fairly big issue unless you very critically manage the repositories so you can remove them / archive them after the projects are finished. SVN will not slow down when the repos is huge (our code one with a few gig commits files as quick as a new one) but they never stop growing.
Answer: I would use Amazon S3 with S3fox.
You can create a container for each of your developer, you can create instant public or password protected download links for your clients.
SVN is almost useless in your case, large files will take ages to put into repository if it won't totally break the whole thing. SVN can store binary but it is not meant to (it can't tell if one pixel is different unlike text files) do that. Since it will try to process and update its database on each commit, it can be errorful. I wouldn't rely on it.
S3 will cost you $1 per 10GB. S3fox is free. Your designers will be happy about it, only thing is that each time they have to rename the file themselves, you can use;
PROJECT4_HOMENY_2009_09_16_20_41_Michael_v1.jpg
This naming will sort the files nicely (groups it by project, sorts it by date).
Comment: Thanks for your suggestion Devrim +1. Unfortunately, we can't use it. Despite my having my boss proof read my question, it turns out an externally hosted solution is unacceptable due to bandwidth constraints. I'm sorry for the mixup and I really appreciate your response.
Answer: As somebody looking for a similar solution for video project files, I agree that SVN isnt really the solution, and I dont think Git is either. Ive been looking at couchDB actually. A UI needs to be coded for it (but can be in Javascript or something) but its a document database so i think conceptually it works better. AND its designed to work with binary blobs. So I think it would be good with performance.
Might be something to think about.
Comment: Thanks for the reply Mark. Unfortunately we don't have the time or resources to develop our own solution, though after checking out CouchDB I certainly see the merit of your suggestion. +1 from me.
Answer: for psd's I second the use of version cue. subversion is great, but it has it's own issues with large binary files.
Answer: You could also try Alfresco. Using Adobe Drive 2.2, you can mount the Alfresco DAM in the Finder and right click to show versions, check out and check in files.
Answer: OP is missing an important information, how big are the repos expected to be, i.e. what is the expected size of all files under change control?
Just use Subversion? SVN in the current versions has no problem with large (a few gigabytes) repositories. If needed, you could always split your data over multiple SVN repos / servers. For Windows-based servers, I really like VisualSVN Server.
If you're more or less exclusively using Unix and OS X machines, then take a look at Git. I don't know if it has user-friendly GUIs, shell integration et cetera available on Unix / OS X. What I do know is that Git's underlying versioning and crypto architecture is simple yet very good, so I personally would have no problem entrusting several gigabytes of data to Git.
Comment: Git is not suitable. I tried committing a 1.5GB SQL file to it, then updating it. I had data loss.
Comment: @dotwaffle: Good catch. On the other hand, it could be fixed in more recent Git builds, or more likely it could be a platform-specific issue, see http://thread.gmane.org/gmane.comp.version-control.git/120057
Answer: Adobe Version Cue - CS3 works better than CS4 in my experience. I'd love to rave about it, but it has plenty of quirks (server can't be dual homed, serious Bridge CS4/Adobe Drive CS4 issues, performance bugs ...I could go on) - but it's still better than a vanilla SVN repo, and handles thumbnails and previews of both images and videos. Not tried adding a 1gb video to it, but would be interested to hear what your experience was.
Answer: Another one to look into depending on the type of assets is AlienBrain.  Like Adobe Version Cue it's made for digital assets and creative workflows and integrates into all the major 2d and 3d applications.


What are the best metrics for examining the separateness of clusters?

Question: I'm working on a new clustering approach. My algorithm has not any intra-class comparison; it only uses some inter-class comparison to decide whether the iteration continues. This lack of criterion causes my algorithm to stop very soon ! Therefore, I'm looking for a robust metric to use it as a criterion for evaluating the intra-class heterogeneity of clusters based on their neighbors. Is there such a metric?
Comment: Again, the most common questions: What is your data, is it real-values, structured, etc...? Also, if you have inter-class comparison (point-by-point) you commenly also have intra-class comparison. I am afraid we need a bit more details here.
Comment: Yes, Dunn's index is among the many. You have to consider a number of most prominant of them (their formulas) and to select one which you think will do. Maybe Silhouette index is what you want. It's you who decides.
Comment: @pAt84 thank you so much for the reply. My data are the images (pixel values) which are real values (between 0-255). Nevertheless, my algorithm is not a pure clustering algorithm. These kinds of algorithm in image processing are known as segmentation algorithm, with which homogeneous image objects are grouped together and then these image segments are used for classification. (Continued...)
Comment: To do this, my algorithm uses three inter-class homogeneity criteria for checking the continuation of iteration for generating image objects. Defining a intra-class comparison criterion for a segmentation algorithm is usually not necessary, but having such a criterion could enhance the capability of the algorithm. Thank you
Comment: Are you speaking of some internal clustering criterion ([pt 3](http://stats.stackexchange.com/a/195481/3277))? If yes, they are so many! Neither one is "robust" in the sense "universal".
Comment: @ttnphns thank you so much for the help. Yes, this criterion is more or less close to that I desire. As I know, some indexes such as " Dunn index " is also of this category. Am I right? Do you think these indexes could of some helps for my case? Thank you
Comment: @ttnphns I'm so grateful for valuable suggestion. I will test the Silhouette index to see its effectiveness in my application.
Comment: I did actually not know these, nice work ttnphns. :)

May I add a question: one of these measures is eventually going to work in keeping the algorithm running -- the "why" is a different question. But who says these clusters may not all lie close to each other or on top of each other in the space that matters for a proper clustering?
Comment: Did ttnphns ideas help you? Then it should be turned into an answer and rewarded. Or did they not and you still have the same problem?
Answer: You are talking about semantic segmentation, I suppose. Don't worry, I know a thing or two about computer vision. ;)
Personally I would not use or build such clustering algorithms anymore. Unsupervised Deep Learning with CNNs or stacks of RBMs do a much better job these days. I have used this for image segmentation and it has shown much more promising results than coming up with your own clustering algorithm.
I assume you actually segmented the whole image in different parts and not only one object (which would make this easy) but I will stick with the first explaination. There is not really all that much you can do here. You could use a bag-of-words representation for each image (how many pixels fall into each cluster) and compare those (k-means comes to mind). [Won't work, see discussion below]
What also comes to mind: If you know which segment is which, i.e. you can achieve a 1-to-1 matching of all segments of one image to another (bijective relationship), you could compare, e.g. the color values in the patches. If you do not know anything about the relationship, then this could still be done by finding the closest matches of segmentation patches. However, this usually ends up in some Simulated Annealing optimization problem and will be very slow. If the segments were already classified into their meaningful categories, there might be more you can do but I doubt they are.
If you only segmented a single object in each image and it is centered, then just devide the area of intersection by the area of the union (pascal measure.).
Comment: Thank you so much for your concise help. It seems you know more than me  about image segmentation. :) . I segment an image into several objects. That is, whole the image is segmented. I have not any prior knowledge about the image objects and their meaning as a real-world object. The fact is that if the process in my algorithm continues for more iterations, some meaningless, small objects merge together and create meaningful ones. For this reason, I think I should have a metric to tell me how much these objects differ from each other at each iteration.
Comment: Then testing the bag-of-words solution is your best shot, I think.

Which segmentation methods do you use? I assume superpixels are in there?
Comment: @ pAt84 thanks again. I will scrutinize bag-of-words solution. My algorithm is based on Watershed segmentation, but I have modified and enhanced it completely. No, I'm not doing super-pixel analysis.
Comment: Actually the bag-of-words solution won't do the trick either because you need to know which segment in one image belongs to which segment in another. The only way you can really do this is by classifying them -- given one patch search the closest patches in all images (RGB distance or something like this). Assume this is your positive class and all others are the negative class (one~vs~all). Then use an SVM to learn how to distinguish. When done label your patches and from there you can explore the clustering algorithms we discussed earlier.
Comment: Thank you. No, I'm not going to match the segments of two images. This comparison is not made at all in my algorithm. I just want to know that how much each created image object is separate (or heterogeneous) from its neighbors. If this separateness is significance, and the inter-class criteria don't meet, the iteration stops, unless it continues and the conditions will be considered again.
Comment: As long as you do not want to match the patches, I doubt a method even exists. You might have to fallback on other image processing than semantic segmentation. How do you compute your inter-class criteria? Maybe there is way in through that.
Comment: Thank you. These criteria are some expressions made according to the variance, entropy, and some model-based concepts in image processing and object detection. At each iteration, pixels merge together based on these criteria. Gradually, these pixels create image objects at subsequent iterations, and then objects merge together or remaining pixels if the criteria meet. As it is clear, there is no any criteria for intra-class heterogeneity examination.
Comment: Well, probabalistic models also won't help, since at some point you need a matching there as well. The only real distance measure, based on the segments, you could compute is a comparison of the form of the segments in each image. Maybe there will be sky in one image and hence a big segment on the top of the image c.f. an inside scene where you do not have this. But this would be a very very weak criteria. Is there any knowledge you can extract from the segmentation algorithm itself? Convergence rates, etc.? It might behave differently for some clusters.
Comment: Thank you for the time you took to help me. I'm so grateful. It's a good idea to consider the convergence rates or other change-tracing measures. It could finally help me.


Water resting in a sin curve

Question: Imagine the sin function as it dips under the $x$ axis and let that part of the curve be filled with (2-dimensional) "water" up to the axis.
We can find the amount of water that fills this area by
$$\int _{\pi }^{2\pi}\left|\sin \left(x\right)\right|dx=2$$
let the sin function be multiplied by a factor of $\left(\frac12\right)^n$ for some $n$ so that by changing $n$, the sin waves are stretched.  Suppose we start out with $n=0$, fill the dip to the axis with $2$ square units of water and then change $n$.  The water level will rise or fall depending on the change in $n$.

At what height or $x$-values will the water lie in terms of $n$?

This is dealing with physical measurements so always calculate the area positively.
Comment: How much time are you going to give us before you post a solution?
Answer: Let me consider the case where the sine wave is amplified by factors $a_n$: this covers your case $a_n = (\frac{1}{2})^n$.
So we start with a constant volume of water, the top surface of which lies on the segment $[\pi; 2\pi]$, and we start stretching the sine wave.
Then, the following "conservation of water volume" equation needs to hold
$$ a_n \int_{\pi + \epsilon}^{2 \pi - \epsilon} sin(x) \mathrm{d}x = 2$$
as $\epsilon$ quantifies  the horizontal changes in segment representing the top water surface.
Solving for $\epsilon$ one gets $$\epsilon = arccos (\frac{1}{a_n}) $$ and the water level rised, or descended, to $sin(\pi + \epsilon)$.
Now, if the $a_n$ are increasing, the water level will continue decreasing, and the water will remain contained in the half sine wave where was originally poured in.
If on the other hand the $a_n$ are decreasing, one has to consider the condition $$ \lvert \epsilon \rvert < \frac{\pi}{2}$$ This represents the point at which the water level has reached the peaks of the neighbouring half-wave, after which the water will pour into the neighbouring valleys, and the level remain constant at the value $a_n$ (peak height of the sine wave).

Water resting in a sin curve


Como funcionam funções anônimas?

Question: Sei que são funções que não tem o nome especificado, mas qual a finalidade?

É possível recursividade com funções anônimas? Ex: Sequência de Fibonacci.

(function(x, y) {
  alert(x + y);
})(5, 5); // Função para somar duas variáveis
Answer: Respondendo literalmente à sua pergunta "Como funções anônimas funcionam?":
Funções anônimas são muito importantes para entender alguns dos conceitos do funcionamento da linguagem JavaScript, são funções que não dependem de nomes, somente são declaradas e armazenadas em uma variável.
Esta é uma função anônima: function(){alert('foo');
Uma das melhores práticas para usa-la consiste em criar JavaScript Closures, pois:

"Conhecer JavaScript e não conhecer Closures, é a mesma coisa que conhecer Java e não conhecer Classes."

Por isso é de suma importância o entendimento das Closures e de Funções Anônimas.
Definição de Closures:

Closure em inglês significa encerramento, no sentido de guardar, pôr em um lugar fechado.

Ou seja, seria armazenar uma variável em uma função que pode ter parâmetros ou não. Ela pode retornar um valor e torna-lo imutável, ou então apenas realizar comandos sem retorno.
Explicação com Exemplos:
Veja como funcionaria uma função anônima simples com uma função sem argumentos:
var anonima = function(){ alert('executou') };
anonima(); //executa a função anônima

Agora uma com parâmetro:
var anonima = function(n){ alert(n) };
anonima(2);

Podemos também criar uma closure com funções anônimas, como por exemplo uma soma de dois números:
    var anonima = function(number1){
  return function(number2){ alert(number1+number2) };
};
var closure = anonima(2); //salva na variavel closure a funcao que manda o parâmetro number1
closure(3); //manda o parâmetro number2 e executa a função final

Closures se torna ótimo para guardar em variáveis algumas operações que chamam funções diferentes retornando um resultado de operação ou função.
Outra coisa muito boa das Closures seria a criação de classes encapsuladas, como por exemplo, uma classe de uma Empresa:
function Empresa(nome){
    //privates
    var _funcionarios       = [];
    var _ordenaFuncionarios = function(){
        return _funcionarios.sort();
    }
    //public's
    return {
        adicionaFuncionario: function(funcionario) {
            _funcionarios.push(funcionario);
            //return this;
        },
        meusFuncionarios: function(){
            return _ordenaFuncionarios(_funcionarios).join(", ");
        }
    };
}

E veja como se torna facil adicionar funcionários, e imprimir eles ordenados:
var p = new Empresa("Foo Ltda");
p.adicionaFuncionario("João da Silva");
p.adicionaFuncionario("Maria da Rosa");
alert(p.meusFuncionarios()); //João da Silva, Maria da Rosa.

Repare que você tem "return this" comentado, teste descomentar e assim você vai poder utilizar encadeamento de métodos desta forma:
var p = new Empresa("Foo Ltda");
alert(p.adicionaFuncionario("João da Silva")
    .adicionaFuncionario("Maria da Rosa")
    .meusFuncionarios()); //Joao da Silva, Maria da Rosa

Outra coisa, você pode evitar a criação de variáveis globais utilizando Closures, da seguinte forma:
cor = "azul";

(function(){ //função anônima
    var cor = "#FF0000";
    document.body.style.background = cor; //deixa o fundo da pagina vermelho
})();
alert(cor); //azul

Javascript closures são muito bons para muita coisa, funções anônimas também. Como podes ver, vale a pena dar uma estudada nisso :)
Comment: Acho que você não está entendendo muito bem [o que são closures](http://pt.stackoverflow.com/q/1859/215). Ou talvez esteja - a segunda metade da sua resposta descreve closures muito bem. Entretanto, isso que você se refere como "armazenar uma função numa variável" não se trata de closures, mas de ["funções de primeira classe"](http://pt.stackoverflow.com/q/2783/215). Em outras palavras, uma linguagem pode ter funções de primeira classe mas não possuir escopo léxico - e portanto, não suportar closures.
Comment: Você quis dizer que as funções que eu adicionei no início que não eram encapsuladas não são closures?
Comment: `funcaoInterna` é um closure. As duas funções internas a `Empresa` também são. O resto não. Para ser um closure, a função tem que referenciar alguma variável do escopo léxico **acima** dela (ex.: quando `funcaoInterna` acessa `number1` - que pertence ao escopo léxico de `funcaoExterna`).
Comment: Tem um typo ali no primeiro exemplo, não? Acho que falta fechar `function(){alert('foo');` . . .
Answer: Você pode implementar usando recursividade sim, basta usar a própria variável a qual você atribuiu a função e chamá-la:
var fibonacci = function(num)
{
   if(num==1 || num==2)
       return 1;
   else
       return fibonacci(num-1) + fibonacci(num-2);
};

jsfiddle
Finalidades de uma função anônima
Passar como se fosse um objeto qualquer
A finalidade de uma função anônima é exatamente a de permitir passá-la como se fosse um objeto qualquer, que você pode atribuir a uma variável, independentemente de haver um nome para a função.
Protegendo variáveis usando uma função anônima
Proteger variáveis contra mal uso, é uma das finalidades que acabou se encontrando para funções anônimas. Seria o equivalente a criar membros privados, como é possível em várias linguagens.
No exemplo do fibonacci, se você quiser proteger a variável usada para atribuir a função, poderia fazer assim:
var fibonacci = (function() {
    var fnc = function(num)
    {
       if(num==1 || num==2)
           return 1;
       else
           return fnc(num-1) + fnc(num-2);
    };
    return fnc;
})();

Dessa forma, não teria como alterar a dependência interna da função depois desta já ter sido criada. Não será mais possível alterar a variável fnc, pois ela está dentro do contexto da função anônima, cuja referência se perde, logo após chamar a mesma.
Estrutura básica:
var obj = (function() {
    // declarações a serem protegidas
    var a, b, c;
    // retornando um objeto construído a partir de a, b e c
    return obj;
})();

Comment: Acho que a questão real era: *"Como é possível usar recursão em um método anônimo, já que esta não possui um nome?"*
Comment: E a parte sobre proteger variáveis dentro de uma função anônima? Eu menciono que a função se perde imediatamente após chamar a mesma... algo do tipo `(function () { })()`
Comment: acho que a questão não é sobre fibonacci mas sobre funções anonimas, o fibonacci foi um exemplo de caso de uso.
Comment: concordo, acho até que valia a edição do titulo :)
Comment: Não querendo ser pedante, mas quando você atribui uma função a uma variável ela não deixa de ser anônima? (i.e. você deu um nome pra ela) Sua resposta está tecnicamente correta, mas tudo o que foi descrito aqui seria igualmente possível com funções nomeadas.
Comment: @MiguelAngelo OK, nesse caso de fato há uma pequena vantagem. Embora seja possível fazer `(function nome() { })()` e **as variáveis dentro dela** continuariam protegidas, a função em si estaria acessível através do nome e poderia ser usada incorretamente.
Answer: Em JavaScript, funções são ditas "membros de primeira classe". Isso significa que você pode pode instanciá-las, atribuí-las a variáveis, ou mesmo criá-las dinamicamente em tempo de execução (nota: 99% do tempo eu não recomendo). Cada função instanciada é portando um objeto da classe Function.
Uma função anônima não é muito diferente de uma função nomeada. Essas duas definições são de fato equivalentes:
function foo() { return "bar"; }
var foo = function() { return "bar"; }

Há diferença?
Não. A aparente diferença (como apontado na resposta do @Gabriel Gartz) se dá pelo fato que em JavaScript as definições de variável são trazidas automaticamente pro topo do seu escopo léxico.
Isso significa que quando o interpretador vê:
console.log(naoAnonima()); // 'foo'
console.log(anonima()); // undefined

var anonima = function () {return 'bar';};
function naoAnonima() {return 'foo'; }

Ele automaticamente converte para:
var anonima; // A definição da variável veio pra cima, a atribuição não
function naoAnonima() {return 'foo'; } // A definição da função veio pra cima

console.log(naoAnonima()); // Aqui naoAnonima já está definida
console.log(anonima()); // A variavel anonima existe, mas ainda não aponta pra uma função

anonima = function () {return 'bar';}; // A partir daqui anonima refere-se a uma função

Para que serve?
Nem sempre você precisa de um nome pra sua função. É simples assim! Se você vai usar a função recém definida em um manipulador de eventos, ou num callback para Ajax, etc, não há necessidade de se colocar essa função numa variável/dar um nome pra ela. Apenas crie a função e atribua-a onde for necessário (primeira classe, lembra?).
window.onload = function() { /* essa função não precisa de um nome */ };

É possível recursividade?
Existe um truque mais de interesse teórico do que prático chamado "Y Combinator", que não vou demonstrar aqui, quem tiver interesse aqui tem alguns links explicativos (em inglês). Ele basicamente permite que a recursividade seja implementada sem nenhuma declaração de variável ou função. Ou seja, ao contrário das demais respostas - que "trapaceiam" um pouco, dando um nome pra sua função anônima (!) - essa solução funciona ainda que não exista nenhuma referência pra função em si.
Y(function (fac) {
    return function (n) {
        return n <= 2 ? n : n * fac(n - 1);
    };
})(5); // 120

Mas se essa "trapaça" for admitida (na prática, não existe muito benefício em soluções "espertas" - melhor que sejam claras e eficientes), então para se obter um efeito recursivo numa função anônima basta fazer com que a mesma receba como argumento uma função:
var fat = function(fn, n) {
    if ( n <= 2 )
        return n;
    return n * fn(n - 1);
};

...e passar ela própria como argumento em sua chamada!
fat(fat, 5); // 120

Ou seja, a função não é recursiva (pois você poderia chamá-la passando outra coisa como primeiro argumento), mas ela se comporta de forma recursiva.
Comment: +1 pelo Y combinator
Answer: Funções anonimas elas não tem uma identificação no escopo de execução do javascript, porém podem ser atribuídas a variáveis, ganhando tornando-se acessíveis apenas quando esta variável é acessível.
Exemplo:
console.log(naoAnonima()); // 'foo'
console.log(anonima()); // undefined

var anonima = function () {return 'bar';};
function naoAnonima() {return 'foo'; }

console.log(naoAnonima()); // 'foo'
console.log(anonima()); // 'bar'

Como pode ser visto no exemplo, a função anonima ela só está acessível assim que a variável também.
Se você não utilizar o modo estrito (use strict) você pode acessar sim a referencia de uma função anonima através da propriedade arguments.callee exposta no seu contexto.
Exemplo:
function () {
    arguments.callee; // Aqui está referencia pra sua função
};

Utilizando o modo estrito, isso vai te causar uma exceção.
Então se você for implementar o exemplo do fibonnaci, pode declarar primeiro uma variável que vai guardar a referencia da sua função anonima e usa-la dentro da função anonima.
var fib = function (n) {
   if (n <= 2) return 1;
   return fib(n - 1) + fib(n - 2);
};

Neste caso fib existe dentro da função anonima pois quando a função estiver sendo acessada por ela mesmo, a variável já foi atribuída. Permitindo a recursividade.
Uma maneira apenas de exemplo didático do ES3 era usar o arguments.callee para isso:
(function (n) {
   if (n <= 2) return 1;
   return arguments.callee(n - 1) + arguments.callee(n - 2);
})(10); // 55

Repare que não foi atribuída a função a nenhuma variável. Isso é, apos ela ter sido executada e finalizada, ela será marcada pelo garbage collector para ser eliminada, pois nesse caso não existe mais nenhuma referencia para ela.
No ES5 você não tem acesso a propriedade arguments.callee no modo estrito, mas você consegue esconder a função que aplica recursividade dentro de uma função anonima caso não queira expor esta. Exemplo:
(function (n) {
   // fib não está exposto
   return (function fib(n) {
     if (n <= 2) return 1;
     return fib(n - 1) + fib(n - 2);
   })(n);
})(10); // 55

Neste caso mesmo que você de um nome a função anonima, a sua função interna fib é inacessível.
Finalidade:
As funções anonimas existem para agilizar e simplificar a codificação, por exemplo, se você quer isolar um escopo de variáveis, pode simplesmente auto-executar uma função anonima pra isso.
É muito comum no javascript atribuir funções a propriedades ou passa-las como argumento, as funções anonimas simplificam a codificação sendo que você não precisa nomear-las para fazer essas atribuições, deixando seu código mais simples.
Comment: +1 pelo uso de `arguments.callee`. Embora na prática não seja recomendado, esse foi o único exemplo de função anônima recursiva em todas as respostas (as demais "trapaceavam" um pouco - dando um nome pra função anônima!).
Comment: Obrigado @mgibsonbr, coloquei apenas para fins didáticos mesmo, não recomendo o uso.
Comment: @mgibsonbr veja minha resposta agora não é mais trapaça e não uso o `arguments.callee` :P
Answer: Encaixa-se também na definição de Funcão de ordem superior em Javascript
Recebem uma ou mais funções como argumentos ou têm uma função como saída.
Através delas é possível criar o que são chamadas functions factories que são funções que a partir de outras funções
simples são capazes de realizar ações mais complexas.
O próprio contexto já nos diz também : Funções sem nome, além disso, ela inclui como principal característica o conceito de recursividade.

Como funcionam funções anônimas?


How can I practice in an apartment without annoying the neighbours?

Question: I live in an apartment and I find my current amp (a 15W solid-state) to be poorly suited to that. I can't turn it up without upsetting the neighbours, but at low volume it sounds horrible with any kind of distortion or other effects.
What should I look for that can help me produce a decent sound at the volume of, say, a slightly loud TV? If it's just a matter of finding a better amp, what characteristics should I pay attention to?
Comment: In another question you were asking about joining a band. Maybe one of the neighbors would like to jam along? :)
Comment: @Silver Light: That's not a bad idea. :) Alas, either everybody here knows how to play at bedroom volume levels or nobody plays. ;)
Comment: When I lived in an apartment building, bedroom volume meant you could hear whatever they were doing in the bedroom down the hall.
Comment: I'm not into electric guitars, but I've once stumbled upon this vid : http://www.youtube.com/watch?v=tBh-IugVG6c Hope it's of any help to you!
Answer: I think your best bet is to get something with a headphone out. Some amps will have them, although probably only solid state ones. A lot of the digital modeling /fx units will have it too (like Pod). Just don't blow your ears out!
Comment: PocketPod + Shure headphones = Practice anywhere.
Comment: high-quality headphones are awesome.
Comment: Another benefit of headphones over a quiet amp is they block out acoustic sound from the guitar - string buzz, the pick hitting the strings - which your audience never hears but can be distracting if you have to practice quietly.
Comment: Agreed. This is what I do. It's only useful for playing alone, of course, but you can scramble your brains to your hearts content with some GOOD headphones. Don't be discouraged if you headphones don't match the output of the amp though, for $2 you can get a converter for almost any combination, to make it work.
Answer: Most of the time I practice my electric guitars with out having them plugged in. I know a lot of guitarists that do this (even famous ones)
You can practice all styles like this - even metal. Distortion and amplification isn't necessary to learn the guitar.
Comment: True, and most times I don't plug in, but it gets pretty boring practicing without actual sounds *all* the time. :)
Comment: It is necessary if you want to work on your tone.
Answer: There are a bunch of things you can do; computers are definitely your friend in this scenario; a DAW of some kind, and some VST plugin's may solve your problem.
There are many brilliant free VST Amp simulators out there; Shred by Acmebargig is one of the better ones as is Nick Crow Lab (his Tubedriver can produce authentic sounding valve tones).   Of course there are the commercial products Guitar Rig and Amplitube which will get you just about any tone you'd like.
A low latency audio card will allow to run your guitar signal (via an adapter cable or a mixer) into the PC and through the Amp Sims, (the M-Audio  2469 is a good card for this and reasonably priced), this will allow you to drive/crank the simulators as loud as you'd like to get the tone you want; and control the overall volume with your PC, good speakers/monitors are a must for this.
Answer: If you have an iPhone or iPad, iRig and the Amplitube app are an inexpensive alternative to buying something like a Pocket POD.
If you have an iPad, you've absolutely, positively got to get GarageBand.
Comment: iRig and Amplitube for iPhone/iPad is amazing.  Allows me to practice anywhere at anytime.  I can even sit under the stars on the deck late at night when the kids are asleep and jam along to backing tracks.  Also, the ability to do multi track recording is great for coming up with ideas at anytime.
Answer: There are a number of small headphone guitar amps available that are fairly inexpensive, although I don't know how they sound. The Vox Amplug comes to mind, although I suspect it isn't as versatile as a regular amp. Another option would be to pick up a cheap multi-effects unit with headphone output.
Comment: Marshall makes something similar as well. This isn't *exactly* the one I had in mind, but you get the idea. http://www.guitarcenter.com/Marshall-MS-2-Micro-Stack-Mini-Amp-Practice-Amp-100037524-i1145911.gc?source=4WBING
Comment: I have a Vox Amplug and a 1Watt Marshall. For headphone usage the Vox wins, so usually the Marshall only comes out if I want to go sit in a park and decide to take an electric instead of an acoustic. Both good little amps though.
Comment: I have a Fender-flavored one, and it's quite handy for hotel-room jamming but lacks decent punch for headphone use.  I prefer my Pocket Pod for that.
Comment: i wasnt aware of this kind of gadget! thank you so much for the info! I used to have an electric guitar and never really played because I was too lazy to set everything up, so the acoustic guitar worked better for me. Now these miniamps might be the solution for my slackness.
Answer: I know of two amp-and-effects modeling apps for the iPhone/iPod Touch/iPad, both of which are great and allow you to get realistic amp tones through your headphones.  AmpKit and Amplitube both do a great job of simulating all the standard amp models and pedals, and they aren't very expensive.  I use and prefer AmpKit myself, and between the app and the guitar-to-iPhone interface, I spent a total of $50.
Answer: As I commented above, my go to method for quiet practice is a PocketPod with Shure headphones. But, who doesn't like plugging in to an amp every once in a while? I live in a house, but the neighbors are close. The amp I use is a Fender Super Champ XD, which is a 15w tube amp with some digital effects. It seemed quiet enough at low volumes, but your mileage may vary. If I were you, I would at least give one a listen at a music store and see if it can do what you need.
Answer: To build on the computer angle:
(for windows) two very respectable FREE amp sim downloads are:
VSTHOST (ugly, but is a host application for VST plugins) ( http://www.hermannseib.com/english/vsthost.htm )
and
Simuanalog (vst amp simulator and effects freeware) ( http://www.simulanalog.org/guitarsuite.htm )
Answer: I was answering this question recently for a friend of mine, only substitute "wife" for "neighbors." He was interested in taking up the electric guitar while at the same time remaining married.
The answer I came up with for him, specifically was a DigiTech RP255.
It is a multi-purpose item with all of this functionality in a single unit:

Amp / Cabinet modeler
Effects modeler
Expression pedal (for wah, volume pedal, other controls, etc.)
USB recording interface
Drum machine
20-second looper

Before I recommended it to him, I went to my local GC and played one through some headphones. I thought it sounded pretty good - and certainly outgunned my Pocket Pod for pure functionality. Is this (or something like it) the be all and and all of tone? Of course not. But this (or something like it) can provide all sorts of options for practicing while leaving your neighbor (or spouse!) in peace.
Comment: I had a similar problem and went with a similar solution - the Vox Tonelab amp modeler and multi-effects unit. Has a headphone out that works fine for practice. Plus it is working well for gigging as well. I can practice tunes with the exact amp and effects that I'm going to use. When I get in front of the guitar amp, I just need to get a clean sound and give it a little color in the tone. It isn't perfect for gigs, but it is SO easy to practice with and can sound like a Fender, Marshall, Hiwatt, Mesa - whatever. This is starting to sound like an ad, so I'll stop. :-)
Comment: @Frank Drake - I have your solution in an amp - a Vox Valvetronix! I love it, and when I need silence, I can just use the headphone jack. But my friend was looking for an inexpensive solution and this offered more than the Vox. I prefer the tube-infused tones of the Vox, but I would love the looper, drum machine, expression pedal, and USB interface of the DigiTech!
Comment: I want to try the amp some day (still haven't done this). I'd like to see if some of the artifacts that I don't like, go away. I'd have gone straight to the Vox amp, but I've got an old Carvin half stack and a Fender Twin - no more room (or money)! :-)
Comment: @Frank, the Valvetronix are really pretty spectacular, especially at the price point. It's the only amp I recommend to my students (at least until they're spending over $500 and looking at tubes). It's not as good as the real thing, but it's a ton of options at a great price.
Answer: If you are looking for a lower volume amp, look for lower wattage.  Keep in mind that wattage and volume are logarithmically related; So a 50W amp is twice as loud as a 5W amp, which is twice as loud as a .5W amp.
The route that I went was to get a 5W practice amp (Vox DA5), that has an attenuator in it (which can reduce the power down as far as .5W).  On top of that, the amp has a headphone jack in case I need to go completely silent.
Answer: Having lived in an apartment when learning guitar, it was painful. Using headphones works, but most days you just want to hear it from an amp like it was meant to be. Your only real solution is to try out some of those tiny lunchbox amps and see if they can fill that void. Another option is to start saving for a house, or find a friend who has one to jam out in.
Answer: I use a Mac and Native Instruments/ Garageband. Plug your guitar straight in and add headphones or just turn it down a bit.
I assume this'll work for PCs too tho of course there's no Garageband for them.
Answer: My answer would be to buy a small multi-effects unit specifically for the purpose of playing at home, with an "amp simulator" and plug it into your home stereo or something. You can get a pretty massive sound without it having to be loud even with a low-end effects box.
I use a cheap zoom effects box (actually because it has a fabulous digital tuner built-in) and if I want to play at home I plug that into the stereo. Don't have it any louder than you would a CD etc .. (ok maybe a bit ;-) )  gives you the flexibility of all the effects sounds plus because it's stereo (assuming you hve the speakers a few feet apart) you get that feeling of it being "large" when really it's not that loud.
If you do this, be sure to buy an effects unit with built in amp simulator, otherwise it'll have the "wasp in a paper bag" sound when you use the crunch/distortion
Comment: Yeah, I use a Zoom multi fx. It works through headphones. It works through a hifi. It works through a PA amp. Very flexible.
Comment: Ah good, I was a bit embarrassed about saying I use something so cheap (£40 here as opposed to £200-odd for a similar Boss thing) but those things are quite a good little package :-)
Comment: I can't see any reason to spend more. If that means I have cloth ears, then hooray for cloth ears. I've even been complimented on the tone of mine - playing crunchy chords through the Zoom to a clean amp.
Answer: Barring use of a headphone jack on yiur amp, there are some solutions available that will allow you to plug straight into your computer so that you can both use it to control volume as well as record the practice so that you can capture those neat little bits as you play around.
Answer: On the other hand, you could load your apartment full of soft things like curtains, blankets, sofas, carpets, etc.  Soft stuff will absorb more noise and allow you to turn up your amp just a little bit louder.  The more absorbent material you place in that room, the better "soundproofed" it will be.


how to merge two array in my self Pattern?

Question: I'm trying to combine 2 arrays in javascript into one.
var one=[11,22,33,44,55];
var two=[66,77,88,99,11];

i want combaine 2 above arraye in below Pattern:
three=[11,66,22,77,33,88,44,99,55,11];

how do merge 2 arrays in above Pattern?
Answer:  const result = [];
 for(var i = 0; i < Math.min(one.length, two.length); i++)
   result.push(one[i], two[i]);


How to implement Pushnotification in Android Phonegap

Question: I'm new to Phonegap. I've an application in which i wanted to add a person as a buddy & all the details will sit in to my database but as soon as i add him a message should send to that person in his android mobile (acts as external notification- status bar notification) who has this app installed. How will send him a message which acts as an external notification for him in android using phonegap.
Thanks in advance.. :)
Answer: To use Android push notifications, you have to implement an application that uses the Google Cloud Messaging service, which could be used by your PhoneGap app.
If you don't want to implement the application by yourself, you could use third party services, such as Urban Airship.
Hope this helps :)
Comment: Hi david, Thanks for the answer but that is there in android native app. i wanted to implement in phonegap. Can you please suggest me how will i implement in phonegap. Also there is a plugin in phonegap for pushnotification, i have implemented that using GCM but im not getting the overall flow of the functionality....
Comment: @user2003570 nope, if you implement the server to comunicate with GMC you can use it however you want (through Javascript AJAX calls according to your requirements), and if you use Urban Airship, it has a Javascript API (https://docs.urbanairship.com/display/DOCS/Client:+Phonegap:+Javascript+API)
Comment: @user2003570 You can implement native GCM for android and create a plugin for that in phonegap. I have implemented this in my application and it works really well.