Q:

Intuition behind Fourier and Hilbert transform

In these days, I am studying a little bit of Fourier analysis and in particular Fourier series and Fourier/Hilbert transforms. Now, I am confident with the mathematical definitions and all the formalism, and (more or less) I know all the main theorems. What I don't really understand is why they are so important, why these concepts are defined in that precise way.
Could you explain to me why all these concepts/tools are so significant and useful in (applied) mathematics? Could you give me some intuition behind them?
I am not particularly interested in mathematical formulae. I would simply like to know what these definitions really mean.
Pretend to be talking with someone smart, very curious but not very knowledgeable about mathematics.
Of course, I encourage not only mathematicians but also engineers and physicists to reply. Having a truly physical interpretation of those concepts would be great!!
Very last thing: I would really love to have some unconventional and "personal" interpretation/point of view.
Thank you very much for any help!!

A:

The Fourier transform diagonalizes the convolution operator (or linear systems). In other words, if you find convolution non-inuitive, it gets simplified into a simple point-wise product. It happens that the eigenvectors are cisoids (or complex exponentials), hence it gives you a frequency-like interpretation. An operator that makes an essential operation simpler, like the $\log$ turns multiplies into adds, is an important one. [EDIT1: see below for details].
The Hilbert transform is even more important. It turns a real function into its most "natural" complex extension: for instance it turns a $\cos$ into a cisoid by adding $\imath \sin$ to it. Thus, the complex extension satisfies Cauchy–Riemann equations.
Hilbert remains quite mysterious to me (Fourier as well, to be honest, I studied wavelet to understand Fourier). S. Krantz writes, in Explorations in Harmonic Analysis with Applications to Complex Function Theory and the Heisenberg Group, Chapter 2: The Central Idea: The Hilbert
Transform:

The Hilbert transform is, without question, the most important
  operator in analysis. It arises in so many dierent contexts, and all
  these contexts are intertwined in profound and influential ways. What
  it all comes down to is that there is only one singular integral in
  dimension 1, and it is the Hilbert transform. The philosophy is that
  all signicant analytic questions reduce to a singular integral; and
  in the first dimension there is just one choice.

[EDIT1] We talked about Fourier transforms as they were unique. Let us keep them loose. There are many Fourier flavors. In the continuous case, you can look for explanations in Fourier transform as diagonalization of convolution. In a discrete case, convolution can be "realized" with (infinite) Toeplitz matrices. In the finite length setting, cyclic convolution matrices can be diagonalized by the Fast Fourier transform.
[EDIT] In addition, F. King has produced two volumes of a  book on the Hilbert transforms in 2009.

A:

The Fourier series is a way of building up functions on $[-\pi,\pi]$ in terms of functions that diagonalize differentiation--namely $e^{inx}$. If $L=\frac{1}{i}\frac{d}{dx}$ then $Le^{inx}=ne^{inx}$. That is $e^{inx}$ is an eigenfunction of $L$ with eigenvalue $n$. The fact that all square integrable functions on $[-\pi,\pi]$ can be expanded as $f = \sum_{n=-\infty}^{\infty}c_n e^{inx}$ is quite a nice thing. If you want to apply the derivative operator $L$ to $f$, you just get $Lf = \sum_{n=-\infty}^{\infty}nc_ne^{inx}$. More generally, if $f$ has $N$ square integrable derivatives, then the $N$-th derivative is
$$\frac{1}{i^{n}}f^{(n)}=L^{N} f = \sum_{n=-\infty}^{\infty}n^{N}c_n e^{inx}.$$
Diagonalizing an operator makes it easier to solve all kinds of equations involving that operator. The only issue is this: How do you find the correct coeffficients $c_n$ so that you can expand a function $f$ in this way? For the ordinary Fourier series,
$$
c_n = \frac{1}{2\pi}\int_{-\pi}^{\pi} f(t)e^{-int}dt.
$$
On a finite interval, this is great. But what happens if you want to work on the entire real line? If you work on larger and larger intervals, then you get more and more terms. You need terms with larger and larger periods, and all multiples of those. In the limit of larger intervals, you need an integral to sum up all the terms, with every possible periodicity. That is, you can expand a square integrable $f$ as
$$f(x) = \int_{-\infty}^{\infty}c(s)e^{isx}ds.
$$
As before, applying operations of $L=\frac{1}{i}\frac{d}{dx}$ is easier using this representation of $f$:
$$
\frac{1}{i^{N}}f^{(N)}(x)=  L^{N}f = \int_{-\infty}^{\infty}s^{N}c(s)e^{isx}ds.
$$
You can see that the discrete and the continuous cases are remarkably similar. And, based on that, how might you expect to be able to find the coefficient function $c(s)$? As you might guess,
$$
c(s) = \frac{1}{2\pi}\int_{-\infty}^{\infty}f(x)e^{-isx}dx.
$$
The Fourier transform is a way to diagonalize the differentiation operator on $\mathbb{R}$.
The reason that the discrete and continuous Fourier transforms are so important is that they diagonalize the differentiation operator. One way to view the effects of diagonalization is that you turn the operator into a multiplication operator. You can see how that makes solving differential equations a lot easier. In the coefficient space all you do is to divide in order to invert.
It's the same way with a matrix: if you have a big matrix equation
$$Ax = y,$$
and if $A$ is symmetric, then you can find a basis $\{ e_1,e_2,\cdots,e_n \}$ where $Ae_k = \lambda_k e_k$. Then, if you can expand $x$ and $y$ in this basis
$$x = \sum_{k=1}^{n} c_k e_k \\y = \sum_{k=1}^{n} d_k e_k.$$
Then the new equation is solved by division:
$$Ax = y \\ \sum_{k=1}^{n} c_k \lambda_k e_k = \sum_{k=1}^{n} d_k e_k \\
c_k = \frac{1}{\lambda_k} d_k e_k.$$
So if you know how to expand $y$ in the $e_k$ terms as $\sum_{k}d_k e_k$, then you can get the solution $x$ by division on the coefficients
$$x = \sum_{k=1}^{n} \frac{1}{\lambda_k} d_k e_k$$
(Assuming none of the $\lambda_k$ are $0$.)
The discrete and continuous Fourier transforms are a way to diagonalize differentiation in an infinite-dimensional space. And that allows you to solve linear problems involving differentiation.
Hilbert Transform: The Hilbert transform was developed by Hilbert to study the operation of finding the harmonic conjugate of a function. For example, the function $f(z) = z^2=(x+iy)^2=x^2-y^2+i(2xy)$ has harmonic real and imaginary parts. Hilbert was trying to find a way to go between these two components (in this case $x^2-y^2$ to $2xy$.) The setting of this transform is the upper half plane. If you start with a function $f(x)$, find the function $\tilde{f}(x,y)$ that is harmonic in the upper half plane, and then find $g(x,y)$ such that $f(x,y)+ig(x,y)$ is holomorphic in the upper half plane, then the Hilbert transform maps $f$ to $g$.
Because $i(f+ig)=-g+if$ is also holomorphic, then the transform maps $g$ to $-f$, which means that the square of the transform is $-I$. In this setting, the Hilbert transform turns out to be concisely expressed in terms of the Fourier transform if you work with square integrable functions.


Q:

Oracle SQL create identity column in nested table

I'm making a table which contains nested table:
create DOCUMENT as OBJECT (
    DOC_ID NUMBER,
    DESCRIPTION VARCHAR(1000));

create type documents_t is table of DOCUMENT;

create table projects (
    ID NUMBER GENERATED ALWAYS AS IDENTITY ,
    DOCUMENTS documents_t)
    NESTED TABLE DOCUMENTS STORE AS documents_nested(
        (PRIMARY KEY(nested_table_id, DOC_ID)) ORGANIZATION INDEX);

This works ok, but I can't seem to find how to make the nested table's primary key as identity column. any suggestions?
Thanks

A:

Please find the code snippet,
CREATE SEQUENCE seq_documents
 START WITH     1
 INCREMENT BY   1
 NOCACHE
 NOCYCLE;

CREATE OR REPLACE TYPE documents_q AS OBJECT
(
   doc_id      NUMBER,
   description VARCHAR2(1000),
   CONSTRUCTOR FUNCTION documents_q(p_description VARCHAR2) RETURN SELF AS RESULT
);

CREATE OR REPLACE TYPE BODY documents_q AS
   CONSTRUCTOR FUNCTION documents_q(p_description VARCHAR2) RETURN SELF AS RESULT IS
   BEGIN
      self.doc_id      := seq_documents.nextval;
      self.description := p_description;
      RETURN;
   END;
END;
/

CREATE TYPE documents_t AS TABLE OF documents_q;

create table projects (
    id NUMBER GENERATED ALWAYS AS IDENTITY ,
    documents documents_t)
    NESTED TABLE documents STORE AS documents_nested(
        (PRIMARY KEY(nested_table_id, doc_id))  ORGANIZATION INDEX);

INSERT INTO PROJECTS(documents) VALUES (documents_t(documents_q('Description One'),documents_q('Description Two')));

SELECT * FROM projects;

Please let me know if it gives you the solution. Thank you


Q:

Being redirected to login page after being already logged in

I have a login form and I'm logging myself in with correct credentials. When you are logged in I did a Redirect to my "about" page (used about page to test this functionality).
I did the above with the following snippet
        $input = Input::all();
        $login = Auth::attempt([
            'username' => $input['username'],
            'password' => $input['password']
        ]);

        if($login){
            return Redirect::to('about');
        }
        else{
            dd('not logged in!');
        }

This snippet is working perfectly
But now in my route to the about page I add ->before('auth'); So if I'm not logged in that I'm going to be redirected to the login page and if I'm already logged in to continue.
Code snippet:
Route::get('about', function(){
    $title = 'About';
    return View::make('about')->with('title', $title);
})->before('auth');

But by adding ->before('auth');, I'm always being redirected to the logging page even after logging in with the correct credentials. So I log in and normally I expect to be redirect to the about page but instead I'm being redirect to the login page again.
What am I doing wrong?
EDIT
Did some more debugging and this is what I've found out:
redirect to my about route and executing this:
Route::get('about', function()
{
    dd( Auth::check() ); // This returns false
});

