calculate difference between 2 dates (most optimized)

Question: I'm creating a page where we can search github users. When username is entered all the repositories of given person are shown.For this I'm using github API. But this is how I am getting updated respository date.
"updated_at": "2024-02-09T10:17:53Z",

This is my code.

updated 4 days ago

So in place of 4 days, I am trying to change whatever the difference is.
Here's what I tried.
const updated = new Date("2024-02-09T10:17:53Z");
  const now = new Date();
  const diff = Math.floor((now - updated) / 1000);

  let updatedDate;
  if (diff < 60) {
    updatedDate = "just now";
  } else if (diff < 3600) {
    const minutes = Math.floor(diff / 60);
    updatedDate = `${minutes} minutes`;
  } else if (diff < 86400) {
    const hours = Math.floor(diff / 3600);
    updatedDate = `${hours} hours`;
  } else if (diff < 2592000) {
    const days = Math.floor(diff / 86400);
    updatedDate = `${days} days`;
  } else if (diff < 31536000) {
    const months = Math.floor(diff / 2592000);
    updatedDate = `${months} months`;
  } else {
    const years = Math.floor(diff / 31536000);
    updatedDate = `${years} years`;
  }

  console.log(updatedDate);

What should be the most optimized approach that accounts for if difference is minutes/hours or just now too?
Answer: Optimization prioritized over readability, making you save a few nanoseconds, maybe.

const updatedAgo = (dateString) => {
  const now = new Date();
  const pastDate = new Date(dateString);
  const secondsPast = Math.floor((now - pastDate) / 1000);

  const units = {
    year: 31104000,
    month: 2592000,
    day: 86400,
    hour: 3600,
    minute: 60
  };

  let unitAmount;
  for (const [unit, value] of Object.entries(units)) {
    const amount = Math.floor(secondsPast / value);
    if(amount > 0) {
      unitAmount = [unit, amount];
      break;
    }
  }

  if(unitAmount === undefined) {
    unitAmount = ['second', secondsPast];
  }

  return `Updated ${unitAmount[1]} ${unitAmount[0]}${unitAmount[1] !== 1 ? 's' : ''} ago`;
}

console.log(updatedAgo('2024-02-09T10:17:53Z'));
Comment: For better internationalization, consider replacing the `return` statement with ``return `Updated ${new Intl.RelativeTimeFormat("en", {numeric: "auto"}).format(-unitAmount[1], unitAmount[0])}`;``.


NodeJs api com promisses

Question: Estou desenvolvendo uma API em TypeScript com NodeJS e MariaDB; quando faço uma operação com o banco, logo abaixo possuo um if para verificar se ocorreu algum erro.
productDao.save({name:"Notebook Dell", price:"5000"}, function(err, res){
   if(err){
      //Código para caso algo dê errado.
   }else{
      //Código se tudo der certo.
   }
})

O caso é: Posso utilizar promises em uma API? Gostaria que ficasse algo assim:
productDao.save({name:"Notebook Dell", price:"5000"})
.then(res => {
   //Caso tudo dê certo.
})
.catch(err => {
   //Caso algo dê errado.
})

Porém, me pergunto, A padrão promise é ideal para uma API? Quais as possíveis complicações? Quais seriam as desvantagens e vantagens sobre esta arquitetura em uma API?
Answer: Podes usar Promises ou Callbacks "à moda antiga" como preferires. A abordagem com promises tem vantagens:

erros lançados dentro de uma promise chamam o catch e não param o script, ao contrário de uma função normal que pára a execução quando houver erros
a promise permite encadeamento e ser incluída em funções de alta ordem como o Promise.all

Em relação a API, é uma questão de preferência.
Comment: Sem falar que usando Promises o código fica bem mais legível :)

NodeJs api com promisses


How to use Cauchy's integral formula with more than one pole?

Question:
$$\int_{\gamma} \frac{z^2}{z(z-2)}, \quad \gamma(\theta) = 3e^{i\theta}, 0 \leq \theta \leq 2\pi$$

Cauchy's integral formula is given by:
$$\int\limits_{\gamma} \frac{f(z)}{(z-a)^{n+1}} = \frac{2\pi i}{n!} f^{(n)}(a)$$
And I can choose my holomorphic $f(z) = z^2$. But it doesn't seem like I can get my integral into a form like $(z - a)^n$ in the denominator. Am I missing some algebraic trick to do this?
Also, if $\gamma(\theta)$ was $e^{i\theta}$, then I could choose my holomorphic function to be $\frac{z^2}{z-2}$?
Comment: Isn't $\frac{z^2}{z(z-2)}=\frac{z}{z-2}$? (with $z=0$ being a removal singularity)
Comment: $\frac{z^2}{z\left(z-2\right)}=\frac{z}{z-2}$ so that you can take $f\left(z\right)=z$.
Comment: http://en.m.wikipedia.org/wiki/Residue_theorem
Comment: Oh, I didn't know we're allowed to cancel out fractions inside an integral. Thanks
Answer: We have
$$\dfrac{z^2}{z(z-2)} = \dfrac{z}{z-2} = 1 + \dfrac2{z-2}$$


Excel distribute value

Question: I would like to divide a number X into possibly N equal values. I explain it in the following scenario. Let's say I have 8000 copies of newspaper and they are wrapped by N (lets say 20, and this can vary). So now I have 400 packets each containing 20 paper. Assume I have X pallets. I want to distribute the 400 packets equally between the pallets where possible. Because sometimes there are more/less paletts I cannot do it with a simple divison function, in excel. Can anyone help?
Comment: Can you post what your data looks like now, and an example of desired outcome.
Comment: added picture. I also wish excel to advise me the number of palets that would be required
Comment: You would need to also know the max per pallet, in your third line, how is Excel to know you want 100,100,92 and not 98,98,96
Comment: true. If I add the max size of a palet, how can I implement it then?
Answer: Hope this helps .... formulas are below each cell
Comment: This helps, but as @Scott said, I need to distribute it. based on a criteria. Thank you!
Comment: pallet can be max 100. Or I dont understand what do you mean by specify even more?
Comment: What should happen if you only had 2 pallets in the above example (i.e. more packets that the number of available pallets)?
Answer: To get the number of pallets needed Use this formula, put in B3 and copy down:
<code>=ROUNDUP(A3/($B$1*$D$1),0)
</code>
Then to get the disbursement table, in C3:
<code>=IF(COLUMN(A:A)<$B3,$D$1,IF(COLUMN(A:A)=$B3,($A3/$B$1)-(COLUMN(A:A)-1)*$D$1,""))
</code>
Then copy drag over and down

Excel distribute value


Apache mpm event not working as expected with SSL/HTTPS

Question: I have a server with Apache/2.4.6 (CentOS) + OpenSSL/1.0.2k-fips (I know this is an old version of Apache but it cannot be upgraded right now). mpm event is used for multi processing.
When serving HTTP content, everything works as expected :

The server can handle many requests concurrently without trouble (the test was made with approximately 150 clients, each creating 4 parallel connections = 600 connections). All requests target static content and use keepalive.
with HTTPS/SSL, it's a different story.

It will quicky use all 400 possible threads (see scoreboard). No async connections will be made. AFAIK it behaves like mpm worker.
At first I thought it was a limitation and that mpm event would work only with HTTP. But this is not what is written in the documentation (under How it Works > Async connections) :

These improvements are valid for both HTTP/HTTPS connections.

EDIT: there is some information in Limitations section of documentation that explain that in some case it might fall back to mpm worker. However it does not seems to apply here.
Comment: Do you KNOW that whatever client you are using for testing will use keep-alives over HTTPS? Are Keep-alives configured on SSL vhost? Are you using the config from Ralph Engeshall's Howto (last updated 2001 which disables Keepalives for some ancient browsers)
Comment: I use an C# console app to simulate workload, which use HttpClient class with default settings (I did not change keepalive).
Comment: Does not answer questions.
Answer: While looking at Apache source code for possible mpm worker fallback conditions, I found the following relevant comment :

If we have an input filter which 'clogs' the input stream, like
mod_ssl used to, lets just do the normal read from input filters, like
the Worker MPM does.

Since I am using an old version of Apache that could be explain mpm event not working well with SSL.
EDIT: it looks like this has been done in this commit :

core, mod_ssl: Lift the restriction that prevents mod_ssl taking full advantage of the event MPM.

I use Apache 2.4.6 and change has been released later, in 2.4.7.


How can I calculate $\int_{|y|\ge a} \frac{1}{|y|^4} dy$?

Question: How can I calculate $n$-dimensional ($y\in \mathbb R^n$) integral of
$$
\int_{|y|\ge a} \frac{1}{|y|^4} dy
$$
where $a>0$.
Answer: Let $\lambda_n$ denote the surface area of a unit $n$-sphere. Then
$$\int_{\vert y\vert > a}\frac{1}{\vert y\vert^4}\, dV = \int_a^\infty \frac{1}{r^4} \cdot \lambda_{n-1}r^{n-1}\, dr = \lambda_{n-1}\int_a^\infty r^{n-5}\,dr$$
The first equality can be thought of as dividing the volume of integration into $n-1$-spherical shells, noting that their contribution to the integral is th surface area of the sphere times $\frac{1}{\vert y \vert}$, and integrating. For $n<4$, this integral can be evaluated directly. Otherwise, the integral doesn't converge.


push jsonlog data to elasticsearch

Question: I have installed the module jsonlog on drupal 7, but there are no information on how can I push the logs to elasticsearch or kibana or logstash. How do I do that?
Answer: As JSONlog project page states:

Logs watchdog events JSON-formatted to log files. Provides a Logstash/ElasticSearch-ready log source.

The module only does one thing: turn Drupal watchdog events into JSON-loggable files and writes them to whatever server dir you've configured for it.
Before using this module you will need to:

Setup ElasticSearch & Kibana. This is a separate task from setting up LogStash. It will depend on your service provider (this is off-topic for Drupal Answers).
Setup LogStash. This will vary based on whatever app server you're running Drupal on. You'll have to find instructions applicable to the app server running Drupal.

push jsonlog data to elasticsearch


Confused by loaded data of scipy.io.loadmat()

Question: I'm trying to load a .mat eye-tracking database from this page. The link of the database is here
After loading using scipy.io.loadmat() function, I found it's hard to understand the loaded data. I don't understand how it corresponds to the original data.
First, the data contains nested numpy arrays, which is not useful because I can't even access the shape. Second, if opening the database by Matlab, I could see the fields I need. But when it was loaded in Python, I can't see how the nested arrays correspond to those fields.
Can someone share an advice on my issue? Thanks
Answer: The answer could be referred to the documentation of this function.

simplify_cells:
False, optional. If True, return a simplified dict
structure (which is useful if the mat file contains cell arrays). Note
that this only affects the structure of the result and not its
contents (which is identical for both output structures). If True,
this automatically sets struct_as_record to False and squeeze_me to
True, which is required to simplify cells.

So, simply pass simplify_cells = True, you would get a dict with clear information.


How do I create a content type that has another content type embedded inside of it?