But instead of redirecting to my route I'm tried:
if($login){
    dd( Auth::check() ); // This returns true
}

So after redirecting it seems I'm getting logged out or something like that??

A:

You should have an Auth filter and need to check whether logged in/out, like :
Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::to('login');
});

And this (filter) code should be added in app/filters.php and your route (what you have)
Route::get('about', function(){
    $title = 'About';
    return View::make('about')->with('title', $title);
})->before('auth');

Also, you can use it as given code below
Route::get('about', array('before' => 'auth' ,function()
{
    $title = 'About';
    return View::make('about')->with('title', $title);
}));

Update :
Also, if you are using database for session then make sure that primary key is id in the model (User Model) and if not then set it manually, like
protected $primaryKey = "IdOfTheCustomIDFieldInTheTable";


Q:

How Should I Store A Value for a Rails Application Which Changes Periodically but Needs To Be Accessible to All Users?

I have an API only application built in Rails, which requires an encrypted login to receive a token. Subsequently, requests for data from the API are authenticated with the token value in the header of the request.
I have another Rails application which uses this API for a few different things. Currently I have it set up to authenticate before making any request, which gets a token for that request.
This is fine, except that it sets up a potential race condition once the application is available to the public. It's possible that two requests could come in at virtually the same time, resetting the token twice, making one of the subsequent requests for data us a token that is no longer valid.
I wanted to use a $global variable to store the token and the date/time it was refreshed so that it's always available to all users and only refreshes the token if it is more than a couple of hours old.
This would solve the race condition problem, but from everything I am reading USING GLOBAL VARIABLES IN RAILS IS BAD. It seems to me this use case is an exception, but I want to do it the right way.
Is my only option to store these values in my own database? It seems silly to set up a data model for a table that will only ever contain two columns and two rows, but I don't know if that is the Rails Way(TM) or the Best Way.
Any advice is appreciated.

A:

You could use Rails' cache to do that. It gets stored in memory, or in a volatile database such as Redis. You could have something like:
def a_cool_token
  Rails.cache.fetch("a_cool_token", expires_in: 2.hours.to_i) do
    a_method_to_regenerate_a_cool_token
  end
end

What will happen is:

When using a_cool_token to pass it to a request it will try to fetch it from cache;
In case that cache key is expired or undefined it returns a_method_to_regenerate_a_cool_token;
When the time set on expires_in passes the key becomes invalid.

You can always use a more statefull cache key, using some database query to build it, like:
Rails.cache.fetch("a_cool_token/#{some_timestamp_that_gets_updated_with_a_cool_token}", expires_in: 2.hours.to_i)

Implementing def some_timestamp_that_gets_updated_with_a_cool_token could retrieve when the token was last updated, avoiding stale responses if something else changes the token outside a_cool_token
I hope this helps to point you into a "good" solution.


Q:

Does null coalescing operator cache the result in c#

I know that doing (myValue ?? new SomeClass()) is similar to (myValue == null ? new SomeClass() : myValue)
But out of curiosity, is there any performance benefit when I call a function, say
(getResult() ?? new SomeClass()). Will getResult() get executed twice? It seems unintuitive since I've specified the method call only once.

A:

Well, if by "caching" you mean storing it in a temporary variable, then yes.
This construct:
var result = (getResult() ?? new SomeClass());

can be thought of to be equivalent to this:
var <temp> = getResult();
if (<temp> == null)
    <temp> = new SomeClass();
result = <temp>;

This also tells you that the second part, the operand after ?? isn't executed at all if the first operand is not null.
So to answer your concrete questions:

Each operand is evaluated at most once
The second operand is only evaluated if the first one evaluates to null

Note also that you can chain these:
var result = first() ?? second() ?? third() ?? fourth();

Which results in:

Evaluates first()
If first() evaluated to null, evaluates second()
If second() evaluated to null as well, evaluates third()
If all of the above evaluated to null, finally evaluates fourth

The result is the first (no pun intended) non-null value returned.

This type of code is about to get even better in new C# with the new ?. operator:
var result = first?.second?.third;

This is basic . handling, ie. it will read the second member of first, and then the third member of whatever second is, but it will stop at the first null, and will also make sure to evaluate each step only once:
(obj as IDisposable)?.Dispose();

obj as IDisposable will only evaluate once.
TryGetObjectToSave()?.Save();

Will only call TryGetObjectToSave() once, and if it returns something, the Save() method on that something will be called.


Q:

How do locals (short of drilling) determine that lake ice is safe for skating, ice fishing, snowmobiling, skiing?

This question is not a duplicate of either (1)  Ice skating on a frozen lake -- how thick should the ice be?, which only asks how thick the ice should be; or (2) How to determine the thickness of ice?, which only asks how to determine how thick the ice is.
When I was a child, we skated on a couple of lakes in Connecticut.  One day my father would declare that "It's safe now" and off we would go.  No one ever fell through.  He did not drill.
My question is: short of drilling, how do locals decide the ice on their lakes is safe for winter sports?  I don't remember the criteria my father used, except on the larger lake the ice had to extend very close to the spill-way, which was in essence an artificial outlet stream.  (We stayed away from that area.)  If it was safe on the larger lake, it would be safe on the smaller lake.
Where I live (Northern VA), the only safe assumption is that the ice is never safe.
Clarification:  If you think drilling is the only way to declare ice safe, in your area for your lakes, that would be a valid answer.  But I am still more interested in how people can make the judgement without drilling.

A:

My question is: short of drilling, how do locals decide the ice on their lakes is safe for winter sports?

What people in North America do (for testing if you can walk on the ice) is:

Check that the edge is thick enough to hold your weight, if you can't get on the edge you won't get to the middle (without getting soaked, which is the #2 thing to avoid).
Slowly walk a little further, if you can feel flexing or hear cracking slowly turn around.
Venture out further and look to see if the ice appears consistent, if it doesn't seem fairly thick and free of cracking and flexing then wait another day or two while temperatures remain a few degrees below freezing. If it gets warmer it's best to forget about going out on the ice.
You can find a shallow depressed area and fill it with water, that way if the ice is uncertain you won't fall in past ankle depth. Such an area is much safer for playing sports with many active people than the risk of letting your children play on a frozen lake.

An additional test that I utilized, since I didn't enjoy getting a soaker in freezing cold water, is to lob a large rock onto the ice. You can tell from the bonk (and above listed checks) that the ice looks and sounds correct.
On the Internet these seemingly reliable sites offer this advice (not involving drilling):

Outdoor Canada Magazine: "How to know when the ice is safe for fishing":

"Freeze Factors
... the first question you should ask yourself at the beginning or the end of the season is this: Has it been cold enough outside for a long enough period of time to create or maintain safe ice? If the answer’s no, it’s not time to go ice fishing.
When you do visit a frozen waterbody, conduct a visual inspection before heading out. Look for cracks on the surface, which can be a sign of instability. ...
Colour code
It’s also very important to consider the colour of the ice. Clear blue ice is the strongest and safest. It forms when the temperature has been at least -8ºC for three consecutive weeks. The colder it gets, the faster blue ice will form. At a minimum thickness of 12 inches, blue ice will even support a large vehicle such as a mid-size pick-up (see “Support system”).
White opaque ice is half as strong as blue ice. It’s formed by wet snow freezing on top of already existing ice. Often referred to as snow ice, it’s most dangerous when it forms on top of ice that hasn’t completely frozen. When that happens, the ice below takes longer to freeze and turn into blue ice. During early-winter and spring snowstorms, opaque ice is notorious for covering up dangerous thin ice, catching ice anglers off guard. Use extreme caution when heading onto snow-covered ice, and check the thickness every 100 metres with your ice auger.
Dull grey ice is the least safe. Why? Because it’s rotting. The grey colouration indicates the presence of water, meaning the ice will not support much weight, if any. Grey ice is most common during the spring melt, although it can be found all winter long near moving water, such as where creeks and rivers enter or leave a waterbody. These same areas also often have underwater currents that can make ice unstable, so avoid them. And remember, no fish is worth the risk of falling through.".

WikiHow: "How to Know When Ice is Safe" (read complete article for details):

Recognize that ice will never be completely safe.
Create an emergency safety plan.
Recognize that determining the safety of ice is dependent on a combination of factors, not on one factor alone.

Ice safety is determined by assessing the following factors together:

Appearance of the ice - its color, texture and features
Thickness of the ice - there are recommended thicknesses for different uses, which are set out below
External temperature over a period of time and on the day
Snow coverage
Depth of water under ice
Size of water body
Chemical composition of water - whether water is fresh or salt
Local climate fluctuations
Extent of ice

Prefer ice that is checked by designated authorities on a regular basis.
Ask the locals.
Observe the ice. Look at the ice to see if you can see any cracks, breaks, weak spots or abnormal surfaces and to identify the color(s) of the ice. You cannot rely on your eyesight alone. This is just an initial look to help you to decide if it is even worth proceeding to the next step of testing the ice.

If you see any of these signs, you may wish to abandon any further attempt to go on the ice:

Flowing water near or at the edges of the ice
Flowing springs under the ice in spring fed ponds and lakes
Water flows in and/or out of the iced-over water body
Cracks, breaks or holes
Ice that appears to have thawed and refrozen
Abnormal surfaces that you have not seen before - e.g., pressure ridges caused by currents or winds

Remember this ditty: "Thick and blue, tried and true; Thin and crispy, way too risky."

Know your ice color meanings. Although a useful indicator, color alone should not be relied upon. For instance, ice of any color subjected to a running water force underneath will be weaker than ice not subject to that pressure. In general, you can surmise the following from ice colors:

Light gray to dark black - Melting ice, occurs even if air temperature is below 32°F (0°C). Not safe, its weak density can’t hold a load, stay off.
White to Opaque - Water-saturated snow freezes on top of ice forming another thin ice layer. Most times it’s weak due to being porous from air pockets.
Blue to Clear - High density, very strong, safest ice to be on if thick enough, stay off if less than 4 inches (10 cm) thick.
Mottled and slushy or "rotten" ice - not so much its color but its texture. This ice is thawing and slushy. It is deceptive - it may seem thick at the top but it is rotting away at the center and base. Most prevalent in spring, may be showing signs of browns from plant tannins, dirt and other natural materials that are resurfacing from thawing. Not suitable for even a footstep.

Test the thickness of the ice. If you have already made your observations and you still feel confident, you will need to back this up by checking the thickness of the ice.

Test with at least one other person (the buddy system). Wear a flotation suit or device and use ropes that your buddy can pull on if something goes wrong.
Only go on the ice if the edge of the water body is firm. If it is slushy or cracking, it is unlikely to be safe to proceed as shoreline ice is the weakest.
Etc. ...

Understand that ice strength is not the same everywhere, not even on the same body of water.
Find alternatives if in any doubt. Skaters can always find a rink or a supervised lake area; snowmobilers and skiers can always stick to trails on land in place of crossing ice; walkers can keep off the ice and continue with their snowshoes along the trail. All out-goers should carry emergency supplies no matter how long they plan to be out nor where they plan to go.

Those are lengthy articles that are grossly abbreviated for this answer.

Canadian Red Cross: "Ice Safety"
Boy Scouts of America: "Ice Safety"
My answer on Physics.SE to "When can water be supercooled" which contains charts regarding pressure and freezing temperature along with a link, huge chart of ice types, leading to a website containing more information about ice and water than the average person would want to know.

Proper drilling would involve drilling and measuring at sufficiently frequent intervals to chart the thickness safely, due to the uncertainty of ice it would provide a time consuming guess.
A great method not involving drilling is explained in this article: "Non-contact ice thickness indicator ‘PicoR ICE’ powered by XeThru radar tech". The PicoR Ice Device is one of many such devices for rapidly measuring ice fields.

I suspect that most people, your father included, simply guess that the ice is safe; with varying results.
See also Psychology.SE:

What research is there on how people go from examining/gathering evidence to executing on a decision?
Why do some people refuse to wear their seat belt while being aware of the risks?
Why do children sometimes not do what they are told, even though their environment supports them fully to do so?
Why do people feel the need to make changes to a solution presented by another person?
Is Decision-Making Emotionally Based, with Rationalization as the only Conscious Component?
Why do some people seem to disregard the choice of doing nothing (The Zero Choice)?

The last link explains that paying to go to a skating rink is cheaper than losing your life, but people think waiting until they decide it is safe to skate (or drive a vehicle) on a frozen lake is the lowest cost alternative.

A:

In sweden, where skate touring is a popular winter sport, skaters bring a device called "ispik". (Ice pike). They come in two varieties. Either double pike, that looks like a sturdier version of a ski pole or a single pike that looks more like a broomstick with a tapered metal point. Generally speaking a single pike is easier to use but a double pike can also be used in the same manner as a cross country skier uses poles, which is useful if the ice surface is uneven and hard to skate.
Skaters judge the thickness and quality of the ice by one or more stabs with the pike. With a bit of practice it is quite easy to tell safe ice from questionable ice. Experienced skaters can also tell "thin but it will hold" from "time to turn around".
While skating, the sound is also a useful clue. As the ice gets thinner, the pitch will rise.

A:

You need between 3 and 4" of clear ice to be safe, but, with practice, you can visually determine if there is this amount or more.  The key is that ice can support your weight in boots and not yet be safe for dynamic or concentrated loads (i.e. jumping or ice skating).
The basic technique is that you first bash the edge of the ice (it is always thinnest at the edge), and look at the thickness underwater.  If your bashing put a lot of cracks in the ice or the ice moved on the water, it isn't safe enough to step on.
Then you step on the ice -- if it cracks and seems springy, you jump off.
Then you jump up and down -- if  that's ok, you go out a few feet and look at the ice at slanted angle.
Because clear ice refracts light differently depending on its thickness, with a little bit of practice, you can see if the ice is 4"+ thick.  In general, if it is 2" or less, a well-driven ski pole will go through it, and if you jump, it it will crack and water will come up through the cracks.
Overall, this is something of an experience-based process.


Q:

Using pagination with CursorLoader and MergeCursor closes old cursors

As the title says, when trying to paginate a ListView backed by a SimpleCursorAdapter and a CursorLoader, old cursors are getting closed, thus the below exception is being thrown. The first 2 pages load just fine (the first isn't using the MergeCursor and the second page is the first one to use the MergeCursor). I don't call any close() on any cursor whatsoever.
What is interesting is that while debugging, I cannot see the closed flags on any cursor being set as true, for what it's worth. Might be an issue with the MergeCursor then. Let me know if you guys have any solutions, I'm out of ideas.
Stack Trace:
android.database.StaleDataException: Attempting to access a closed CursorWindow.Most probable cause: cursor is deactivated prior to calling this method.
    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:139)
    at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)

Code:
private List<Cursor> mCursorsList = new ArrayList<>();

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
                     int visibleItemCount, int totalItemCount)
{
    if (!isLoading && !isAllLoaded &&
            firstVisibleItem != 0 &&
            firstVisibleItem == totalItemCount - visibleItemCount)
        getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data)
{
        Cursor oldCursor = mCursorAdapter.getCursor();
        mCursorsList.add(data);
        if (oldCursor != null)
        {
            Cursor[] cursorArray = mCursorsList.toArray(new Cursor[mCursorsList.size()]);
            MergeCursor newCursor = new MergeCursor(cursorArray);
            mCursorAdapter.swapCursor(newCursor);
        }
        else // first cursor
        {
            mCursorAdapter.swapCursor(data);
        }
}

@Override
public void onLoaderReset(Loader<Cursor> loader)
{
}

A:

The main cause of this issue is that the CursorLoader manages the inner cursor, so whenever it needs to open a new one (such as a new page query), it closes the old cursor.
For a more simple pagination implementation, don't query with offsets, just bump the limit on every page, so that the new cursor contains all previous pages as well. Also, as Ian Lake suggested on Google+, sometimes you don't even need pagination, especially if you are doing complicated joins or sorting the data.


Q:

App Store Distribution Provisioning Profile vs Development Provisioning Profile

I've got two provisioning profiles: App Store Distribution Provisioning Profile and Development Provisioning Profile. The question is rather easy but I need a clarification. I guess that the code signed with the App Store Distribution Provisioning Profile won't run on the devices I normally use for development. Am I right? And is there any possibility to run this code on my devices?
P.S. I know there are similar questions. However, no one has asked whether it is possible to run code signed with the App Store Distribution Provisioning Profile on the devices normally used for development.
The reason why I am asking is that I am integrating Push Notifications with Parse.com (which is in beta) and I'd like to test if their service works well in the production environment.
The Answer (thanks to Kheldar):
App Store provisioning profiles do not allow for a distribution built application to be installed on an Apple device. To install your distribution ready application on a device, you must create an Ad Hoc provisioning profile.
It can be also checked in the Organizer:

A:

The development profile serves for developing and testing on your devices.
The distribution profile serves for making your IPA file, sign it and send it to Apple.
It is clearly marked that you cannot run it on devices, unless you have an Ad Hoc distribution profile:
App Store provisioning profiles do not allow for a distribution built application to be installed on an Apple device. To install your distribution ready application on a device, you must create an Ad Hoc provisioning profile.

A:

Back in 2014 when this question was asked, and perhaps a bit later, it was perfectly possible to install an application signed with an AppStore profile on device, provided that the matching AdHoc profile was already installed. This subsequently changed, and it is no longer possible (2019) to install an app signed with an AppStore profile except via download from Apple (e.g. via TestFlight).


Q:

Discordant vs controversial vs non-concurring

Do these three words mean the same thing?
From my understanding, discordant means not agreeing or out of tune. This is similar to non-concurring (as concurring would mean agreeing on something). Also, controversial means something which gives rise to disagreement.
How do I understand the subtle difference in meaning when the wors are so similar?

A:

Controversial is the adjective form of controversy. And controversy is defined as "disagreement, typically when prolonged, public, and heated." Therefore something that is controversial is "of, producing, or marked by controversy." It has aspects of dividing public opinion over a period of time, often heatedly so.
Discordant means "not being in accord; conflicting." And one definition of accord is "a settlement or compromise of conflicting opinions." So discordant has more of the connotation of being disharmonious, being contrary, clashing with others on purpose.
Nonconcur is defined as "to refuse or fail to concur." And concur is defined as "be of the same opinion, agree; agree with a decision, opinion, or finding." So nonconcurring can be a quiet, nonpublic disagreement with something. It doesn't have to be one side or the other, it could be that there are several nonconcurring opinions. This is the word used sometimes when a Supreme Court justice has a dissenting opinion. One of Merriam-Webster's sample sentences is: The one nonconcurring judge in the case issued his own opinion.
You are correct that the meanings are similar, and it will depend on the context in which the word is used but, based on their definitions, I think controversial has a public and prolonged element to it, discordant has an intentional element to it, and nonconcurring has a thoughtful, respectful connotation.


Q:

Adding Gradle plugin tasks to build invocation

Here is my build.gradle:
plugins {
    id 'net.saliman.cobertura' version '2.3.1'
}

apply plugin: 'groovy'
apply plugin: 'idea'

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile(
        'org.codehaus.groovy:groovy-all:2.4.6'
    )

    testCompile(
        'org.spockframework:spock-core:1.0-groovy-2.4'
    )
}

cobertura {
    coverageCheckTotalLineRate = 95

    coverageCheckHaltOnFailure = true
}

As you can see I have set up the Gradle Cobertura plugin. Typically build my application via:
./gradlew build

But to run Cobertura, I have to run a totally different invocation:
./gradlew cobertura coberturaCheck

I want to condense these so that running ./gradlew build also runs these 2 Cobertura tasks.
How can I reconfigure my build so that ./gradlew build also runs ./gradlew cobertura coberturaCheck after all tests have finished running?

A:

I've had a quick look at the sources of the Cobertura plugin.
The dependencies that the tests must run befor Cobertura and so on are all correctly set up by the plugin, so the right order should be taken as granted.
Actually it is the case that all tasks of type Test are set up in such a way that the Cobertura Report generation is always run after them as well as the coverage checking. Those tasks are simply disabled by default.
Adding coberturaCheck to the task graph to be executed enables all cobertura tasks including the coverage check task.
Adding cobertura to the task graph enables all cobertura tasks except of the coverage check task. So if you already added coberturaCheck to the task graph, adding cobertura has the only effect that it depends on all tasks of type Test.
As in your project the only task of type Test is the task called test which is already depended on from check which is depended on from build, it is enough to depend on coberturaCheck to enable the cobertura tasks, so just do build.dependsOn coberturaCheck in your build file, or if you like it more check.dependsOn coberturaCheck.
If you nevertheless want to depend on cobertura also, because you might fear that tasks of type Test are added in the future that are not depended on by task check, you can of course also do that. This would look like build.dependsOn tasks.cobertura, coberturaCheck or check.dependsOn tasks.cobertura, coberturaCheck.
The extra tasks. for cobertura is necessary, because there is also a project extensions called cobertura which would be taken before looking for a task called cobertura so you must explicitly state that you want the task here.


Q:

Multiple web applications into one portal

I am not pretty sure if this the right place for this question, if it is not i will tank you to redirect me.
Ok, well i am a web developer (Java, jsp, jpa, etc) now i finish a project for a company wich is web based, and i will start another one in a few days, but i don want to tu have multiple access paths like this "http://app1" "http://app2", instead it would be nice to have just one entry point like this "http://companypage" and then once inside a menu with the different options according the user profile, like this app1 app2, so the user do not have to enter his username and password for every application.
Right now i am reading about LifeRay wich seems to be what i need, but it requires to change my application in order to develop it as a portlet and i am not sure about changing so much.
Hope you can help me.

A:

Have you looked into CAS? This would provide the entry point for authentication. Each application would still need to have a common menu bar with all the applications a user has access to.


Q:

Historical esgrimas de navaja technical manuals

The Navaja is a Spanish knife, which started as a tool (like most knives) and ended up being used for fighting. During Napoleonic times, it was banned by the French, to quote wikipedia:

The navaja de muelles proved sufficiently formidable as an offensive arm that it was specifically named by the Marqués de la Mina, the Spanish military governor of Catalonia, in his edict of 29 May 1750 prohibiting the carrying of armas blancas, or edged weapons.[10]
Despite official disapproval, the navaja de muelles became popular throughout Spain as a fighting and general utility knife, and was the primary personal arm of the Spanish guerrilleros who opposed Napoleon during his invasion and subsequent occupation of Spain in the Peninsular War of 1808–1814.

I found this video showing how it is used now or Curro Jiménez - Duelo de Navajas.
However, I am interested in technical manuals that would have existed in Napoleonic times1. Either from primary sources (since my Spanish is very limited, translated text or pictures would be better) or form a current practitioner with knowledge of such.

1: Why only Napoleonic times? I am writing a character for an pen & paper RPG set in that time period. This is research so I can accurately portrait their fighting techniques.

A:

If 1849 is recent enough, there's the Manual del Baratero. I've only found a partial translation available for free, but there are a few ones for sale such as this one.

Excerpt from the free online translation:

The instruction for wielding the navaja is divided into four parts.  The first part contains lessons on the characteristics of the weapon and its different techniques.  In the second the guards are analyzed, the manner of attacking the enemy is explained, to give a small idea of the various ways in which it is performed, and the tretas are discussed.  In the third is the method of wielding the cuchillo.  Finaly, in the fourth are lessons on the method of wielding the tijeras as in practice among the jitanos.  The first part is divided into eleven lessons, the second into 12, the third in six, and the fourth in two, in the following manner.

....

THE POSITIONS OR STANCES

Those skilled in wielding the navaja take their first position or stance, in a similar manner to that of the espada and sable, which is called guardia. After taking the navaja in either of the hands place the thumb upon the first third of the blade, whose edge should lie towards the inside, place yourself in guardia at a reasonable distance from your opponent, better far than near, with the unoccupied hand held against the body at the waist and in front of the abdomen, and in such a disposition so as to be ready to recieve the navaja when you wish to make a cambio; the feet and legs are placed at equal distance from the oponent, a little open, and in such a manner that all the body faces front and none to the side, as is seen in the present figure: but not when a hat, cap, jacket or mantle is used in either of the hands, in which case you should arrange yourself with the leg on the same side as the arm in which is the hat or cap, towards the front and in the manner of the figure found in lesson eight, the Cambios.
Upon coming on guard take care to draw in the abdomen all that is possible, for which effect it will be neccesary to stoop a little, or else the face will be exposed too far forward, will recieve a blow, and be disgraced. The eyes are always fixed on those of the enemy; in an unwavering manner, even if provoked with feints, words or gestures; it is neccesary to point out that good wielding of the navaja lies essentialy in the swiftness of the eyes and feet, as we now move on.

From the introduction by Maestro Ramon Martinez, director of Martinez Academy of Arms, President of the association for historical fencing and founding member of the International Masters at Arms Federation:

After my meeting with Maestro Loriega, I read the Manual again more carefully and come to realise that here was a manual of the Destreza for the common man. Though extremely brief and superficially written, Manual del Baratero is nonetheless the first book on the art of Spanish knife fighting ever published and the only known historical text on the subject. Even though Mariano de Rementeria y Fica may not have had in-depth knowledge of the methods of the navaja, he nonetheless provided for posterity a window to the methods of knife fighting practices in 19th century Spain by the working class, the barateros, and, in particular, the Gypsies.

Sardathrion, having read the book, confirms that this is a good description of the manual although the translator notes make the technical aspect much clearer. Some of the original drawings were published in 1836 and the manual was first published in 1849, so about 35 years after The Peninsular War (1807–1814). Sardathrion seriously doubt that much had changed in that time frame. Most of the technology and weaponry were the same. In any case, they are not striving for 100% historical accuracy, just enough to be thematically appropriate. The manual is perfect for Sardathrion's needs.


Q:

How does CXF translate WSDL's localhost to actual server URL?

All WSDLs I have seen so far, use localhost to describe the services address. e.g.:
<wsdl:service name="SQLService">
  <wsdl:port name="SQLServiceSoap" binding="tns:SQLServiceSoap">
     <soap:address location="http://localhost:8080/rservice/services/SQLServiceSoap" />
  </wsdl:port>
</wsdl:service>

But when the client of such service is run, it somehow knows where the real URL of that service, even if run on a remote machine!
How does CXF perform this "magic"?
IOW, how does the client JAR on a test machine which is not the machine on which the service runs, know where that server is and its address?
I grep-ed the source code and strings-ed the client's jar file and found no trace whatsoever to the server's URL.
So how does that work?
UPDATE: In my super natural detective efforts, I just found a file named config.xml in the directory where the client's JAR file is located. That config.xml contains the actual server's URL. So it appears that this is how this is done in the particular case of the project I inherited.
Now the question(s) is:

Is this the standard way of doing this?
Is there a standard (or recommended way) at all in CXF?
Or is it pretty much left to the developer to decide?

A:

In many cases, the web service will have a production URL and a test/QA/UAT URL.  The developer will develop against the test URL, and then once it's ready for production he will switch the URL to point to production.
It is up to the developer to decide how this is accomplished and there is no standard way of handling it.


Q:

LibGDX - How many references counted in AssetManager of my case?

I created an AssetManger Class called AssetsTest.
    package com.program.mydemo;

    import com.badlogic.gdx.assets.AssetManager;
    import com.badlogic.gdx.graphics.Texture;
    import com.badlogic.gdx.graphics.g2d.TextureAtlas;

    public class AssetsTest {

        public static AssetManager manager = new AssetManager();

        public static void load() {
            manager.load("bgscreen.png", Texture.class);
            manager.load("menu.pack", TextureAtlas.class);
        }

        public static void unload() {
            manager.unload("bgscreen.png");
            manager.unload("menu.pack");
        }

        public static boolean update(){
            return manager.update();
        }

        public static void dispose() {
            manager.dispose();
        }

    }

I also created another Class called MyDemo
public class MyDemo extends Game {

    private SpriteBatch batch;
    private Sprite spriteStart1, spriteStart2;
    private Texture texture1, texture2;
    private TextureAtlas atlas1, atlas2;
    private TextureRegion startRegion1, startRegion2;
    private Camera camera;
    private int refCount;