Question: I'm building a content type for a journal-type product. In each journal there are a number journal articles that vary from journal to journal, which have their own unique fields (like author, date, subject, synopsis, etc). Right now I've set it up so you fill out all of the contents for the articles and then you pull them into the journal via entity reference.
Ideally though, it would be great if I could just streamline all of this into the same "create content" form. For example, when I click "create new journal", I want to get all the fields for my journal plus the ability to dynamically add journal articles and all of their fields.  It could be in a different tab or something, it just needs to be in the same create journal content type form.
Answer: Use References dialog. "This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog"
Answer: You will find Inline Entity Form useful.

Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.
Answer: I think this module can help you: https://www.drupal.org/project/editableviews
If you embed the view in a block on the path node/add/journal
Comment: I don't think editable views is fitted for this use case, References Dialog is...
Comment: Agreed, I've up-voted your answer :)
Comment: But glad you pointed it out Coleman - i have long been a watcher of https://www.drupal.org/project/editablefields having used it in D6 for getting editable fields in a View - looks like this new kid on the block does that and more.


GraphQL - Select different fields of a returned list per item

Question: Lets say i have the following query:
query getBooksQuery($userId: String) {
  getBooks(userId: $userId) {
    id
    description
    image
    user {
      email
      firstName
      lastName
      image
    }
  }
}

Imagine i have to show a list with books of a user and display the author details above the list. Since I'm querying with a userId, i know that all books belong to the same user.
So, i would not like to get for each book of the list the same user details, but get them only once in the response.
Is there any way to declare that i want these info only for the first book i.e.?
Or is it the only way to have two objects in the response, like:
query getBooksQuery($userId: String) {
  getBooks(userId: $userId) {
    books {
      id
      description
      image
    }
    user {
      email
      firstName
      lastName
      image
    }
  }
}

Unfortunately with the second solution, even if its clearer at this point, will require server-side work to support this custom query. So i was thinking if it is still feasible using the current api.
(Also ofc i can do two requests, one for the user and one for the books, but meh...)
I'm using Apollo without relay, but I'm experimenting at this point, so if not feasible in Apollo but feasible otherwise I'm still interested
Answer: You can use the same param for 2 'subqueries' in one request
query getBooksQuery($userId: String) {
  getBooks(userId: $userId) {
    books {
      id
      description
      image
    }
  }
  getUsers(userId: $userId) {
    user {
      email
      firstName
      lastName
      image
    }
  }
}

Comment: yes, mutations additionally are processed sequentially
Comment: This way of combination of different resolvers is a life changer! unbelievable! Same can happen with mutations?


Is there any sql interpreter for objects?

Question: Is there any interpreter that takes a string or even a custom object as input and execute it on my datasource?
I cannot use linq to object because query always changes and the report i'm working on, has about 6000 queries which i can reduce to 9 if i find some tool doing that for me.
Opensource is very applicable.
thanks in advance.
Answer: Check out the expression evaluation functionality within the (open source) Spring.NET library:
http://www.springframework.net/doc-latest/reference/html/expressions.html
Comment: Fast is a subjective term I guess, but I have never found it to be a bottleneck in my application.


Drupal role does not appear in Views Filter

Question: According to one post, I added Author uid in contextual filter but user role still does not appear in the filter. Any other lead help?
Answer: By default, views of content only get access to the UID of the author. Add a relationship to the user to gain access to all the user-related fields, including your custom ones


assigning custom class to UIWindow while using storyboard

Question: In non-storyboard projects i can simply select window in interface builder and change it's class from UIWindow to MyUIWindow. How i am supposed to do it in storyboard project? Thanks in advance for any help!
Comment: See: http://stackoverflow.com/questions/10403137/sublassing-uiwindow-while-using-storyboards
Answer: In AppDelegate you have: <code>@property (strong, nonatomic) UIWindow *window;</code>
So if you do rest in past but not with storyboard you should be fine from there.


what is this ornament called?