    public void create () {

        batch=new SpriteBatch();
        camera = new OrthographicCamera(500,700);

        AssetsTest.load();
        AssetsTest.manager.finishLoading();

        texture1 = AssetsTest.manager.get("bgscreen.png",Texture.class);
        atlas1 = AssetsTest.manager.get("menu.pack", TextureAtlas.class);
        startRegion1 = atlas1.findRegion("startbutton");
        spriteStart1 = new Sprite(startRegion1);
        spriteStart1.setPosition(-210/2,-150);

        texture2 = AssetsTest.manager.get("bgscreen.png",Texture.class);
        atlas2 = AssetsTest.manager.get("menu.pack", TextureAtlas.class);
        startRegion2 = atlas2.findRegion("startbutton");
        spriteStart2 = new Sprite(startRegion2);
        spriteStart2.setPosition(-210/2,-150);

        refCount = AssetsTest.manager.getReferenceCount("bgscreen.png");
        System.out.println(refCount);

//      AssetsTest.unload();

//      AssetsTest.load();
//      AssetsTest.manager.finishLoading();

    public void render () {
        Gdx.gl.glClearColor(0,0,0,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.draw(texture2, -500/2,-700/2);
        spriteStart2.draw(batch);
        batch.end();
    }

    @Override
    public void dispose () {
        super.dispose();
        batch.dispose();
        texture1.dispose();
        AssetsTest.dispose();
    }
}

Then, I created two Texture References (texture1 & texture2) reference to AssetsTest.manager.get(...);
The refCount is 1. Why?
It should be "2" because I have two references (texture1 & texture2).
If I try to call AssetsTest.load(); twice, I will get refCount is 2. Calling twice of AssetsTest.load(); should create two objects and stored in different  memory address. Is my concept correct?

A:

Directly from the libgdx documentation:
Assets are reference counted. If two assets A and B both depend on another
asset C, C won't be disposed until A and B have been disposed.

This also means that if you load an asset multiple times, it will actually be shared and only
    take up memory once!
you load
texture1 = AssetsTest.manager.get("bgscreen.png",Texture.class);

and then
texture2 = AssetsTest.manager.get("bgscreen.png",Texture.class);

both texture1 and texture2 point to the same texture which is shared and takes memory only once. That's why you get ref count 1.
Update
Yes, texture1 and texture2 point to the same object ("bgscreen") which is shared. So in a sense they are reference variables pointing to the same memory address. Once an item is loaded in the asset manager it could be reused/shared in this way. In your case this means that no new object will be created each time you reference "bgscreen.png". So you will always get ref count 1.
As regards to the the 2nd part of your question. To clarify some things: Assetmanager.load in its way doesn't load any assets. The method just enqueues the assets. Once you call manager.update() or manager.isFinished only then the assets which you've enqueued with the load method will be loaded into memory. So if you call load twice of the same texture then when you call manager.update() you will end up with two references of the same object ("bgscreen.png") which is unnecessary because what you usually want is have only one shared reference of the same object for efficiency.
If this answers your question please don't forget to accept the response.


Q:

PHP PayPal API and Sandbox Issue

Stupid question maybe..
How do I know if my integration with the PayPal API works fine?
I mean the code goes to PayPal fine, the Payment on PayPal seems to work fine and then the user is redirected in the right page on my site after the payment.
So I am assuming it works OK.
But no Price is shown on the PayPal form.
No charges for my test account
No incomings on my other test account (seller)
I am assuming it works only because the user is redirected to the success page on my site!
But how do I know that it is really working?!
Nothing makes me totally sure it works!!
Please advise..
I am using the Express Checkout API
I am justing charging a customer for a single item, no PayPal authorizations etc.. just a simple PayPal sale.
Thank you
<?php

require_once ("paypalfunctions.php");
// ==================================
// PayPal Express Checkout Module
// ==================================

//'------------------------------------
//' The paymentAmount is the total value of
//' the shopping cart, that was set
//' earlier in a session variable
//' by the shopping cart page
//'------------------------------------
$creditsAmount = $_GET["creditsAmount"];
if ($creditsAmount <= 4) {
$price = 10;
}elseif($creditsAmount <= 19 && $creditsAmount >= 5) {
$price = 7.5;
}else{
$price = 5;
}
$paymentAmount = $price * $creditsAmount;
$SubmID = $_GET["SubmID"];
$memberID = (int)$_COOKIE["memberID"];
//'------------------------------------
//' The currencyCodeType and paymentType
//' are set to the selections made on the Integration Assistant
//'------------------------------------
$currencyCodeType = "USD";
$paymentType = "Sale";

//'------------------------------------
//' The returnURL is the location where buyers return to when a
//' payment has been succesfully authorized.
//'
//' This is set to the value entered on the Integration Assistant
//'------------------------------------
$returnURL = "http://domain.co.uk/modules/yobilab/copyright/PAYPAL_process.php?creditsAmount=".$creditsAmount; // AGGIUNGERE ID SUBMISSION
//$returnURL = "http://domain.co.uk/modules/yobilab/copyright/PAYPAL_process.php"; // AGGIUNGERE ID SUBMISSION
//'------------------------------------
//' The cancelURL is the location buyers are sent to when they hit the
//' cancel button during authorization of payment during the PayPal flow
//'
//' This is set to the value entered on the Integration Assistant
//'------------------------------------
$cancelURL = "http://domain.co.uk/m/copyright/overview/".$SubmID; // AGGIUNGERE ID SUBMISSION
//$cancelURL = "http://domain.co.uk/m/copyright/error/"; // AGGIUNGERE ID SUBMISSION

//'------------------------------------
//' Calls the SetExpressCheckout API call
//'
//' The CallShortcutExpressCheckout function is defined in the file PayPalFunctions.php,
//' it is included at the top of this file.
//'-------------------------------------------------
$resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL);
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
{
    RedirectToPayPal ( $resArray["TOKEN"] );
}
else
{
    //Display a user friendly Error on the page using any of the following error information returned by PayPal
    $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
    $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
    $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
    $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);

    echo "SetExpressCheckout API call failed. ";
    echo "Detailed Error Message: " . $ErrorLongMsg;
    echo "Short Error Message: " . $ErrorShortMsg;
    echo "Error Code: " . $ErrorCode;
    echo "Error Severity Code: " . $ErrorSeverityCode;
}
?>

A:

Use Paypal IPN (instant payment notification) send that url via your html from and then on that page put this code you will get response in email
<?php
error_reporting(E_ALL ^ E_NOTICE);
$email = $_GET['ipn_email'];
$header = "";
$emailtext = "";
// Read the post from PayPal and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc'))
{
    $get_magic_quotes_exits = true;
}
foreach ($_POST as $key => $value)
// Handle escape characters, which depends on setting of magic quotes
{
    if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1){
        $value = urlencode(stripslashes($value));
    } else {
        $value = urlencode($value);
    }
    $req .= "&$key=$value";
}
// Post back to PayPal to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

// Process validation from PayPal
// TODO: This sample does not test the HTTP response code. All
// HTTP response codes must be handles or you should use an HTTP
// library, such as cUrl

if (!$fp) { // HTTP ERROR
} else {
// NO HTTP ERROR
fputs ($fp, $header . $req);
while (!feof($fp)) {
    $res = fgets ($fp, 1024);
    if (strcmp ($res, "VERIFIED") == 0) {
        // TODO:
        // Check the payment_status is Completed
        // Check that txn_id has not been previously processed
        // Check that receiver_email is your Primary PayPal email
        // Check that payment_amount/payment_currency are correct
        // Process payment
        // If 'VERIFIED', send an email of IPN variables and values to the
        // specified email address
        foreach ($_POST as $key => $value){
        $emailtext .= $key . " = " .$value ."\n\n";
        }
        mail($email, "Live-VERIFIED IPN", $emailtext . "\n\n" . $req);
    } else if (strcmp ($res, "INVALID") == 0) {
        // If 'INVALID', send an email. TODO: Log for manual investigation.
        foreach ($_POST as $key => $value){
        $emailtext .= $key . " = " .$value ."\n\n";
        }
        mail($email, "Live-INVALID IPN", $emailtext . "\n\n" . $req);
    }
}
fclose ($fp);
?>


Q:

Solving equations of the form $\operatorname{trig function}(x) = \mathrm{constant}$

Is there a way to solve for x where $$\operatorname{trig function}(x) = \mathrm{constant}$$
and where the domain is such that the function has an inverse.
For example,
$$\begin{align*}\sin x &= \sqrt3 / 2,\\ \cos x &= -1,\\ \tan x &= 1/\sqrt3\end{align*}$$

A:

All of the examples that you give (now that we have changed the first constant to $\sqrt{3}/2$ ) are values on the unit circle.
When you first learn about this, you'll be asked which angles satisfy the equation:
TrigFunction(angle) = constant, where the trig functions are:
sin, cos, tan, csc, sec, cot, and the constants are quotients involving:
$\pm \{0, \frac{1}{2}, \frac{\sqrt{2}}{2},  \frac{\sqrt{3}}{2}, 1 \} $


Q:

Passing temporaries as LValues

I'd like to use the following idiom, that I think is non-standard. I have functions which return vectors taking advantage of Return Value Optimization:
vector<T> some_func()
{
    ...
    return vector<T>( /* something */ );
}

Then, I would like to use
vector<T>& some_reference;
std::swap(some_reference, some_func());

but some_func doesn't return a LValue. The above code makes sense, and I found this idiom very useful. However, it is non-standard. VC8 only emits a warning at the highest warning level, but I suspect other compilers may reject it.
My question is: Is there some way to achieve the very same thing I want to do (ie. construct a vector, assign to another, and destroy the old one) which is compliant (and does not use the assignment operator, see below) ?
For classes I write, I usually implement assignment as
class T
{
    T(T const&);
    void swap(T&);
    T& operator=(T x) { this->swap(x); return *this; }
};

which takes advantage of copy elision, and solves my problem. For standard types however, I really would like to use swap since I don't want an useless copy of the temporary.
And since I must use VC8 and produce standard C++, I don't want to hear about C++0x and its rvalue references.
EDIT: Finally, I came up with
typedef <typename T>
void assign(T &x, T y)
{
    std::swap(x, y);
}

when I use lvalues, since the compiler is free to optimize the call to the copy constructor if y is temporary, and go with std::swap when I have lvalues. All the classes I use are "required" to implement a non-stupid version of std::swap.

A:

Since std::vector is a class type and member functions can be called on rvalues:
some_func().swap(some_reference);


Q:

IntelliJ: Ubuntu/linux how to open file with IntelliJ from shell

Following this question, it seems that it is possible to open a file from the shell with IntelliJ on MAC.
IntelliJ: how to open files in an existing IntelliJ from the command line
Is there anything something similar for Ubuntu?

A:

You can associate the files with IDEA_DIR/bin/idea.sh file. Or even better, use Tools | Create Command-line Launcher...
Then you can open files in IDEA using the following command:
idea FileName.java


Q:

Augmented triads in classical music

I would like to know of examples of augmented chords of type 5# (I do not refer to 6th) in classical music, I know the theory for the formation of this type of chords (C aug or C+ or C(5#)-> C, 3ª major interval -> E and 5ª augmented interval -> G#), I have learned many examples in popular music and jazz but I would like to know in as much detail as possible examples in classical music.

A:

Before I start, note that oftentimes these "augmented triads" in classical music are not bonafide augmented triads but actually just dominants with a brief chromatic passing tone. But not always!
Now, there's really no better one-stop shop than this terrific minuet by Mozart (K 355). Here's a score, and below is a sample of the opening measures; check out the augmented triads in mm. 1, 5, 7, and 9. (Whether they truly "are" and function as augmented triads is a much longer discussion; but they do momentarily create augmented harmonies.)

And since I've got Wagner on the brain, here are some other ideas.
I've linked the music; I'll leave it up to you to find the scores:

Wagner, Siegfried, Act I Scene 3 (beginning in m. 2430), at the famous "Nothung!" calls. The calls themselves are above an F augmented triad, and there's a brief intro that could be understood as a D augmented triad.
Wagner, Siegfried, Act III Scene 2 (m. 440), as Siegfried confronts The Wanderer. The opening progression, in A flat, alternates between I and V+.
Similarly, check out Beethoven's Op. 119 No. 1 Bagatelle in G minor. In m. 17, a V chord in A flat has a chromatic passing tone B-natural that briefly creates a V+.

A:

You will find plenty of augmented chords in the music of Edvard Grieg.  For instance, Measures 11 and 13 of "To Spring", Op. 43 no. 6.

A:

Beethoven actually uses them quite functionally in the first movement of Eroica, right in the beginning of the development. Here, the Ab augmented triad resolves into G7 with Ab moving down to G and E natural up to F. Then with the same melody he moves from C major to F minor, then again from Ab augmented to G7, where he stays for four bars before modulating to G major, using the Ab major chord as a Neapolitan.


Q:

How to touch up scratches on a black anodized aluminum flashlight?

One of my flashlights that has a black anodized aluminum housing has a couple of scratches on it, all of the way through the anodized coating.
How can I cover up the scratches so that its completely black again?

A:

How to touch up scratches on a black anodized aluminum flashlight?
Try using black nail polish on your flashlight . But make sure it is a good quality nail polish and not something from the Dollar Store. People have used nail polish to remove scratches on cars for many years now.

Some people may only know nail polish as something women put on their nails as a form of an accessory. However, nail polish has a lot of uses, and one of these uses includes being a great scratch remover. As you can tell with the other DIY fixes, you will need to buff and sand. However, with nail polish, you will just need to clean the area before applying it. Nail polish helps cover up the scratches instead of doing a lot of legwork to “remove” the scratch. Furthermore, nail polish comes in a variety of colors, so it’ll be easier to match a color with your paint. This makes it a really effective way to remove scratches on your car paint. So, you should look for the closest color to your car paint that you can find. Apply the polish as evenly as possible so the scratch will no longer be seen. If you still see the scratch afterward, you can just apply another coat of nail polish after it has dried. - Nail Polish

A:

"How can I [make] it completely black?"
Cover it with something black.
Drawing on it with a black marker will work, but that might rub off after serious use. You could use black spray paint, but that requires etching into the rest of the anodized part. Black electrical tape would be great, and makes it a little more grippy when wet, but gets gross after a while.

A:

I have a small can of Bar-B-Q-Black, a Rustoleum product that we have used on scratches or dings on black metal objects, such as a wood-burning stove or a iron garden bench. This particular can says it resists heat up to 1,000 degrees F, which performance limit you are unlikely to need.
If you Google Bar-B-Q-Black, Rustoleum you will find an array of products at an array of prices at many places. It may be more expensive than nail polish (see answer of Ken Graham) but not necessarily.


Q:

arm eabi v7a system image not found android

I've to develop a simple Android app using the Cordova API(PhoneGap) and it requires Android 4.0.3 or higher versions (API Level 15 or above) to build the app on the emulator correctly.
But, when I give a build for the coded app, I happen to see that I get this below error message,
[2012-07-02 13:10:29 - SDK Manager] Unable to find a 'userdata.img' file for ABI armeabi to copy into the AVD folder.

On googling this problem, I came to know that I need to install the arm-eabi v7a system image onto my machine for this to run smoothly.
But the issue is that, unlike API 14, this is not appearing for API 15!
Below image shows the same:

Now, can anyone explain me how to fix this up, please? This is very peculiar to look at and re-installing the Manager/SDK/API Levels again and again was of no use.
Reference: Android SDK Manager is not showing ARM EABI v7a System Image option
Help is much appreciated!

A:

Ideally this should not be the case.
For e.g. one does see the ARM EABI v7a System Image (API level 15) in the SDK Manager window.
You could try a few things:

Reinstall the SDK.
Alternatively, delete the ANDROID_SDK_INSTALL_FOLDER\system-images\android-15 folder and then install the SDK again and try.


Q:

Spark 1.5 MlLib LDA - getting topic distribusions for new documents

Not a duplicate of this because I'm asking about what the input is, not what function to call, see below
I followed this guide to create an LDA model in Spark 1.5. I saw in this question that to get the topic distribution of a new document I need to use the LocalLDAModel's topicDistributions function which takes an RDD[(Long, Vector)].
Should the new document vector be a term-count vector? That is the type of vector the LDA is trained with. My code compiles and runs but I'd like to know if this is the intended use of the topicDistributions function
import org.apache.spark.rdd._
import org.apache.spark.mllib.clustering.{LDA, DistributedLDAModel, LocalLDAModel}
import org.apache.spark.mllib.linalg.{Vector, Vectors}
import scala.collection.mutable

val input = Seq("this is a document","this could be another document","these are training, not tests", "here is the final file (document)")
val corpus: RDD[Array[String]] = sc.parallelize(input.map{
  doc => doc.split("\\s")
})

val termCounts: Array[(String, Long)] = corpus.flatMap(_.map(_ -> 1L)).reduceByKey(_ + _).collect().sortBy(-_._2)

val vocabArray: Array[String] = termCounts.takeRight(termCounts.size).map(_._1)
val vocab: Map[String, Int] = vocabArray.zipWithIndex.toMap

// Convert documents into term count vectors
val documents: RDD[(Long, Vector)] =
    corpus.zipWithIndex.map { case (tokens, id) =>
        val counts = new mutable.HashMap[Int, Double]()
        tokens.foreach { term =>
            if (vocab.contains(term)) {
                val idx = vocab(term)
                counts(idx) = counts.getOrElse(idx, 0.0) + 1.0
            }
        }
        (id, Vectors.sparse(vocab.size, counts.toSeq))
    }
// Set LDA parameters
val numTopics = 10
val ldaModel: DistributedLDAModel = new LDA().setK(numTopics).setMaxIterations(20).run(documents).asInstanceOf[DistributedLDAModel]

//create test input, convert to term count, and get its topic distribution
val test_input = Seq("this is my test document")
val test_document:RDD[(Long,Vector)] = sc.parallelize(test_input.map(doc=>doc.split("\\s"))).zipWithIndex.map{ case (tokens, id) =>
    val counts = new mutable.HashMap[Int, Double]()
    tokens.foreach { term =>
    if (vocab.contains(term)) {
        val idx = vocab(term)
        counts(idx) = counts.getOrElse(idx, 0.0) + 1.0
        }
    }
    (id, Vectors.sparse(vocab.size, counts.toSeq))
}
println("test_document: "+test_document.first._2.toArray.mkString(", "))

val localLDAModel: LocalLDAModel = ldaModel.toLocal
val topicDistributions = localLDAModel.topicDistributions(documents)
println("first topic distribution:"+topicDistributions.first._2.toArray.mkString(", "))

A:

According to the Spark src, I notice the following comment regarding the documents parameter:
   * @param documents:
   * RDD of documents, which are term (word) count vectors paired with IDs.
   * The term count vectors are "bags of words" with a fixed-size vocabulary
   * (where the vocabulary size is the length of the vector).
   * This must use the same vocabulary (ordering of term counts) as in training.
   * Document IDs must be unique and >= 0.

So the answer is yes, the new document vector should be a term count vector. Further, the vector ordering should be the same as was used in training.


Q:

Unknown space between links

I have three links:
   About
   Login
   Create Account

I have some CSS styling for them:
.f_link{
height:38px;
padding-top:12px;
margin:0px;
color:gray;
}
.f_link:hover{
color:black;
text-decoration:none;
}

How this html is displayed in FF 3.6, IE 8, and some version of Google Chrome:

And this is how I would like it to be displayed in my three major browers:

I used firebug and it said there is no padding or margin between these links. What is that space there for then, and how can I get rid of it? I'm open to suggestions!

A:

Line breaks are/should be treated as a single white space in HTML. You can update your markup to this (line break before the closing tag, but no space before the next A tag)
   About
   Login
   Create Account

A:

Add float: left; to your .f_link declaration, that will remove spaces.
http://jsfiddle.net/wMwEQ/
Also, using   for spacing is baaaad, even though it's not an issue here.


Q:

Method for storing a large amount of units, with a large array of attributes

Me and a friend are currently looking at developing a game, with similarities to a certain trademarked francise. To define the units in the game, we've created an abstract class which denotes the 44 variables, and two methods that need to be instantiated with each instance of a unit. The next step in this game would be to of course, define all the units in the game. Unfortunately, I have 648 units that need to be defined, with 22 final values for each which must be examined at each individual instantiation in the game. For example, if I encounter this unit in the game, I would pass a method it's value, and it would look at some sort of defining table which give all these base, final values. The problem we've encountered with this of course, is finding a method of doing this effectively, and securely. Currently, for testing of other methods, I have a few units defined through enumeration, and have their values stored in an array. My partner has suggest we create a defining class, which will look at a plaintext lookup table. However, I see the problem with such a solution would either be the length, or quantity of lookup tables would be massive. I have searched around, but most solutions entail the use of a server. Our current goal, however is to just release an offline client with everything already defined.
Anyways, I know this was a lot of possible rambling, but... does anyone have any suggestions on how to store 648 units with 22 different final attributes effectively, so that such an entity could be called later and examined? I don't need a thorough code example, but ideas would be helpful.

A:

You probably want to create a database which contains a table of units and a set of columns (or fields) for the respective attributes. This is most abstract example I can provide.
An implementation without a server would instead entail a flat file database such as SQLite. Of course, if you want to build your own custom database as your friend suggests, it would be the same.


Q:

Applying Jquery UI theme to Asp.net buttons

I have an Asp.Net button and I am applying flick theme to my buttons and it's applying to it but on mouse hovering it doesn't change the colour.
Here is what I am doing?May be I am wrong Can anyone guide me through this as I am able to work with normal html button by using
<button>Click Me!</button>

This is how I am working with Asp.net button:
<asp:Button ID="Button1" runat="server" Text="Click Me!" CssClass="ui-button ui-state-default"/>

A:

In ASP.NET the ID get's transformed so you can't pass it as a selector. You could probably use a class instead.
So instead of
$('#Button1').button();

use
$('.MyButtonStyle').button();

EDIT:
BTW, you shouldn't be adding any jquery-ui classes to the button manually (your example looks like that's what you are doing). This is all done by the .js file included with jquery ui