Question: Can anybody tell me what this sign is called ?
I thought it was a mordent, but why isn't it written above the lines, why is it so short?
Do you know any theory page on it?
Comment: thanks for answering. But shouldn't articulations be written above or below the note (and not next to it) ?
Comment: @froggynathy A lot of jazz articulations are written next to the note- for example, falls, bends, doits, shakes. They make more sense there, because the symbol is a visual representation of how you play the start/end of the note.
Comment: I assume it is an articulation rather as an ornament. While it seems, that it is covered by Unicode as [Stroke-2](http://unicode-table.com/en/1D19C/), no explanation is found there.
Answer: It's a turn, apparently sometimes called a 'flip':

Source: http://www.timusic.net/wp-content/uploads/jazz+artikulation.pdf, Page 6.

what is this ornament called?


mysql view over single table performance

Question: I have a single table datastore with loads of integer, decimal , date,varchar fields in. I want to logically separate the data in datastore by using a views over this table.
so that datastore.i1 becomes view.field1 datastorei2 becomes view.field2 etc....
There are indexes in the datastore that provide the 'key to the view'.
Are there performance implications to this approach ?
Comment: Without knowing a bit more about the shape of this table, I think it's hard to say what the right approach is.
Answer: Yes, of cource there are performace issues. This article can shed the light on this problem - MySQL Performance Blog.
As a workaround - you could to split data into two physical tables (one-to-one relation).


Find files in one directory not in another

Question: Are there any Linux/Unix tools which find all the files in one directory not present in another? Basically I'm looking for diff which works on the output of ls.
Short and sweet scripts are also appreciated.
Answer: diff does this already:
diff dir1 dir2

Example output:
Only in dir1: some_file.txt
Only in dir1: some_other_file.txt
Only in dir2: third_file.txt

Comment: This is good. One gripe: diff is actually running on each of the files that are in both. Is there an obscure option to just run against file names (I may have missed it)? Otherwise, I suggest `diff dir1 dir2 | grep "Only"`
Comment: wow this just save me many minutes of bash scripting thanks
Answer: Bash:
diff <(cd dir1; ls) <(cd dir2; ls)

Compare only the filenames - not the contents of the files.
Comment: Do not parse `ls`, use `find` instead!
Comment: Also ksh and zsh.
Comment: use rsync for sync dirs
Comment: @valisstillwithMonica: This isn't an example of parsing `ls` since it's only getting a list of files and not looking at fields in output such as `ls -l`. It's also not parsing the names themselves so special characters aren't a problem except for newlines. But diff is going to treat parts of file names surrounding newlines separately anyway (even [this answer](https://serverfault.com/a/177012/1293) with `grep Only` fails in this regard).
Comment: can this be made to be recursive?
Comment: @majorgear: These answers offer ways to do that: [with `--brief`](https://serverfault.com/a/839992/1293) or [with `find`](https://serverfault.com/a/871967/1293) (use `find .` if on a Mac).
Answer: Like people told you here, you can use DIFF in various usage variations. Or you just use dirdiff instead, which is meant for what you're trying! :-)
But if you want to keep some directories in sync then you really should take a look on rsync.
Regards
Answer: If you are wanting to do this through all sub directories as well, a good way to do it is:
diff --brief -r dir1/ dir2/

I prefer using brief, but you can leave that out if you want.
Comment: This is exactly what I was looking for but found WAY more files than I anticipated. Is there any way to copy the files found in `dir2/` to a new folder? `dir3/`
Answer: for i in $(ls -1 directory1); do if (test -f directory2/$i) then echo $i; fi; done
Answer: Dennis Williamson had a good answer, but I needed to do this recursively. GNU findutils 4.7.0 doesn't sort its output, so here's what I used
diff <(cd $dir1; find | sort) <(cd $dir2; find | sort)

To do this only one way, and produce a list of files, I used this:
diff <(cd $dir1; find | sort) <(cd $dir2; find | sort) \
| grep '< ./' | sed "s,< ./,$dir1/,"

For this to work properly, neither $dir1 nor $dir2 should include the trailing slash.
Answer: This works..
ls -a1 /dir1 | sort > /tmp/1
ls -a1 /dir2 | sort > /tmp/2
diff /tmp/1 /tmp/2

Answer: untested:
find /dir/A -printf "%P" | while read f; do
  if [ ! -e "/dir/B/$f" ]; then
    echo $f
  fi
done


Percussion Rhythm Help

Question:
Hey, so I need help counting the two measures underlined in red (43-44). I play the conga for this and I need help with counting the rhythm here.
Thank you!
Answer: Supposing the time signature is 4/4 (common time), the rhythm you have underlined sounds like this (where a beat in bold means a note you hit).
1 & 2 & 3 & 4 & | 1 & 2 & 3 & 4 &
Yes, I know it is an irregular beat but is probably typical of the conga music you play. Do let me know if you need any more help!
Comment: The bold symbols hard barely distinguishable from the non-bold ones sadly :(
Answer: Consider each punctuation mark an 8th note and accent the exclamations:
. . ! . . ! . !
. . ! . . . ! !
Alternatively, speak the phrase with each word on an 8th note, accentuating every word which sounds like "TWO", "TOO", etc.  If you can repeat this phrase and snap on each "TWO/TOO/TO/TU" syllable, you should be able to internalize the beat.  Then when you play the piece, you'll be thinking about your mother's tutu.
After TWO is far TOO late TO
Step in-TO my mother's TU-TU.
This phrase will haunt you for the rest of your life and you will likely be hearing it around your time of death.  I hope that it was worth this to learn these two measures properly.  You're welcome.
Comment: This is a great way to remember a particular phrase. If finding homophones is too (!) time-consuming, just come up with an ordinary sentence that has the same emphases. +1
Comment: Some of us are TOO compelled by our homophonic tendencies.
Comment: Trouble is, there aren't that many homophones with more than two spellings/meanings, which is where my comment came in.

Percussion Rhythm Help


dotnet framework 2.0 sp2 breaks CLR integration in SQL server

Question: It appears that CLR integration does not like Dotnet framework 2.0 sp2. I am getting the following error message when trying to run code that depends on the clr.
Msg 6510, Level 16, State 11, Line 1
Common Language Runtime (CLR) v2.0.50727 not installed properly. The CLR is required to use SQL/CLR features.

I have verfied with the dotnet verification tool that the dotnet framework for all versions installed work.
I have only found possibly one hint that this is whats causing the issue. I would think thought that if this was the case more people would be screaming. Does anyone have any suggestions on how to track this down better. We have a few systems that are relying on this implementation.
Answer: Restarting the SQL Server service got me past this problem.
The CLR had been enabled using the...
sp_configure 'clr enabled', 1;
GO
reconfigure
GO

...statements but until the SQL Server service was restarted none of the CLR features could be used.
Answer: It almost sounds like a corrupt install of v2.0.50727.  I would try to reinstall that version and the SP.  Can you run a custom .net app compiled for that version on that machine?
Comment: I'm glad you got it working.  I should have been clearer with my answer.  I meant to reinstall .Net framework v2.0.50727 and any SP's/hotfixes (to get you to where you were before reinstalling).
Comment: the MS verification tool runs a custom app as part of its process, but i think it runs it against sp2. Do you mean specifically for dotnet framework 2.0 no sp?
Comment: Our server rebooted overnight unexpectanly. I tested the clr process report and it is now working, so maybe something was corrupt, we had an issue with zombie processes.


Interval set through content script being cleared by webpage

Question: In my chrome extension, I have a setInterval in the content script which checks for changes in the webpage after every 3 seconds.
setInterval(detectChange, 3000)

function detectChange(){
    ...
}

This works perfectly well for all websites except one (www.rdio.com). The webpage scripts somehow clears the interval set through the content script.
I thought of putting the setInterval in background script and sending a message to the content script at each interval. But that would require me to track all the tabs in which the content script is running, which does not seem like a good idea.
Please let me know if there is a way around.
Comment: What you describe is impossible. Unless the page navigates away, your content script's context is untouchable by the page. Needs more debugging.
Comment: That was my understanding as well. But I couldn't find any other explanation. The page does not navigate away, because, other parts of the content script still works, such as message listeners and event handlers.
Answer:
Cancelable task schedulers (setTimeout, setInterval,  requestAnimationFrame, etc.) are apparently tied to a document. Although the script execution context of a content script is isolated from the page, the document is not.
It seems rather weird that a site clears timers that are not created by the site itself. You could try to debug the issue, and check why the site is clearing the timer at all by overriding the clearTimeout / clearInterval methods.
Here is an example to catch code that clears timers that are not installed by the script itself:
// Run this content script at document_start
var s = document.createElement('script');
s.textContent = '(' + function() {
    var clearTimeout = window.clearTimeout;
    var setTimeout = window.setTimeout;
    var setInterval = window.setInterval;
    // NOTE: This list of handles is NEVER cleared, because it is the
    // only way to keep track of the complete history of timers.
    var handles = [];
    window.setTimeout = function() {
        var handle = setTimeout.apply(this, arguments);
        if (handle) handles.push(handle);
        return handle;
    };
    window.setInterval = function() {
        var handle = setInterval.apply(this, arguments);
        if (handle) handles.push(handle);
        return handle;
    };
    window.clearTimeout = window.clearInterval = function(handle) {
        clearTimeout(handle);
        if (handle && handles.indexOf(handle) === -1) {
            // Print a stack trace for debugging
            console.trace('Cleared non-owned timer!');
            // Or trigger a breakpoint so you can follow the call
            // stack to identify which caller is responsible for
            // clearing unknown timers.
            debugger;
        }
    };
} + ')();';
(document.head || document.documentElement).appendChild(s);
s.remove();

If this shows that the site is buggy, and (for example) clears every even-numbered timer, then you simply call setTimeout twice to resolve the problem.
For example:
Promise.race([
    new Promise(function(resolve) {
        setTimeout(resolve, 3000);
    }),
    new Promise(function(resolve) {
        setTimeout(resolve, 3000);
    });
}).then(function() {
    // Any of the timers have fired
});

If all else fails...
If it turns out that the site clears the timers in an unpredictable way, you could try to use other asynchronous methods or events to schedule tasks, and measure the time between invocations. When a certain time has elapsed, simply trigger your callback. For example, using requestAnimationFrame (which is usually called several times per second):
function scheduleTask(callback, timeout) {
    timeout = +timeout || 0;
    var start = performance.now();
    function onDone(timestamp) {
        if (timestamp - start >= timeout) callback();
        else requestAnimationFrame(onDone);
    }
    requestAnimationFrame(onDone);
}

// Usage example:
console.time('testScheduler');
scheduleTask(function() {
    console.timeEnd('testScheduler');
}, 1000);

Or insert an  and create timers in the context of the frame.
Comment: Thanks for the reply. I debugged as you suggested and got this:
`Cleared non-owned timer!  [VM54028:1]
window.clearTimeout.window.clearInterval [ImageLoader.f79c22ba20b9f32ecc63488859b91348.js:87]
R.Component.create.onLoaded [jquery-1.8.3.c2901e3fdd932a1fc29794aafece65e5.js:3058]
jQuery.event.dispatch [jquery-1.8.3.c2901e3fdd932a1fc29794aafece65e5.js:2676]
jQuery.event.add.elemData.handle.eventHandle [(index):129]
nrWrapper`

Looks like, some ImageLoader code in the page is clearing my interval!
Comment: I tried your scheduledTask function using requestAnimationFrame. It is not working either, the callback function runs only once.
Comment: @Samik The callback *should* run only once, because the method is similar to `setTimeout`. Call `scheduleTask` again when the callback is called if you want yo schedule a *periodic task*, like `setInterval`.
Comment: Right! Still I was having some issues with it. Finally, I went for your last suggestion (using ): `$('').css('display','none').appendTo('body')[0].contentWindow.setInterval(detectChange,3000)`. It is working nicely. Thanks again for your help.
Comment: That's.. messy with regards to CS/webpage separation. Thanks for weighing in on the topic.


Modular Arithmetic Equations

Question: I'm trying to solve $x^{16} = [1]_{989}$ in  $x ∈\Bbb Z/989\Bbb Z$.
I tried a few simplifications but don't know how to solve it.
Any help is welcome.
Comment: Do you know the prime factorization of 989? Applying CRT helps.
Comment: CRT is probably the way to go but not sure how to apply it here.
Answer: Here $989=23\cdot 43$, and both $23$ and $43$ are primes. For $x$ to be a solution of your equation, it is necessary and sufficient that $x$ is a solution of the congruence
$$
x^{16}\equiv 1\pmod{23}
$$
and of the congruence
$$
x^{16}\equiv 1\pmod{43}.
$$
For a prime number $p$ the multiplicative group $\mathbb{Z}_p^*$ is cyclic of order $p-1$. In a cyclic group of order $m$ there are $\gcd(m,n)$ solutions of the equation $x^n=1$. From this we can deduce that there are $2=\gcd(23-1,16)$ residue classes $x$ modulo $23$ with the property. You can find them either by trial and error or using DonAntonio's answer as a hint, so I won't do that here. Similar we see that the solutions of the latter congruence form two residue classes modulo $43$.
Now if you know that an integer $x$ is $\equiv a\pmod{23}$ and $\equiv b\pmod{43}$, then the Chinese Remainder Theorem tells you that there is a unique residue class $x$ modulo $989$ such that it satisfies both of the congruences $x\equiv a\pmod{23}$ and $x\equiv b\pmod{43}$. In other words any solution of your congruence modulo $23$ can be paired up with any solution of your congruence modulo $43$. Doing this CRT-pairing for all the four possible pairs will give you four pairwise non-congruent solutions.
If you have problems with any of the steps, ask more.
Comment: Got it ! Thanks :)
Answer: $$x^{16}=1\Longleftrightarrow x^{16}-1=0\Longleftrightarrow (x^8-1)(x^8+1)=0\Longleftrightarrow ...$$
$$\Longleftrightarrow (x-1)(x+1)(x^2+1)(x^4+1)(x^8+1)= 0...$$

Modular Arithmetic Equations


GPS continua ligado após fechar a Activity

Question: Estou usando no meu aplicativo, GPS e Direction do Google. Está funcionando, porém eu notei o seguinte. Após eu retornar da activity onde tem o mapa, o ícone do GPS do smartphone não sai, ele fica como se tivesse ainda consumindo a atividade. Ele só sai quando eu realmente fecho todo o aplicativo.
A tela em si (do mapa), só traça a rota do usuário do ponto A até o B.
Alguma dica?
Answer: Qualquer que seja o método que esta a utilizar para rastrear a localização do dispositivo deve iniciá-la no método onResume()/onStart() e terminá-la no método onPause()/onStop().
Se estiver a usar o FusedLocationClient será qualquer coisa assim:
@Override
public void onResume() {
    super.onResume();
    if (checkPermissions()) {
        startLocationUpdates();
    } else if (!checkPermissions()) {
        //Não implementado, apenas necessário se targetSdkVersion >= 23
        requestPermissions();
    }
}

@Override
protected void onPause() {
    super.onPause();
    mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}

Ver esta resposta à pergunta Como obter a localização actual do dispositivo android? para um exemplo de implementação.
Comment: obrigado pela ajuda. Segui o que você me passou e utilizei o método onPause() . Dentro dele usei o `LocationManager` junto com `LocationListener` que são os métodos que uso. Testei e funcionou.
Answer: Para parar o serviço eu faço de uma forma diferente da sua. Faço com
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, context);

no onPause(), e no onStop() eu faço
mGoogleApiClient.disconnect();

Comment: obrigado pela ajuda. Eu utilizei o método onPause() . Dentro dele usei o `LocationManager` junto com `LocationListener` que são os métodos que uso. Testei e funcionou.


How many times a batsman can stop a bowler while he starts bowling the ball in Cricket? Is there any hard rule/limitation for the batsman?

Question: I saw so many times that a batsman stopped the bowler while he is coming to bowl the ball. After he raises his hand bowler stops bowling that ball and he will go back and bowl again. It's a usual behavior in some matches. But I don't know whether there is any count limitation for a batsman to stop a bowler in 1 match?
Answer: There's no limit - a bowler can stop in his run-up as often as he likes, and a batsman can pull out of a delivery as often as he likes.
In practice, the umpire will have a word if he feels the players are messing about, and it doesn't happen too often.
Note, though, that if a batsman pulls away, and the bowler actually delivers the ball, if the batsman plays at the ball it's considered a stroke, and he can get runs or be out. When umpiring a 20/20 game here I gave out a member of our international team when he slashed at a ball having pulled away, and guided it onto his stumps. He wasn't happy, but he was told by his coach that he was out!
Comment: An international player had to be told of the rule by a coach? Wow!
Comment: You'd be flabbergasted at the lack of knowledge of the laws amongst players, even top-level ones. There's also a large amount of simply wrong impressions out there - for instance, nobody seems to know the only correct way to run out a batsman when the bails are already removed.


proving two statements are equivalent

Question: Let $X$ be a set, ler $R$ be a binary relation on $X$, let $PX$ be the set of subsets of $X$, then 1) and 2) are equivalent:
1) $\forall a\in X\ \forall A\in PX(\forall f\in X(aRf\rightarrow f\in A)\rightarrow\forall g\in X(aRg\rightarrow\forall h(gRh\rightarrow h\in A)))$
2)$\forall a,g,h((aRg,gRh)\rightarrow\forall A[(\forall f(aRf\rightarrow f\in A))\rightarrow h\in A])$
Is there a way to prove the equivalence?
Comment: Some may argue against that, since it seems that you are quantifying over subsets (I just noticed that after posting the previous comment). But I think it's fine, because we can consider this in the universe of set theory, and we may consider $P$ as a function symbol. So it's first-order after all.
Comment: Propositional calculus has no quantifiers, this is first-order logic, or predicate logic.
Comment: @AsafKaragila thank you, i've modified tags
Answer: I think I have proven it without resorting to set-theoretic axioms. Let us introduce the following abbreviations:
$$\phi:= aRg, \psi:=gRh, \chi:={f\in A}, \mu:={h\in A}, \kappa:= aRf$$
The formulae now become (ignoring domain specifications):
$$\begin{align*}\forall a \forall A &\left((\forall f: \kappa \to \chi) \to \forall g[\phi\to\forall h(\psi\to\mu)]\right) \\
\forall a \forall g \forall h & \left((\phi \land \psi)\to\forall A[(\forall f:\kappa\to\chi)\to\mu]\right)\end{align*}$$
We will proceed by showing they are both equivalent to:
$$\forall a \forall A \forall g \forall h \, \left(\phi\land \psi \land (\forall f:\kappa\to\chi)\right) \to\mu$$
which basically follows from applying the rules:
$$\begin{align*}\phi \to \forall x \psi &\iff \forall x (\phi \to \psi) \\
\phi \to (\psi \to \chi) &\iff (\phi\land \psi)\to\chi\end{align*}$$
the first of which is valid whenever $x$ does not occur freely in $\phi$. Please let me know if you want this last part in more detail.
Comment: when you rewrite formula 1) using $\phi,\psi,k...$ in the final part $\phi\rightarrow\mu$ should be replaced by $\psi\rightarrow\mu$
Comment: Of course, thanks. One of my most common typos.
Answer: If you want a set-theoretic proof, one way is to prove that each is equivalent to the statement that $R$ is transitive:
$$\forall a,g,h\in X(aRg\land gRh\to aRh)\;.\tag{3}$$
For $a\in X$ let $R[a]=\{f\in X:aRf\}$. Then (1) can be rewritten as
$$\forall a\in X\forall A\in\wp(X)\Big(R[a]\subseteq A\to\forall g\in R[a](R[g]\subseteq A)\Big)\;,\tag{1'}$$
and (2) as
$$\forall a,g,h\in X\Big(aRg\land gRh\to\forall A\in\wp(X)(R[a]\subseteq A\to h\in A)\Big)\;,\tag{2'}$$
while transitivity becomes
$$\forall a,g,h\in X\Big(g\in R[a]\land h\in R[g]\to h\in R[a]\Big)\;.\tag{3'}$$
Now $\forall A\in\wp(X)(R[a]\subseteq A\to h\in A)$ is clearly equivalent to $h\in\bigcap\{A\in\wp(X):R[a]\subseteq A\}$, and that intersection is evidently just $R[a]$, so it's easy to see that $(2')$ is equivalent to $(3')$.
$(1')$ clearly implies
$$\forall a\in X\forall g\in R[a](R[g]\subseteq R[a])\;,\tag{1''}$$ which is easily seen to be equivalent to $(3')$. Finally, one can again use the fact that $R[a]=\bigcap\{A\in\wp(X):R[a]\subseteq A\}$ to show that $(1'')$ implies $(1')$.

proving two statements are equivalent


Element not found in the cache - perhaps the page has changed since it was looked up in Selenium Ruby web driver?

Question: I am trying to write a crawler that crawls all links from loaded page and logs all request and response headers along with response body in some file say XML or txt. I am opening all links from first loaded page in new browser window so I wont get this error:
Element not found in the cache - perhaps the page has changed since it was looked up

I want to know what could be the alternate way to make requests and receive response from all links and then locate input elements and submit buttons form all opened windows.
I am able to do above to some extent except when opened window has common site searh box like one on this http://www.testfire.net in the upper right corner.
What I want to do is I want to omit such common boxes so that I can fill other inputs with values using i.send_keys "value" method of webdriver and dont get this error
ERROR: Element not found in the cache - perhaps the page has changed since it was looked up.
What is the way to detect and distinguish input tags from each opened window so that value does not get filled repeatably in common input tags that appear on most pages of website.
My code is following:
require 'rubygems'
require 'selenium-webdriver'
require 'timeout'

class Clicker
def open_new_window(url)
  @driver = Selenium::WebDriver.for :firefox
  @url = @driver.get " http://test.acunetix.com "
  @link = Array.new(@driver.find_elements(:tag_name, "a"))
  @windows = Array.new(@driver.window_handles())
  @link.each do |a|
      a = @driver.execute_script("var d=document,a=d.createElement('a');a.target='_blank';a.href=arguments[0];a.innerHTML='.';d.body.appendChild(a);return a", a)
      a.click
    end
    i = @driver.window_handles
    i[0..i.length].each do |handle|
        @driver.switch_to().window(handle)
        puts @driver.current_url()
        inputs = Array.new(@driver.find_elements(:tag_name, 'input'))
        forms = Array.new(@driver.find_elements(:tag_name, 'form'))
        inputs.each do |i|
            begin
                i.send_keys "value"
                puts i.class
                i.submit
                rescue Timeout::Error => exc
                    puts "ERROR: #{exc.message}"
                rescue Errno::ETIMEDOUT => exc
                    puts "ERROR: #{exc.message}"
                rescue Exception => exc
                    puts "ERROR: #{exc.message}"
            end
        end
        forms.each do |j|
            begin
                j.send_keys "value"
                j.submit
                rescue Timeout::Error => exc
                    puts "ERROR: #{exc.message}"
                rescue Errno::ETIMEDOUT => exc
                    puts "ERROR: #{exc.message}"
                rescue Exception => exc
                    puts "ERROR: #{exc.message}"
            end
        end

    end
#Switch back to the original window
    @driver.switch_to().window(i[0])
end
end
ol = Clicker.new
url = ""
ol.open_new_window(url)

Guide me how can I get all requeat and response headers with response body using Selenium Webdriver or using http.set_debug_output of ruby's net/http ?
Answer: Selenium is not one of the best options to use to attempt to build a "web-crawler". It can be too flakey at times, especially when it comes across unexpected scenarios. Selenium WebDriver is a great tool for automating and testing expectancies and user interactions.
Instead, good old fashioned curl would probably be a better option for web-crawling. Also, I am pretty sure there are some ruby gems that might help you web-crawl, just Google search it!
But To answer the actual question if you were to use Selenium WebDriver:
I'd work out a filtering algorithm where you can add the HTML of an element that you interact with to an variable array. Then, when you go on to the next window/tab/link, it would check against the variable array and skip the element if it finds a matching HTML value.
Unfortunately, SWD does not support getting request headers and responses with its API. The common work-around is to use a third party proxy to intercept the requests.
============
Now I'd like to address a few issues with your code.
I'd suggest before iterating over the links, add a @default_current_window = @driver.window_handle. This will allow you to always return back to the correct window at the end of your script when you call @driver.switch_to.window(@default_current_window).
In your @links iterator, instead of iterating over all the possible windows that could be displayed, use @driver.switch_to.window(@driver.window_handles.last). This will switch to the most recently displayed new window (and it only needs to happen once per link click!).
You can DRY up your inputs and form code by doing something like this:
inputs = []
inputs << @driver.find_elements(:tag_name => "input")
inputs << @driver.find_elements(:tag_name => "form")
inputs.flatten
inputs.each do |i|
  begin
    i.send_keys "value"
    i.submit
  rescue e
    puts "ERROR: #{e.message}"
  end
end

Please note how I just added all of the elements you wanted SWD to find into a single array variable that you iterate over. Then, when something bad happens, a single rescue is needed (I assume you don't want to automatically quit from there, which is why you just want to print the message to the screen).
Learning to DRY up your code and use external gems will help you achieve a lot of what you are trying to do, and at a faster pace.


If $f(0)=0$, $f(1)=1$, $f(2)=2$, and $f$ is twice-differentiable then $f''(u)=0$ for some $u$ in $(0,2)$

Question: Let the real-valued function $f$ be continuous on $[0,2]$ and twice-differentiable on $(0,2)$. Assume that $f(0)=0$, that $f(1)=1$, and $f(2)=2$.
Prove that there exists $u\in(0,2)$ such that $f''(u)=0$.
Comment: I couldn't even start...
Comment: How comes you "couldn't even start"? Which similar results can you prove?
Answer: hint
Let $g (x)=f (x)-x $
then
$$g (0)=g (1)=g (2)=0$$
Apply Rolle's Theorem at $[0,1] $ and $[1,2] $ to get $c_1$ and $c_2$.
then apply it again to the derivative $g'$ at $[c_1,c_2] $.
observe that $$g''(x)=f''(x). $$
Answer: By mean value theorem:
$f(0) = 0$ and $f(1) = 1$, so there exists an $s \in (0,1)$ such that $f'(s) = 1$.
$f(1) = 1$ and $f(2) = 2$, so there exists a $t \in (1, 2)$ such that $f'(t) = 1$.
$f'(s) = f'(t) = 1$, so there exists an $u \in (s, t)\subset (0,2)$ such that $f''(u) = 0$.
Answer: Hint: What does the mean value theorem tell you? Consider separately the intervals $(0,1)$ and $ (1,2)$. See what you can do from there (maybe Rolle's might be helpful).


Question about changing parameter value in Swift

Question: I am working on a POST request with application / x-www-form-urlencoded. There is a question in the process of specifying parameters to be passed using Alamofire.
I created a parameter variable called passingParameter
I want to change the parameter at the time the user_id was created.
var passingParameter = [
        "user_id" : "null",
        "user_email" : "null",
        "user_age" : "null",
        "user_gender" : "null",
        "user_birthday" : "null",
        "user_type" : "google"
    ]

How do I put an id in the passingParameter variable?
ex)
var passingParameter = [
        "user_id" : "1122445566",
        "user_email" : "null",
        "user_age" : "null",
        "user_gender" : "null",
        "user_birthday" : "null",
        "user_type" : "google"
    ]

Comment: Do you know how to use dictionaries? `passingParameter` is basically a dictionary.
Answer: It's difficult to tell what's being asked here.
If you already have the variable of user_id somewhere, let's say like
var userID = "1122445566"

Then you can simply assign the value at creation.
var passingParameter = [
        "user_id" : userID,
        "user_email" : "null",
        "user_age" : "null",
        "user_gender" : "null",
        "user_birthday" : "null",
        "user_type" : "google"
    ]

or later like
passingParameter["user_id"] = userID


how to take image from iphone phonebook using programming?

Question: there are two normal ways to import images (from camera and from album) but I also want to take images of iphone phonebook, so what should I do ?
Answer: Below can be used for getting image from AddressBook
NSData  *imgData = (NSData *)ABPersonCopyImageData(person);

UIImage  *img = [UIImage imgaeWithData:imgData];

where person is of type ABRecordRef. Now as CFData and NSData are
toll-free bridged
, so you can simply type cast CFData to NSData and get the image
Here is the Tutorial
http://adeem.me/blog/2009/04/02/get-image-from-contact-stored-in-addressbook/
Answer: If with "phonebook" you mean AddressBook framework to access contacts data, try using Erica Sadun's AB cocoa wrapper. It includes a sample project, so it will be easy.


Compute the angles between the elements of the standard basis with respect to this scalar product

Question: I have an homework to solve but I am behind with the theory. It doesn't look difficult, since it is about computations, just it would be good for me to find a short document which explains exactly what is introduced here. This is the text to which I refer:
"Consider on $\mathbb{R}^{3}$ the scalar product defined by assuming that the vectors $f_{1}=(1,0,0), f_{2}=(1,1,0), f_{3}=(1,1,1)$ are orthonormal:
(1) Compute the angles between the elements of the standard basis $e_{1}=(1,0,0), e_{2}=(0,1,0), e_{3}=(0,0,1)$ with respect to this scalar product.
(2) Compute the orthogonal projections of the ei onto each other with respect to this scalar product."
My interpretion of the text:
I have a 3D space and I am considering the vector space defined by the 3 orthonormal vectors. First question: what are orthonormal vectors? Also reading on the internet, I have understood they are orthogonal unit vectors. Cfr. https://en.wikipedia.org/wiki/Orthonormal_basis but of the vectors above only the first one is a unit vector.
The text asks for computing the angles between the elements of the standard basis with respect to the scalar product. Does this mean that I have to draw the 3 vectors above and the other 2 unit vectors and evaluating the degrees/radians of the angles between them? (of course, I would made any computation in analytical way; for now, I want to just understand what is asked by the text).
While the second task isn't very clear for me in this moment.
Could you give me some insights on the exercise(s), please? In addition, could you post here some examples, in order to let me understand me what is asked by the text, please?
Answer: The set $F = \{ \vec f_1, \vec f_2,\vec  f_3 \}$ form a basis for $\mathbb R^3$ and what's more, we are told that with respect to some inner product $\langle \cdot, \cdot \rangle$ they are orthonormal, hence
$$\langle \vec f_i, \vec f_j \rangle = \delta_{ij} = \begin{cases} 1, i = j \\ 0, i \neq j \end{cases}$$
Thus given any two vectors $\vec a,\vec  b \in \mathbb R^3$, write them with respect to the $F$ basis, $\vec a = a_1 \vec f_1 + a_2 \vec f_2 + a_3 \vec f_3$ and $\vec b = b_1 \vec f_1 + b_2 \vec f_2 + b_3 \vec f_3$. Then by linearity of inner products
$$\langle \vec a, \vec b \rangle = \sum_{i=1}^3 \sum_{j=1}^3 a_ib_j \langle \vec f_i, \vec f_j \rangle$$
As $\langle \vec f_i, \vec f_j \rangle = \delta_{ij}$ this sum reduces to
$$\langle \vec a, \vec b \rangle = \sum_{i=1}^3 a_ib_i = a_1b_1 + a_2b_2 + a_3b_3$$
Use this to solve the question asked by writing the $\vec e_i$ in the $F$ basis: $\vec e_1 = \vec f_1, \vec e_2 = \vec f_2 - \vec f_1, \vec e_3 = \vec f_3 - \vec f_2 - \vec f_1$

For example, the angle $\theta_{12}$ between $\vec e_1$ and $\vec e_2$ satisfies
$$\cos\theta_{12} \| \vec e_1 \| \ \| \vec e_2 \| = \langle \vec e_1, \vec e_2 \rangle$$
where $$\| \vec e_1 \| = \sqrt{\langle \vec e_1, \vec e_1 \rangle} = \sqrt{\langle \vec f_1, \vec f_1 \rangle} = \sqrt 1 = 1$$ and $$\| \vec e_2 \| = \sqrt{\langle e_2, e_2 \rangle} = \sqrt{\langle f_2 - f_1, f_2 - f_1 \rangle} = \sqrt 2$$
as $\langle \vec f_2 - \vec f_1,  \vec f_2 - \vec f_1 \rangle = \langle \vec f_2, \vec f_2\rangle - \langle \vec f_2, \vec f_1\rangle - \langle \vec  f_1, \vec  f_2\rangle + \langle \vec f_1, \vec f_1\rangle = 1 - 0 - 0 + 1 = 2$
Also $$\langle e_1, e_2 \rangle = \langle f_1, f_2 - f_1 \rangle = \langle f_1, f_2 \rangle - \langle f_1, f_1 \rangle = 0 - 1 = -1$$ and thus we have
$$\cos\theta_{12} = \frac{\langle \vec e_1, \vec e_2 \rangle}{ \| \vec e_1 \| \ \| \vec e_2 \|} = \frac{-1}{\sqrt{2}}$$
Comment: I doubt someone who is just learning about orthogonality knows about the kronecker delta.
Comment: Which is why I wrote the definition of $\delta_{ij}$
Comment: @SimonS, thank you for your answer! Could you add some conceptual information for every passages, please? Maybe this could suffice in order to let me understand. I hope I am not asking too muh to you...
Comment: If you have a specific follow up, please ask. I don't know how to address that kind of general request as I don't know what it is you don't understand.
Comment: @SimonS, About notation, the 2 vectors you mention, a and b, should be written with an arrow above? While = a1f1 ..etc., which stands for an inner product between the coordinates of the vectors and the vectors that form the basis, don't need it, right?
Comment: I've added vector arrows above throughout. In particular, we write $$\vec a = a_1 \vec f_1 + a_2 \vec f_2 + a_3 \vec f_3$$ because $\{ \vec f_1, \vec f_2,\vec  f_3 \}$ is a basis so we can write any vector $\vec a \in \mathbb R^3$ as a unique linear combination of the basis **vectors** $\vec f_j$. That is, this is *not* an inner product.


ConcurrentModificationException on LinkedList

Question: The code given below dont throw a ConcurrentModificationException.But if i add 2 more elements into the LinkedList, it throws the Exception. Why ?
List<String> list = new LinkedList<String>();
list.add("A");
list.add("B");

for (String s : list) {
    if (s.equals("B")) {
        list.remove(s);
    }
}

Comment: See http://stackoverflow.com/a/223929/4290096
Comment: possible duplicate of [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing)
Comment: I guess which question was asked more times, this or strings comparison..
Answer: You can't remove items from a Collection while iterating over it using an enhanced for loop. What you want to do instead is this:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
  String s = iterator.next();
  if (s.equals("B")) {
    iterator.remove();
  }
}

Comment: I know Iterator is good for such operations, but i m curious to know why only the last and 2nd last elements are removed from the linkedList without throwing the ConcurrentModificationException ?
Answer: You cant remove an entry from a list in a for loop, you have to use an iterator, like that:
List<String> list = new LinkedList<String>();
list.add("A");
list.add("B");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
  String entry = iterator.next();
  if(entry.equals("B") {
   iterator.remove();
  }
}

Comment: Well that's uncanny. :P
Comment: That kind of sucks. Here, have some rep anyways. :)
Comment: @RedRoboHood what do you mean? =)
Comment: @RedRoboHood You were a couple secs faster=) This moment, when being second costs you at least 10 points of rep, lol.
Comment: Yeah... that's just how SO is, I guess. Not sure why your post got downvoted, though.
Comment: @RedRoboHood Hey cool, I also got downvoted. Whats wrong with those guys? They thought I just copy pasted your answer, did they? :P
Comment: B could be removed in a foreach loop also without any exception. What i want to know is why it throws ConcurrentModificationException when i add 2 more elements into the list ? like -
                list.add("A");
  list.add("B");
  list.add("C");
  list.add("D");
Comment: @Bibhudutta please do some effort and see at least [here](http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html)


Integral estimation of the number of zeros of an function

Question: Let be $f : [a, b] \mapsto \mathbb{R}$ a continuously differentiable function.
We suppose that:

$f(a)f(b) < 0$
$\lvert f \rvert + \lvert f' \rvert > 0$

Let us denote $I(\varepsilon) = \dfrac{1}{2\varepsilon} \int\limits_a^b \lvert f' \rvert 1_{\lvert f \rvert < \varepsilon}$ where $1_A$ is the indicator function of the set $A$.
I would like to show that $I(\varepsilon) \to \mathrm{card } f^{-1}(0)$ as $\varepsilon \to 0$.
What I have done so far:

I have proved there was a finite amount of zeros using the hypothesis as all zeros were isolated points.
I found a certain set of $\varepsilon$ where $f^{-1}(]-\varepsilon, \varepsilon[)$ is a finite reunion of open intervals.
I can upper bound my integral by the limit desired, using the finite reunion of open intervals.

I would like to show something like the integral would be strictly decreasing or get a lower bound and squeeze theorem. I tried to use uniform convergence to get precise estimates but failed to get further.
Answer: You have done the hardest part of the problem.
As you said the second condition :

$\mid f \mid + \mid f' \mid > 0$

Means that all the zero are isolated points, which means that if : $f(c) = 0$ for some $c \in [a, b]$ then there is an $\epsilon$, such that $\forall x \in ]c-\epsilon, c+\epsilon[, f(x) \ne 0$.
Moreover the first condition is also very important. $f(a)f(b) < 0$, means that $f(a)$ and $f(b)$ have different signs.
So using the fact that $f$, is continuous we have by the intermediate value theorem a point $c'$ where $f(c') = 0$.
Now, let $n$ be the number of annulation points of the function $f$, as we said earlier $n$ is such that : $0 < n < \infty$ and let's denote : $r_1 < r_2 < ... < r_n$ the roots of $f$.
Using the fact that $r_i$ are isolated points, we can find a couple $(z_i, z'_i) \in [a,b]^2, z_i \ne z'_i$ such that $\mid f(r_i-z_i)\mid =  \mid f(z'_i+r_i) \mid = \epsilon  $ and for all $i \leq n$ :
$$\forall x \in [r_i-z_i, r_i+z'_i], \mid f(x) \mid \leq \epsilon $$
Moreover $f$ is continuous so on the compact sets : $[r_i, r_{i+1}]$, $f$ has a supremum. Hence if we take $\epsilon$ such that : $\epsilon < \min \{ \sup_{[r_{i-1}, r_{i}]} f, \sup_{[r_{i}, r_{i+1}]} f \}$ then we have :
$$\int_a^b \mid f' \mid \mathbb{1}_{\mid f \mid < \epsilon} = \sum_{i = 1}^n \int_{r_i-z_i}^{r_i+z'_i} \mid f'(x) \mid \mathrm{d}x$$
Hence :
$$\int_{r_i-z_i}^{r_i+z'_i} \mid f'(x) \mid \mathrm{d}x = \mid f(r_i+z'_i)+f(r_i-z_i) \mid = 2\epsilon$$
So finally we get :
$$I(\epsilon) = \frac{1}{2\epsilon} \sum_{i = 1}^n \int_{r_i-z_i}^{r_i+z'_i} \mid f'(x) \mid \mathrm{d}x = \frac{1}{2\epsilon}\cdot n \cdot 2\epsilon = n = \mid f^{-1}(\{0\}) \mid$$
You can note that here I am not taking the limit but just assuming that  :
$\epsilon < \min \{ \sup_{[r_{i-1}, r_{i}]} f, \sup_{[r_{i}, r_{i+1}]} f \}$, and your equality is always true when this happend (so especially when $\epsilon \to 0$).
Answer: Since $|f'|$ is positive near a zero of $f$, all zeros are isolated.
Assume $f$ has countably infinite many zeros, say $x_k$ for $k\in \mathbb N$. Then, as $[a, b]$ is compact, there exists a convergent subsequence with limit $x^*$. By continuity, $x^*$ is a zero but not isolated. That's a contradiction.
Let $x_1, \dotsc, x_n$ denote the zeros of $f$. Then, for each $k=1,\dotsc,n$ by continuity of $f'$ there exists some $\delta_k > 0$ such that $|f'|$ is positive on $(x_k - \delta_k, x_k + \delta_k)$. Now, let
$$ \epsilon = \min_{1\le k \le n} \min \{ |f(x_k - \delta_k)|, |f(x_k + \delta_k)|\}.$$
For that $\epsilon$, $N_\epsilon = f^{-1}((-\epsilon, \epsilon)) = \bigcup_{k=1}^n I_k$ is partitioned into $n$ disjointed open intervals such that $f$ is injective on $I_k$ and $f(I_k) = (-\epsilon, \epsilon)$.
Integrate by substitution yields
$$ I(\epsilon) = \frac1{2\epsilon} \int_{N_\epsilon} |f'| = \frac1{2\epsilon} \sum_{k=1}^n \int_{I_k} |f'| = \frac1{2\epsilon} \sum_{k=1}^n \int_{-\epsilon}^{\epsilon} 1 = n.$$
Comment: Do you have an example of a function with countably infinite many zeros which verify the hypothesis? I believed that through compactness of the set of zeros and isolation, there could be no injective sequence of zeros. But very nice answer.
Comment: @Raito my bad, there are only finitely many zeros. I edited my answer.


Printing database query results in AS3

Question: new-ish to PHP. Attempting to create a highscore table in Flash, I've got my game linked to the database and can send scores to it no problem. I can also retrieve them but the problem lies in the output.
My PHP code for retrieving the data and outputting it:
<?php
include_once("connect.php");
if ($_POST['systemCall'] == "getScores"){
    $sql = "SELECT * FROM highscores ORDER BY score DESC LIMIT 0,5";
    $query = mysql_query($sql);
    $counter = mysql_num_rows($query);
    if ($counter > 0){
        while ($data = mysql_fetch_array($query)){
            $name = $data["name"];
            $correct = $data["correct"];
            $time = $data["time"];
            $score = $data["score"];
            print "systemResult=$name\t\t\t$correct\t\t$time\t\t$score\n\n\n";
        }
    } else {
        print "systemResult=Error.";
    }
}
?>

Flash & AS3 are receiving the output and I've got it displaying on my game where I want it, the problem is the 'systemResult=' appears at the start of all outputs but the first one. So the high score table is something along the lines of:
name                  correct    time    score
alice                 19/20      38s     2182
systemResult=bob      17/20      68s     1827
systemResult=charlie  15/20      55s     1722

I know I could probably remove this with string manipulation but I wanna do this properly - am I going the right way about outputting the data, and if not, what's the right way to go?
Thank you
Answer: I assume you are retrieving the data and using the systemResult item.  If so, changing the code to the following should do the trick.
if ($counter > 0){
    print "systemResult=";
    while ($data = mysql_fetch_array($query)){
        $name = $data["name"];
        $correct = $data["correct"];
        $time = $data["time"];
        $score = $data["score"];
        print "$name\t\t\t$correct\t\t$time\t\t$score\n\n\n";
    }
} else {
    print "systemResult=Error.";
}

Printing database query results in AS3


Asymptotically $\binom{2n}{n}\approx\frac{2^{2n}}{\sqrt{\pi n}}$ or $\binom{2n}{n}\approx2^{2n}$?

Question: The Wikipedia entry about the binomial coefficient has the following (asymptotic) estimation for $n$ and $k$ that grow in the same rate (under "Bounds and asymptotic formulas")
$$\log\binom{n}{k}\approx nH_{2}\left(\frac{k}{n}\right)$$
where $H_{2}\left(\alpha\right)=-\alpha\log\left(\alpha\right)-\left(1-\alpha\right)\log\left(1-\alpha\right)$ is the binary entropy function
Which would imply
$$\binom{2n}{n}\approx2^{2nH_{2}\left(\frac{1}{2}\right)}=2^{2n}$$
However, the same paragraph has the following asymptotic estimation of the central binomial coefficient
$$\binom{2n}{n}\approx\frac{2^{2n}}{\sqrt{\pi n}}$$
Aren't these two contradictory? If not, why not and if so, which one is correct?
Comment: One cannot say that$$\log{(f(n))}\sim g(n)\iff f(n)\sim \exp{(g(n))}$$Consider, for example, $f(n)=n\exp{(n)}$ and $g(n)=n$.
Comment: Better to use Stirling formula $$n!\approx\sqrt{2n\pi}\frac{n^n}{e^n}$$
Answer: You're using the approximation symbol $\approx$ where Wikipedia uses the asymptoticity symbol $\sim$. The former is an informal way of saying that two expressions are approximately equal without specifying in which way or to what extent. By contrast, the latter makes a well-defined statement about the two sides: $f(x)\sim g(x)$ is defined to mean
$$
\lim\frac{f(x)}{g(x)}=1\;,
$$
where a particular limit process, typically $x\to\infty$, is specified or assumed from the context.
The two asymptotic statements that you cite, spelled out properly including the limit process, are
$$
\binom{2n}n\sim_{n\to\infty}\frac{2^{2n}}{\sqrt{\pi n}}
$$
and
$$
\log\binom n{\lambda n}\sim_{n\to\infty}-n\left(\lambda\log\lambda+(1-\lambda)\log(1-\lambda)\right)
$$
(where the logarithm can be taken for any base).
There is no contradiction because
$$
\log_2\left(\frac{2^{2n}}{\sqrt{\pi n}}\right)=2n-\frac12\log_2(\pi n)\sim_{n\to\infty}2n
$$
since
$$
\lim_{n\to\infty}\frac{\log n}n=0\;.
$$
By contrast, omitting the factor $\frac1{\sqrt{\pi n}}$ in the first result without taking logarithms would make it false.


Cauchy sum of ratio of sequences not converging.

Question: Prove if ${x_n}$ and ${y_n}$ are Cauchy and $x_n + y_n > 0$, for all natural n,
then $\frac{1}{x_n + y_n}$ cannot converge to zero.
Attempt: Suppose $x_n → a$ and $y_n → b$. Then $x_n + y_n → a + b$. Then since the sequences are Cauchy, they converge. Then $x_n$ and $y_n$ are bounded. Thus, there is a positive M real number such that $|x_n + y_n| < M$ . Then,  $|1/(x_n + y_n)| < 1/M$. I am assuming it cannot converge to zero since zero is not defined in the denominator.
Can someone please help me finish? Thank you very much.
Answer: You are basically done. Since $(x_n)$ and $(y_n)$ are Cauchy, they are bounded. In particular $(x_n + y_n)$ is bounded, so there is some constant $M$ such that  $|x_n + y_n| < M$ for all $n$. Then (and here is a little mistake in your attempt), we have $\left|\frac1{x_n + y_n}\right| > \frac1M$ for all $n$.
Now if $\frac1{x_n + y_n}$ did converge to $0$, then we could make its absolute value as small as we want by choosing a very large $n$. However, the above relation shows that this absolute value is always bigger than $\frac1M$.


How to delete uploaded image from server when working using Summernote Editor

Question: I have working Summernote editor with image upload, but i noticed that when i add an image content inside the editor it is uploaded successfully into my server folder without saving it yet, but when i delete the image inside the editor it is not remove from my server folder.
Answer: To Delete file form Server, you need to use onMediaDelete but usage varies with different summernote versions, sometimes difficult to find in the docs
FOR SUMMERNOTE 0.6.x
$(document).ready(function() {
    $('.summernote').summernote({
        height: "300px",
         onMediaDelete : function($target, editor, $editable) {
         alert($target.context.dataset.filename);
         $target.remove();
    }
    });
});

FOR SUMMERNOTE 0.7.x
$(document).ready(function() {
    $('.summernote').summernote({
        height: "300px",
        onMediaDelete : function(target) {
                deleteFile(target[0].src);
            }

    });
});

FOR SUMMERNOTE 0.8.x (Use Callbacks)
$(document).ready(function() {
    $('#summernote').summernote({
        height: "300px",
        callbacks: {
            onImageUpload: function(files) {
                uploadFile(files[0]);
            },

            onMediaDelete : function(target) {
                // alert(target[0].src)
                deleteFile(target[0].src);
            }
        }
    });
});

Javascript : Sample to Delete File using img src
function deleteFile(src) {

    $.ajax({
        data: {src : src},
        type: "POST",
        url: base_url+"dropzone/delete_file", // replace with your url
        cache: false,
        success: function(resp) {
            console.log(resp);
        }
    });
}

PHP: Sample to Delete Image afeter retrieving img src
<?php
  $src = $this->input->post('src'); // $src = $_POST['src'];
  $file_name = str_replace(base_url(), '', $src); // striping host to get relative path
        if(unlink($file_name))
        {
            echo 'File Delete Successfully';
        }
?>

Reference for Image Upload - Summernote v0.8 Image upload to Server
Answer: You can use this code here
<?php

// include Database connection file
require_once("../../resources/directories.inc.php");

// Return the domain uri
function url(){
  return sprintf(
    "%s://%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}

// Upload file into directory
if (isset($_FILES['file']['name']) && isset($_POST['upload_directory']) && isset($_POST['action']) && $_POST['action']=='upload_file') {
    if (!$_FILES['file']['error']) {
        $folder_dir = $_POST['upload_directory'];
        $name = rand(100,1000).'_'.date('Ymd');

        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $filename = $name.'.'.$ext;
        $destination = '../../uploads/'.$folder_dir.'/'.$filename; //change this directory
        $location = $_FILES["file"]["tmp_name"];
        move_uploaded_file($location, $destination);
        echo BASE_URL.'uploads/'.$folder_dir.'/'.$filename;
    } else {
        echo 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
    }
}

// Delete file from directory
if (isset($_POST['img_src']) && isset($_POST['delete_directory']) && isset($_POST['action']) && $_POST['action']=='remove_file') {
    $full_img_src = $_POST['img_src'];
    $folder_dir = $_POST['delete_directory'];

    $upload_dir_url = url().BASE_URL.'uploads/'.$folder_dir.'/';
    $file_name = str_replace($upload_dir_url, '', $full_img_src); // striping url to get file name
    $upload_path = '../../uploads/'.$folder_dir.'/'.$file_name; // path to delete from

    if(unlink($upload_path)){
        echo 'File removed successfully';
    } else {
        echo 'File could not be removed successfully';
    }
}

?>
Javascripts
    const lib_url = '<?php echo BASE_URL."resources/library/summernote.lib.php"; ?>';
$('.summernote_editor').summernote({
    tabsize: 2,
    height: 400,
    spellCheck: true,
    toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'underline', 'italic', 'superscript', 'subscript', 'clear']],
      ['fontname', ['fontname','fontsize']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['table', ['table']],
      ['insert', ['link', 'picture', 'video']],
      ['view', ['fullscreen', 'help', 'undo', 'redo']],
    ],
    callbacks: {
        onImageUpload: function(files, editor, welEditable) {
                        sendFile(files[0], editor, welEditable);
                    },
                    onMediaDelete : function(target) {
                        deleteFile(target[0].src);
                    }
    }
});

function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    data.append("action", 'upload_file');
    data.append("upload_directory", 'news');
    $.ajax({
        data: data,
        type: "POST",
        url: lib_url,
        cache: false,
        processData: false,
        contentType: false,
        success: function(url) {
            var image = $('').attr('src', url);
            $('.summernote_editor').summernote("insertNode", image[0]);
        }
    });
}

function deleteFile(src) {
    data = new FormData();
    data.append("img_src", src);
    data.append("action", 'remove_file');
    data.append("delete_directory", 'news');
    $.ajax({
        data: data,
        type: "POST",
        url: lib_url,
        cache: false,
        processData: false,
        contentType: false,
        success: function(resp) {
            console.log(resp);
        }
    });
}


What do LI, RI, LH, CH, RH mean in old soccer positions?

Question: I am reading an old newspaper published in the 1940s about a soccer game.
The positions were GK, RB, LB, RH, CH, LH, RW, RI, C, LI, and LW.
B is for backs and W is for wings which are obvious,
but I can't figure out what H and I mean.
Answer: This is the standard 2-3-5 formation, which was the most popular formation in the sport from the 1890s until about the 1930s, but which is now extremely archaic.

As you mentioned, the RB and LB are the right-back and left-back, the two defensive positions. They would have been positioned similarly to the two center-backs in a modern 4-4-2 system.
The RH, CH, and LH are the right-half, center-half, and left-half, collectively known as "half-backs". These, at the time, were analogous to modern midfielders, but over time they moved backwards into defence and the full-backs were moved wider to accommodate them. "Center-half" is now an archaic synonym for "center-back", while the concept of "right-half" and "left-half" no longer exists in the modern game.
The five upfront players were the outside-left (or left-wing), the inside-left, the center-forward, the inside-right, and the outside-right (or right-wing). In your newspaper article, "RI" would denote the inside-right and "LI" would denote the inside-left - again, these are concepts that no longer exist.
Answer: What you're looking at here is the pyramid formation or a close variation. In modern terms, we'd denote this as a 2-3-5 formation:

GK is the goalkeeper
[R/L]B are the right and left fullbacks, essentially what we'd call the defenders today.
[R/C/L]H are the right, centre and left halfbacks, what we'd call midfielders today.
The forward line is from right to left the right winger (RW), the right inside (RI), the centre forward (C), the left inside (LI) and the left winger (LW).


what's the meaning of the master process creates the listen socket and sends it to interested workers in node?

Question: nodejs cluster api says :The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly.
I ' M fused about what is the listen socket  and how it can send to workers.moreever. what the relationship between the listen socket and the incomming connections.
Comment: What is the question in this? If you dont got something we can reliably answer on then we cant help you...
Comment: Did my answer help? It'd be appreciated if you set it as the accepted answer, or at least give some feedback!
Answer: The listen socket is what Node (or any networked software) will use to map an external request or incoming data to the application code that you've written to handle it.

The second approach is where the master process creates the listen
  socket and sends it to interested workers. The workers then accept
  incoming connections directly.

Means that the master script will create a port that can be shared transparently between the workers, allowing you to connect to port 3000, for example, and have a bunch of workers deal with the incoming request.
See this diagram below. In this instance Worker 2 ends up dealing with the request:
Request -> [localhost:3000] -> Worker 1
                            -> Worker 2 -> Handle Request -> Send back result
                            -> Worker 3
                            -> Worker 4

This allows you to write applications that are more fault tolerant and responsive, because if there's an issue in one of the workers, the master (if configured correctly) will send the request to a worker that isn't as busy or is operating normally.


NumberFormatException: how to deal with it

Question: I have a simple application which allows users to input a divisor, a divident and then calculates the quotient.
I'm using vaadin as framework but I don't think that matters.
So I've been thinking about the exceptions that can occurr and these are the ones i have identified:
-Division by 0: ArithmeticException;
-Users typing a string rather than a number: InputMismatchException
Here is the class that creates the form and deals with the exceptions:
package my.vaadin.project.exceptionTest;

import java.awt.Component;
import java.util.InputMismatchException;

import com.vaadin.server.Page;
import com.vaadin.shared.Position;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.event.Action;

public class Calculation extends CustomComponent{
    final VerticalLayout vl = new VerticalLayout();
    final TextField dividend = new TextField();
    final TextField divisor = new TextField();

    final TextField result = new TextField();
    final Button resetButton = new Button("Reset");
    private int divisionResult = 0;
    Button button = new Button("Click Me");

    public Calculation(){
        dividend.setCaption("Enter the dividend:");
        divisor.setCaption("Enter the divisor:");

        result.setCaption("Result");
        result.setReadOnly(true);
        button.addClickListener( new Button.ClickListener(){
            @Override
            public void buttonClick(ClickEvent event) {
                System.out.println("this is a test");
                validateInputs();
            }
        });
        resetButton.addClickListener(new Button.ClickListener(){
            @Override
            public void buttonClick(ClickEvent event) {
                setDividend("");
                setDivisor("");
                setResult("");
            }
        });
        vl.setMargin(true);
        vl.setSpacing(true);
        vl.addComponents(dividend, divisor, button, result );

    }//end of constructor
    public void validateInputs(){
        System.out.println("theDivisor is " + getDivisor() + " theDividend " + getDividend());
        try{
            divisionResult = ( Integer.parseInt(getDividend()) / Integer.parseInt(getDivisor()));
        }
        catch(ArithmeticException arithmeticException){
            System.err.println("Zero is an invalid denominator!");
            createError("Divisor can't be 0!! Please enter a number  > 0!");
        }
        catch(InputMismatchException inputMismatchException){
            System.err.println("The dividend or divisor are not a number! Please enter a valid number!");
            createError("The dividend or divisor are not a number! Please enter a valid number!");
        }
    }//end of validateInputs
    public String getDivisor(){
        return divisor.getValue();
    }
    public String getDividend(){
        return dividend.getValue();
    }
    public void setDivisor(String newDivisor){
        divisor.setValue(newDivisor);
    }
    public void setDividend(String newDividend){
        dividend.setValue(newDividend);
    }
    public void setResult(String newResult){
        result.setValue(newResult);
    }
    public void createError(String errorString){
        String error = errorString;
        Notification notif = new Notification(
                error,
                Notification.TYPE_ERROR_MESSAGE
            );
            notif.setDelayMsec(20000);
            notif.show(Page.getCurrent());
    }
}

I use the try catch statement when I calculate the quotient (but I haven't displayed the result as yet)
If I type 0 in the divisor then I get what I expect, an ArithmeticException is thrown and dealt with.
However, if I type a string in the fields I would have thought that the InputMismatchException would take care of it but in fact this is the message I get in the console http://pastebin.com/z8U6bUYg
I looked the NumberFormatException up and I'm not sure I understand what to do and why that happens. As you can see from the code I'm parsing the string to integers but it seems that the compiler doesn't like it. Do I have to add a catch statement and deal with the NumberFormatException too? Shouldn't the InputMismatchException be enough?
Please let me know what you think
Comment: Under what circumstances do `Integer.parseInt(String)` or integer division throw a `InputMismatchException`? That's only thrown by `Scanner`, [according to its documentation](https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html).
Comment: `NumberFormatException: For input string: "iuy"` suggests the input data, possibly collected through an input/textfield, you're trying to convert to a number is not actually a number, more specifically `iuy`. Looking at your code I don't see anything that could through the `InputMismatchException`, while `Integer.parseInt` does throw a `NumberFormatException` if it can't convert the string to a number, so you're probably _expecting_ the wrong exception...
Comment: Possible duplicate of [What is a NullPointerException and how can I fix it?](http://stackoverflow.com/questions/39849984/what-is-a-nullpointerexception-and-how-can-i-fix-it)
Answer: If you look at the documentation of Integer.parseInt it is specified this:

Throws:
  NumberFormatException - if the string does not contain a parsable integer.

Instead, the InputMismatchException documentation specify this:

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

Therefore the program seems to behave correctly and accordingly to the specifications.
This means you should catch NumberFormatException instead of InputMismatchException.
Answer: Incompatibility issue
I have the same issue on Android Studio 0.8.7. But it is working fine with Android Studio 2.1. I think it should be fixed by updating Android Studio and Gradle Plugin to latest version.
good luck
Answer: There are very rare occasions where you would catch RuntimeExceptions. Especially in your business code it's a bad pattern.
Make sure you validate your input values before you process them. You know that the divisor must not be zero, so, in your example, you should reject the input of zero for the divisor in your GUI, whatever it is (HTML input form, Swing TextField etc.).
At the latest, your setter setDivisor() MUST not accept a 0 and throw itself a Exception, e.g. an IllegalArgumentException.
Moreover, you should separate the concerns of your code. Don't mix the calculation of numbers with your GUI. The calculation should take place in another class that does not know about your GUI.
PS/EDIT:
Trying to explain why catching RuntimeExceptions is not a good idea:
Taken from Oracle Docs: http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

The third kind of exception is the runtime exception. These are
  exceptional conditions that are internal to the application, and that
  the application usually cannot anticipate or recover from. These
  usually indicate programming bugs....

In your case the application CAN anticipate and recover from the fact that the user entered an invalid divisor. And even more, you should try your best to avoid letting the user enter invalid data.
Moreover, some other questions on SO, where people agree on the fact that catching RuntimeExceptions are a code smell.

Yes, catching any RuntimeException is almost always a code smell. The
  C2 Wiki seems to agree. Is Catching a Null Pointer Exception a Code Smell?

Another one from a more official source

Unchecked exceptions: RuntimeException also extends from Exception.
  However, all of the exceptions that inherit from RuntimeException get
  special treatment. There is no requirement for the client code to deal
  with them, and hence they are called unchecked exceptions.
  http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=1

It goes on and on...

Likewise, programs must not catch RuntimeException, Exception, or
  Throwable. Few, if any, methods are capable of handling all possible
  runtime exceptions. https://www.securecoding.cert.org/confluence/display/java/ERR08-J.+Do+not+catch+NullPointerException+or+any+of+its+ancestors
Comment: Why? The exception tells you it's invalid, and `parseInt()` already has to check that. Why repeat all that code?
Comment: See the links to various websites that support my proposal. If you like we may discuss this issue more in detail beyond this thread. I'd be even happier if you withdrew the -1 vote unless you prove your theory right.
Comment: thanks guys, I will update my code and use the right exceptions then


Why to report R squared?

Question: If adjusted R squared is superior to R squared, then why do statistical software continue to report the latter? Is there any kind of situation when a researcher may prefer to use R squared instead of adjusted R squared?
Comment: What kind of regression are you dealing with? If I am not mistaken, for linear regression, there is no difference between the R-squared and the adjusted R-squared. So in this case it is very appropriate to use the plain R-squared value.
Comment: A linear one. But statistical packages provides both measures. That's why I wonder why.
Comment: Well, according to [Wiki](http://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2), the equation is a bit different even for linear regression (`p=1`). But the whole point of adjusted R-squared is "_The use of an adjusted R2 is an attempt to take account of the phenomenon of the R2 automatically and spuriously increasing when extra explanatory variables are added to the model._". Linear regression doesn't have any additional explanatory variable, because it is the most primitive type of regression.
Comment: @alesc, I know that. What I don't know is why to report both values.
Comment: What are you trying to prove with your R-squared value? Do you compare different regression models? If you compare linear and non-linear regression models, then it would make sense to use adjusted R-squared, otherwise the plain R-square will be sufficient. But then again, you can also use the adjusted R-squared even for linear regression :) I personally would not report both values. So choose one metric and report only that value (either R-square or adjusted R-square).
Comment: I try to prove nothing. Looks like you misread my post. "... statistical software continue to report ", not me.
Comment: The following post may give a good answer to this question when to use adjusted or unadjusted: http://stats.stackexchange.com/questions/29185/adjusted-r2-versus-r2-in-multiple-regression
Comment: My best guess would be for legacy reasons. A lot of research uses the plain R-square metric and if you want to make an upgrade or repeat the experiment, you should use the same metrics as the original research (so that you can compare the results).
Comment: @alesc, do you mean *simple* linear regression when you write linear regression?
Comment: I have had many clients who preferred $R^2$ because they wanted the results to look as good as possible and this is always larger than the adjusted $R^2$ :-).  I rarely use $R^2$, for [reasons explained elsewhere](http://stats.stackexchange.com/questions/13314/is-r2-useful-or-dangerous/13317?s=1|0.0000#13317).
Answer: Under conditions for instance explained here, $R^2$ measures the proportion of the variance in the dependent variable explained by the regression, which is a natural measure. Adjusted $R^2$ does not have this interpretation, as it modifies the $R^2$ value.
So while adjusted $R^2$ has the indisputable advantage of not increasing automatically when the number of regressors goes up, you pay a price in terms of how you can interpret the measure.
Note I am not advocating the use of one or the other, just giving a possible reason for why people still use the standard $R^2$.
Comment: Yes, but as we can write $R_{adj.}^2=1-\frac{n-1}{n-K}+\frac{n-1}{n-K}R^2$ and, obviously, $\frac{n-1}{n-K}\to1$ (at least when, as is mostly assumed, $K$ remains fixed as $n\to\infty$), we have that $R_{adj.}^2-R^2=o_p(1)$, so that does not seem to be a reason to prefer one over the other.
Comment: Quick question: is it perhaps true that $R^2_{adj.}$ is a consistent estimator of the population $R^2$ under some conditions, e.g. a well-specified model? Then it would make sense to report $R^2_{adj.}$ in place of $R^2$.
Comment: Well...do we define population $R^2$ as $1-\sigma^2/Var(y)$? If so, writing $R^2_{adj.}=1-\frac{s^2}{\sum_i(y-\bar{y})^2/(n-1)}$ ($s^2$ the d.f.-adjusted variance estimate dividing by $n-K$) shows that both the estimator of the error variance in the numerator and that of the variance of $y$ in the denominator are unbiased for the respective population parameters, $E(s^2)=\sigma^2$ and $E[\sum_i(y-\bar{y})^2/(n-1)]=Var(y)$. But that does not make the ratio an unbiased estimator of the ratios of the parameters, as the expectation operator does not pass through nonlinear functions in general.
Comment: Thanks. Perhaps I should have posted my comments as a separate question, then I could have upvoted your answers. Since I suspected similar things have been asked, I just hoped for a short confirmation/disconfirmation, comment style. You were more explicit than that, I appreciate it!
Comment: $K$ is of course the number of regressors
Comment: So perhaps then $R^2_{adj.}$ is unbiased while $R^2$ is biased? I think this could be rather relevant given that $R^2_{adj.}$ is consistent.
Answer: Adjusted R-squared is useful for comparing different regression models. This task cannot be accomplished by R-squared which, as Others have already said, has another informative goal, that is expressing the proportion of variance of the dependent variable that is explained by the regression model under investigation.

Why to report R squared?


Atualizar Python 3x

Question: Tenho a versão 3.7.3 do Python (apenas para estudos) no meu Raspbian Buster e gostaria de atualiza-lo para a versão mais recente (3.8.3).
Já tentei utilizar sudo apt update e sudo apt upgrade mas o sistema não atualizou informando que os pacotes estão atualizados.
Como proceder neste caso?
Comment: pelo o pouco tempo que venho usando exclusivamente linux, notei que python só é atualizado para versões recentes quando os desenvolvedores da distro escolhem fazer, ai o apt update/upgrade vai funcionar, se vc quer python3.8 instalado vc teria que fazer isso explicitamente, trate como um segundo programa, um programa independente, e ja adiantando não exclua o python 3.7 pois pode haver funções do sistema dependentes desta versão e a exclusão pode quebrar o sistema, ja vi em foruns relatos de tal, não era rasp, mas melhor não arriscar
Answer: O Python que vem no sistema é usado, dentre outras coisas, para rodar as diversas aplicações que estão instaladas e que foram feitas em Python. É claro que você pode usá-lo para programar em Python, mas a maioria das distribuições não vai ter a versão mais nova. Especialmente uma distribuição baseada no Debian (que prima pela estabilidade e não por estar "na crista da onda") como o Raspbian.
Já o Arch Linux, por exemplo, tem um modelo de "rolling release" e sempre está atualizado e nesse momento que escrevo a versão do Python no Arch é 3.8.2 (essa é a última versão até o momento e a 3.8.3 ainda está como "release candidate").
Mas o melhor mesmo quando se programa em Python é usar um ambiente virtual ao invés de usar o Python que vem com o sistema. Um ambiente virtual é isolado e separado do Python do sistema e com isso você pode usar differentes versões do Python e de quaisquer biblioteca que queria usar sem correr o risco de prejudicar alguma outra aplicação.
Para se trabalhar com ambientes virtuais existem algumas opções, incluindo distribuições completas (com repositórios próprios) como o anaconda (provavelmetne a opção mais fácil). Com o anaconda você cria um ambiente virtual e especifica a versão exata do Python que quer usar.
Outras opções para usar ambientes virtuais são pipenv, poetry, ou até o próprio módulo venv que já vem no python 3. Mas acredito que essas opções só gerenciem as bibliotecas e não a versão do python (você trabalha com um python isolado, mas a mesma versão do sistema). Para trabalhar com diferentes versões do python tem o pyenv, que certamente é usado junto com algumas das opções para trabalhar com ambientes virtuais.

Atualizar Python 3x


SQL AlwaysOn auto fail over due to disk

Question: All,
I'm in the process of evaluating SQL AlwaysOn, and everything is failing over as expected, except in one circumstance, when the disk goes belly up.  In this case, SQL does nothing, other than present the following two errors.

The error makes sense, as I've dropped the drive that also contains TempDB, but what concerns me, is dropping the drive doesn't seem to be catastrophic enough to cause a fail over.
Am I missing something here?  I tried adding the drive to wsfc, but because its not a clustered drive, it doesn't seem that it will work, as each individuals servers drive shows up as a separate resource.
Edit 1:
The only event log entry is as follows.  Once again, pretty much an expected error.
The operating system returned error 21(The device is not ready.) to SQL Server during a read at offset 0x00000000382000 in file 'E:\Data\vcdb.mdf'. Additional messages in the SQL Server error log and system event log may provide more detail. This is a severe system-level error condition that threatens database integrity and must be corrected immediately. Complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online.
Comment: I guess as you can see, SQL also doesn't seem to see a fault in the DB either.
Comment: So... did you check the event log? Did it have anything in there?
Comment: Hi Mark, see my edit.  Nothing that i wouldn't expect.
Answer: Losing a database file, even one as critical as the tempdb file, is still a database-level event.
According to this Microsoft Technet article:
(Failover and Failover Modes (AlwaysOn Availability Groups) )

Issues at the database level, such as a database becoming suspect due to the loss of a data file, deletion of a database, or corruption of a transaction log, do not cause an availability group to failover.
Comment: Thanks, although i would still like to see a "disk" failure cause a fail over.  Meaning a HW event not a DB event.  The DB going offline would merely an effect of the HW going offline.
Comment: I completely agree. Common sense expectations would see a failover with disk failure. But I think the documentation here is distinguishing between the SQL Server Service availability and the underlying OS/hardware availability. It does have a "Lawyer Ball" flavor to it, but I think this is intended functionality (or at least, MS considers it "as designed")

SQL AlwaysOn auto fail over due to disk


contains() method in java.util.HashSet doesn't behave as i expected from it

Question: This is the java main() method:

    public static void main(String[] args) {

        HashSet set = new HashSet();
        Mapper test = new Mapper("asd", 0);
        set.add(test);

        System.out.println(new Mapper("asd", 0).equals(test));
        System.out.println(set.contains(new Mapper("asd", 0)));

    }

and my Mapper class is :
class Mapper {

String word;
Integer counter;

Mapper (String word, Integer counter) {

    this.word = word;
    this.counter = counter;

}

public boolean equals(Object o) {

    if ((o instanceof Mapper) && (((Mapper)o).word == this.word)) {

        return true;

    }

    return false;

}

}

and the result is :

true
false

From HashSet specifications, at this method I read this : "Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)). "
So, can anyone explain me where i'm wrong? Or ...?
Thanks.
Comment: Just to add something, you should use the String `equals()` method (instead of the `==`, that's reference test) if you want to compare it's values.
Answer: You need to implement a proper hashCode() function.
public int hashCode() {
  // equal items should return the same hashcode
}

The Java utilites java.util contain a lot of classes which rely on hashing.  To allow one to override equals() as they see fit means that one must also properly override hashCode() to match.
A correct implementation of hashCode() would return the same hash for any two objects where equals() returns true.  Hash related functions check the hashes for equality before checking to see if the objects equal (to resolve hash collisions).
Comment: ... and while you are at it, correct (or clearly document) your equals to not use referential equality for the string. In this case, you get away with it because "asd" is used twice in the same class file. But If you had read the string from user input, for example, the first comparison would have failed, too.
Comment: @Dilum : Why that? I know that strings are created in a string's pool of memory created apart when JVM is initialized.
Comment: @artaxerxe Strings are Objects.  The default implementation of hashCode() is to return a unique number for each instance.  If you create two strings ala `a1 = new String("a"); a2 = new String("a");` one would probably expect `a1 == a2` to be `false` as they are not the same object (due to the two new calls).  This means that for Strings (and other objects) `a1.equals(a2)` is typically much, much safer.
Comment: @artaxerxe What you said is only true of strings that are explicitly intern'ed. ( http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#intern%28%29 ). Lets say you read an XML document, and you get an element with attributes containing 'asd' and '0'. Those are not interned strings. That's one of countless cases where the string is not interned. Try this one to illustrate my point: System.out.println(new Mapper("asd".toUpperCase().toLowerCase(), 0).equals(test));
Answer: The hashCode contract says that if two objects are equal, they should have the same hash code. Collections like HashSet assume that this is upheld.
Object's implementations of equals and hashCode are based on addresses (or object IDs). If you override equals to do a content comparison, you should override hashCode to generate a hash based on content.


Purpose of this javascript, what kind of design patten it used?

Question:     if (!window['console']) {
        window.console = {
        log: function(msg) {}
        }
    }

$(window).ready(function() {
    Site.onReady();
});

    var Site = {
        host: null,
        path: null,
        etc..

And there have var Helpers, var Site, looks pretty good, but can't understand the purpose? Anyone who knows that?
Answer: if (!window['console']) {
    window.console = {
    log: function(msg) {}
    }
}

This checks to see if there's anything currently assigned to window.console already and if there's not, it assigns a custom object that has a 'log' function. This makes window.console.log usable no matter what, and if there's already a native (or earlier defined) version of the function, it will be used.
$(window).ready(function() {
    Site.onReady();
});

    var Site = {
        host: null,
        path: null,
        etc..

I have no idea what this is for, but Site is undefined at the time it is placed into the anonymous callback for $(window).ready(), which is something that should be avoided (just place the $(window).ready() below where site is defined)
As for this specific snippet:
$(window).ready(function() {
        Site.onReady();
    });

this passes an anonymous function to the $(window).ready() function, which will call it when the DOM is ready. Using an anonymous function directly avoids the need to name a function and then pass it in later.
function myFunc() { //we can use myFunc anywhere now, which may be unwanted
    Site.onReady();
}
$(window).ready(myFunc);

Lastly:
   var Site = {
            host: null,
            path: null,
            etc..

The var myVar = {key1:"value", key2:"other_value"}; syntax creates a new object with keys and values that can be used like this: myVar.key1 = "newValue!"
Answer: Looks like it initializes several global objects that are expected on the page. For example console, which is available in Firefox/Firebug for logging, but not other browsers. So by checking for existence of window['console'] and adding it when necessary, you can trust in the JavaScript code you can call console.log() without causing an error.
I assume Site, Helpers, etc all do something similar.
Answer: its defining a 'console' object literal on the window object, if it is not already there, which has a function log.  This means in your code you can write
console.log('something')

even if the browser doesn't support it.