A:

Anyways I found the answer and here is what I have did and worked well!
<script type="text/javascript">
$('#btnSample').button();
</script>

Code for displaying:
 <asp:Button ID="btnSample" runat="server" Text="Click Me!"/>


Q:

Increase Array Size Based on Total Numbers Entered

I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;

class setArray {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int stopInput = 000;
        int number;

        System.out.print("Enter a number: ");
        number = input.nextInt();

        while(number != stopInput) {
            System.out.print("Enter a number: ");
            number = input.nextInt();
            int array[] = {number};
        }
       System.out.print("Array size: " + array.length);
    } // Main brace
} // Class brace

setArray.java:19: error: cannot find symbol
    System.out.print("Array Size: " + array.length);
      symbol:    variable array
      location:  class setArray
    1 error

A:

You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();

while (number != stopInput) {
  System.out.print("Enter a number: ");
  values.add(Integer.valueOf(input.nextInt()));
}

Integer[] array = values.toArray(new Integer[values.size()]);


Q:

C++ Iterate an istream

What is the best way to parse or iterate an istream? I need to create a function that takes an istream, parses it and creates an object so was wondering the easiest way to do this. Even something that could convert it to string would be dandy.

A:

You can use an istream_iterator.
typedef std::istream_iterator<std::string> streamiter;
for (streamiter it = streamiter(some_istream); it != streamiter(); it++) {
    // process words
}

This will split the input stream at all whitespaces.


Q:

Redis list performance metrics

I am using redis-queue gem to implement a message queue in redis server.
Every single message undergoes the lpush and lpop command in the message queue.
I am able to get the current length of the queue which is apparently a Redis list using the llen command.
But is there any single way I can get the total number of lpush as well as lpop happened on the list during a particular time span, say in the past 24 hrs. ?

A:

It seems like you can use Redis keyspace notifications for this. Redis can be activated to publish messages when keys are changed under certain conditions and then you can subscribe to this messages using regular Redis pubsub.


Q:

How to calculate the permutation of a bit vector?

Given a bit vector V = (101101), and a permutation function: F(x) = (a*x + b) mod p. Where a and b are random numbers and p is a prime number. How can I calculate the permutation of the vector V? Does F(x) take V as an entire value or should I use each bit in V as a x for the function?

A:

Yes in order to permute the bit vector, then take each bit and apply the permutation function on it.


Q:

java.net.SocketTimeoutException: Read timed out when querying url

I get this error :
java.net.SocketTimeoutException: Read timed out
http://api.trove.nla.gov.au/result?key=<KEY HERE>&zone=all&reclevel=brief&q=%20am%20only%20yours%20fear&encoding=json
Exception in thread "main" java.lang.NullPointerException   at
trove.connect.TroveService.QueryTrove(TroveService.java:134)    at
datasetconverter.CsvReader2.main(CsvReader2.java:64) Java Result: 1
BUILD SUCCESSFUL (total time: 1 minute 41 seconds)

When I execute my code:
   public String getJSON(String url, int timeout) throws IOException, Exception {
    try {
        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 504:
            case 503:
                Thread.sleep(10000);
                this.QueryTrove(url);
                break;
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        System.out.println(ex);
        System.out.println(url);
    } catch (IOException ex) {
        System.out.println(ex);
        System.out.println(url);
    }
    return null;
}

    public int QueryTrove(String query) throws Exception{
        int sum =0;
        String json = getJSON("http://api.trove.nla.gov.au/result?key=<KEY HERE>&zone=all&reclevel=brief&q="+query+"&encoding=json",10000);

        Gson gson = new Gson();

        JsonResponse r = gson.fromJson(json, JsonResponse.class);
        for (Zone zone : r.getResponse().getZones()) {
            sum = sum + Integer.parseInt(zone.records.getTotal());
        }

        return sum;
    }

Is this because of the setConnectionTimeout and how can this be fixed ?

A:

Read timeout happens because the server took longer then the "read-timeout" parameter to respond.
But assuming you have a reasonable read-timeout value (let's say 30 seconds), it doesn't have to mean that the problem is that your read-timeout is too short, it could be that the server is stuck and would never return an answer.
To diagnose there are several things that you can do:

first try and see how long it takes to get a full response when you try to access through the browser.
try and get rid of the timeout (the default is no timeout) and see if you ever get the response.

If the server answers your browser and not your java app, then first make sure that you are calling the exact same URL. Other then that it's possible the server is ignoring you due to your USER-AGENT, try and impersonate a real browser.
Also just a friendly advice, I would pass the timeout as a parameter, just define a reasonable timeout and use it directly, unless its a very unusual use-case, no body wants to pass the timeout when using this kind of abstraction.


Q:

Return array key via array value in multiple array data

My $_SESSION stores array in the format below. All of productId value are unique. I want to get array key using a productId.
Array
(
[0] => Array
    (
        [productId] => 3
        [productQuantity] => 1
    )

[1] => Array
    (
        [productId] => 4
        [productQuantity] => 1
    )

[2] => Array
    (
        [productId] => 5
        [productQuantity] => 1
    )

)

I have tried array_search but its not working. I actually saw a similar question, but the answer was left untold. This is the code i tried but its not displaying anything:
$key = array_search(3,$_SESSION['cart']);
echo $key;

A:

Since they are unique just re-index by the productId:
$cart = array_column($_SESSION['cart'], null, 'productId');
echo $cart[3]['productQuantity'];

Or:
echo array_column($_SESSION['cart'], null, 'productId')[3]['productQuantity'];

If you'll only ever have those 2 then it makes sense to extract productQuantity and re-index by productId:
$cart = array_column($_SESSION['cart'], 'productQuantity', 'productId');
echo $cart[3];

The array will look like $cart = [3 => 1, 4 => 1, 5 => 1].
Or:
echo array_column($_SESSION['cart'], 'productQuantity', 'productId')[3];

If you really just want the current key for some reason, extract productId and search that (as long as keys are 0 based and sequential:
$key = array_search(3, array_column($_SESSION['cart'], 'productId'));


Q:

Paginate table with inner joins

I need some help, I have the following query:
SELECT
    l.*,
    d.*,
    i.*,
    DATE_FORMAT(l.date_created, '%d/%m/%Y') as date,
    UNIX_TIMESTAMP(l.date_created) as ts,
    DATE_FORMAT(d.date_deposit_made, '%d/%m/%Y') as date_deposit_made,
    l.commission_introducer
FROM
    tbl_client_commissions_log l
INNER JOIN
    tbl_client_deposits d
INNER JOIN
    tbl_initial_commissions i
ON
    l.fk_deposit_id = d.pk_deposit_id AND i.fk_client_id = d.fk_client_id

WHERE
    d.date_deposit_made BETWEEN ? AND ? AND l.system_fee = '0'

AND
    l.fk_introducer_id = ?

ORDER BY ? LIMIT ? OFFSET ?

The problem is when I put a limit of say 10 and an offset of 0 to start it off. It only returns one row.
How do you paginate with inner joins betweem 2 tables?
Thanks.

A:

I think you can simply try the LIMIT as:
  LIMIT ?, ?

where first param will be set to 0 and second will be set to 10 and you should get your results.
From MySQL Manual here:

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15


Q:

Use VBA to toggle conditional formatting on and off

How do I use VBA to toggle conditional formatting on and off?
I have a range C3:AD46. I have two conditional formats.

I want to toggle the first format on/off using a macro. The second format can stay enabled all the time.
Thanks.

A:

For the first format I was able to piece together the following:
Private Sub CheckBox1_Click()
   Dim rngMyRange As Range

   Set rngMyRange = ActiveWorkbook.Worksheets("tim-vgr_hgn").Range("C3:AO46")  'Set your range here

    If rngMyRange.FormatConditions.Count = 0 Then  'Set Conditional Formats
      With rngMyRange
            .FormatConditions.AddColorScale ColorScaleType:=3

            ' Format the first color as green
            .FormatConditions(1).ColorScaleCriteria(1).Type = xlConditionValueNumber
            .FormatConditions(1).ColorScaleCriteria(1).Value = 0
            .FormatConditions(1).ColorScaleCriteria(1).FormatColor.Color = RGB(0, 255, 0)

            ' Format the second color as yellow
            .FormatConditions(1).ColorScaleCriteria(2).Type = xlConditionValueNumber
            .FormatConditions(1).ColorScaleCriteria(2).Value = 120
            .FormatConditions(1).ColorScaleCriteria(2).FormatColor.Color = RGB(255, 255, 0)

            ' Format the third color as red
            .FormatConditions(1).ColorScaleCriteria(3).Type = xlConditionValueNumber
            .FormatConditions(1).ColorScaleCriteria(3).Value = 7200
            .FormatConditions(1).ColorScaleCriteria(3).FormatColor.Color = RGB(255, 0, 0)

      End With

    Else    'Clear Conditional Formats

      rngMyRange.FormatConditions.Delete

    End If
End Sub

But, how do I recreate the second format?
[edit]
I will start a new question for the second format.


Q:

plot values against gaussian curve

I am new to R and statistics and am still understanding the basic concepts. I need to create a graph of all values in a column of matrix against a Gaussian curve.
Below is the code
#Generates a random matrix with 50 columns
randomMatrix1 <- matrix(c(1:30000), ncol=50)

#Base sequence
x  <- seq(15001,30000, 25)

#Normal function using mean and sd of randomMatrix1
y1 <- dnorm(x/1000,mean=mean(randomMatrix1[,50]),sd=sd(randomMatrix1[,50]))

#Getting the actual values in randomMatrix1
y2 <- cbind(randomMatrix1[,50]/1000)

df <- data.frame(x,y1,y2)

require(ggplot2)

ggplot(df, aes(x)) +                    # basic graphical object
geom_line(aes(y=y1), colour="red") +  # first layer
geom_line(aes(y=y2), colour="green")  # second layer

I need the output of the two plots on same plot, however the output is not scaled and I tried some combination of varying the mean and sd but nothing worked.
I know this must be a very basic question but which parameter should I change so the two plots get scaled and display right next to each other.

A:

I am not sure if I understood the question right, but does this help?
library(reshape2)
ggplot(melt(df, id="x"), aes(x=x, y=value)) +
  geom_line() +
  facet_wrap(~ variable, scale="free_y")


Q:

MessageBodyProviderNotFoundException while running jar from command line

I am using the Java Jersey framework(with Maven), and use IntelliJ as my IDE. I have encountered this runtime exception that ONLY happens when I try to run the code from the command line (using maven to compile and then java -jar ) but NOT when running within IntelliJ, which is strange.
I have some Java code that will try to make an HTTP GET on some remote URL and try to read the returned JSON into some Lombok POJO :
String targetUrl = "some valid URL";

WebTarget webTarget = client.target(targetUrl);

Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE).get();

ParseResponse parseResponse = response.readEntity(ParseResponse.class);

I am not sure why, but when it hits that last line that does the "readEntity()" method, I will get the error below:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=text/json; charset=utf-8

This is strange, because I definitely have the jersey-media-json-jackson dependency specified in my pom.xml :
<dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.23</version>
</dependency>

and this is my POJO class that I was trying to readEntity() into :
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class ParseResponse {

   @JsonProperty("id")
   private Integer id;

   ...Other params...
}

And like I mentioned before, it is strange that this only happens when I try to run on the command line like this but there is no error when running in IntelliJ:
mvn clean package
java -jar target/NameOfJar.jar

Did I miss something obvious here? I have looked at other people with similar issues like this online but haven't found a solution.
Thanks
IS

A:

If you look inside the jersey-media-json-jackson jar you should see a file
META-INF/services/org.glassfish.jersey.internal.spi.AutoDiscoverable

The contents of this file should be a single fully qualified name of a class that implements the name of the file, namely
org.glassfish.jersey.jackson.internal.JacksonAutoDiscoverable

This file is used by Jersey auto-discoverable mechanism to automatically register features without us having to explicitly register them. Briefly, how it works, is that all Jersey modules/jars that have components that should be automatically registered, should have the above named file located in the jar, with the contents being the name(s) of the auto-discoverable component. Jersey will then use the Service Loader pattern to load the classes named in the file, and register them.
The problem this causes when creating uber jars is that you can only have one copy of a file, you can't have duplicates. So what if we have multiple jars with the above file? Well only one of those files will be included in the uber jar. Which one? Who knows, but there is only one lucky winner. So for the rest of the jars, their auto-discover mechanism never kicks in. This is the case with your Jackson feature, where the auto-discoverable registers the JacksonFeature. You can try to explicitly register with your application, and you should see that it now works.
But what about other jars/modules that may have this file? It's for this reason that when creating uber jars, you should use the maven-shade-plugin. What this plugin allows you to do, is combine the contents of the files so that all the discoverables get included into that one single file. Below is an example usage
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <createDependencyReducedPom>true</createDependencyReducedPom>
        <filters>
            <filter>
                <artifact>*:*</artifact>
                <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                </excludes>
            </filter>
        </filters>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.example.YourApp</mainClass>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>

This example was actually taken from Dropwizard's Getting Started. You can check it out for further explanation. The main part of concern the ServicesResorceTransformer, which is what concatenates the services files.


Q:

Python and Skype: `skype --callto` in subprocess finishes early

Python documentation on subprocess.check_call says that it will wait for the command to complete. However, if you fire up skype and then run the code snippet provided below, you will see that the line "Finished calling" appears almost instantly (even before skype finishes dialing support). The call still takes place even though the script finishes execution. Could you please explain why?
from subprocess import check_call
check_call(['skype', '--callto', "echo123"])
print("Finished calling!")

A:

Looks like skype uses the client-server model: there is a running process skype and when one invokes skype --callto echo123, then it looks for that running process, tells it to make the call and immediately exits. The first process then takes the liberty of actually making the call.


Q:

Why the period of early morning (brahma muhurta or amrut wela) important?

Why the period of early morning (brahma muhurta or amrut wela) important for meditation? And what is that period (approx. from hhmm AM to hhmm AM)? (I know the twilight period for sandhya vandanam. But here I am talking about amrut wela).
Would like to have scriptural references, not just opinions please.

A:

Your enquiry is about Brahma Muhurta or Amrit Vela. The scriptural ref. can be found in one of the ancient text called Ashtanga Hridaya , which is an Ayurvedic text The author is called Vagbhata .The approximate best time to wake up or Brahma Muhurta is mentioned there.
Pratahkalotthana (Wakeup Time).

ब्राहमे मुहुर्त उत्थिष्ठेत स्वस्थो रक्षार्थमायुष:  in order to protect
  his life , healthy person should get up from the Bed in Brahma
  Muhurta.

Arundatta in his "Sarvangasundari" commentary on Asthanga Hrdaya it is clearly stated as

रात्रेश्चतुर्दाशो मुहूर्तो    ब्रहमो मुहूर्त: | That means brhama
  muhurta is the 14 th muhurta kala of the night. One muhurta is
  equivalent to 48 minutes.

Whole night consisit of 15 muhurtas = 15*48 =720 minutes.
Brahma muhurta is te time , which is after completion of 13 muhurtas in the night time i.e.
13*48=624 minutes
720-624=96 minutes
Hence one has to getup from the bed early in the morning 96 minutes before sunrise i.e. about 4:24 a.m.
It is sutaible time to study and obtain knowledge. It is also the time when all the three doshas are in equilibrium state.

Here more about  Ashtanga Hridaya-
There is also mentioning of Daybreak or Brahma Muhurta in  Srimad Bhagavata Purana. Swami Prabhupada in his commentary of the below shloka   is explaining  significance of Brahma Muhurta. It's said that this time is recommended very suitable for conducting Spiritual activities , at this time they will have great effect than any other part of the day or night.

ते तु तज्जगृहू रूपं त्यक्तं यत्परमेष्ठिना । मिथुनीभूय
  गायन्तस्तमेवोषसि कर्मभिः ॥SB 3.20.46||
te tu taj jagṛhū rūpaḿ tyaktaḿ yat parameṣṭhinā mithunī-bhūya
  gāyantas tam evoṣasi karmabhiḥ
The Kimpurusas and Kinnaras took possession of that shadowy form left
  by Brahma. That is why they and their spouses sing his praises by
  recounting his exploits at every daybreak. Purport -The time early in
  the morning, one and a half hours before sunrise, is called
  brahma-muhurta. During this brahma-muhurta, spiritual activities are
  recommended. Spiritual activities performed early in the morning have
  a greater effect than in any other part of the day.

A:

Ganganatha Jha, in his translation of Medhatithi's commentary on the Manusmriti quotes the following from a Dharmashastra digest:

Vīramitrodaya (Āhnika, p. 13), which explains ‘Brāhma muhūrta’ as ‘the last quarter of the night’, and adds that the time is so called because it is the time for the awakening of Brāhmī, i.e., Bhāratī, the goddess of speech; and that the term ‘muhūrta’ is to be taken as standing for time in general, and not in the restricted technical sense of a period of 48 minutes; and this on the ground that 48 minutes would not suffice for all those acts that are prescribed for being done after rising and before sunrise. It goes on to add that according to other Nibandhas, the last but one Muhūrta (48 minutes) of the night is called ‘Brāhma’, because it is sacred to Brahman. The conclusion that it arrives at is that those who have to perform all the acts of Vedic study and the rest should rise in the beginning of the last quarter of the night, i.e., at 3 a.m. while others in the third Muhūrta of that quarter, i.e., after 4-36 a.m.

See source link for more quotations of the same author.
As to its significance and duties, see the various Puranas such as the Brahma-purana 113.17-18:

One shall get up in the Brāhma Muhūrta and think about virtue and wealth. After getting up, one shall perform the Ācamana rite. After taking both and making himself pure one shall worship the Sandhyās. The early Sandhyā (i.e. dawn) he shall worship even when the stars are seen. He shall worship the late Sandhyā (i.e. dusk) even when the sun is visible. He shall perform Sandhyā prayers duly. Unless in extreme case of emergency he shall not forsake it.

As well as the Garuda-Purana chapter 229:

Rising at the Brahma Muhurta (about half an hour before the dawn) a house-holder shall attend to the calls of nature, and then having carefully washed himself, at the close of the night, shall think of his own good both in this world and the next. Then he shall bathe and attend to the rite of his Sandhya meditation. He shall perform the rite of his morning Sandhya after having washed his face and cleansed his teeth.

Also, the Rudra-samhita of the Shiva-purana:

16-18. One shall get up early in the morning during the Brāhma Muhūrta (about an hour before dawn). He shall remember the preceptor and Śiva. O sage, he shall then remember the holy centres and meditate on Hari. Thereafter he shall remember me, the deities and the sages. Then he shall recite a prayer in the name of Śiva duly. Then he shall get up and evacuate his bowels in southern quarter.

In his comments on the above verse, the translator J. L. Shastri, says the following about Brahma-muhurta:

It is the period between the fourth and the second ghaṭikas before sunrise. “rātriśca paścime yāme muhūrto brāhmya ucyate”