Q:

Why do I have to deal with Throwable if I invoke getCause() on an Exception

It is designed in Java that I get a Throwable object if I invoke getCause() on an Exception.
I understand that getCause() is simply inherited from Throwable and I know that Throwable can be either an Error or an Exception, but a programmer generally should work only on the Exception level without dealing with Throwable/Error classes.
What was the reason in the Java exception hierarchy design to, for example, not include getCause() in the Exception class that would return an Exception object?
Here is an illustration of the inconvenience taken from Java Concurrency In Practice (Brian Goetz):
public class Preloader {
    private final FutureTask<ProductInfo> future =
        new FutureTask<ProductInfo>(new Callable<ProductInfo>() {
            public ProductInfo call() throws DataLoadException {
                return loadProductInfo();
            }
        });
    private final Thread thread = new Thread(future);
    public void start() { thread.start(); }
    public ProductInfo get()
        throws DataLoadException, InterruptedException {
        try {
            return future.get();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof DataLoadException)
                throw (DataLoadException) cause;
            else
                throw launderThrowable(cause);
        }
    }
}

It is said in the book:

...but also because the cause of the ExecutionException is returned as a Throwable, which is inconvenient to deal with...

And in launderThrowable() it is dealt with rethrowing Error right away (because we don't want to deal with it) and returning RuntimeException:
public static RuntimeException launderThrowable(Throwable t) {
    if (t instanceof RuntimeException)
        return (RuntimeException) t;
    else if (t instanceof Error)
        throw (Error) t;
    else
        throw new IllegalStateException("Not unchecked", t);
}

A:

getCause is a method defined in Throwable, and simply inherited in Exception. The cause of a Throwable is simply a Throwable (it could be an Exception or an Error).
IMO, having a method, say getCauseAsException, that just returns an Exception if any as the cause exception is not really useful. You could simply invoke getCause() and check if it's an instance of Exception if you're just concerned with Exception and not Errors.

A:

First, if you have a type that has a few subtypes, and their behavior is really the same, it makes sense to define the methods at the parent class. Basically, what the designers are saying is: "Throwable can have a cause, which is also a throwable, and you can get that cause". And you can do that in both Exception and Error because they both happen to be throwables.
Now, the Throwable hierarchy exists since Java 1.0, and generics didn't exist there. Nowadays you might be able to have defined the behavior like this:
class ModernThrowable<T extends ModernThrowable<T>> {
    T getCause() {...}
}

And you could define ModernException as extends ModernThrowable<ModernException> and then you could get the sort of behavior that you expect.
But this design didn't exist back then, so you get a Throwable back, and you have to cast it. That's how things used to work and you have to keep backward compatibility.
But actually... as plausible as this may sound, this is not true. At least, it's not the whole truth.
It is perfectly OK to get an Error as the cause of an Exception. Take a look at javax.management.RuntimeErrorException. When you are working with an agent, you might get an Error, which in these special circumstances, should not cause you to abort the system immediately. So you put it as the cause of this special Exception. And thus, your getCause() will actually return an Error from an Exception.
So if it wasn't designed like this, you would have to go through hoops - have a specialty method just for the cause of this particular exception.


Q:

"Orthogonal complement" in $\mathbb{Z}_q^n$

Let $W$ be the finite $\mathbb{Z}$-module obtained from $\mathbb{Z}_q^n$ with addition componentwise where $\mathbb{Z}_q$ is the integers mod $q$. Let $V$ be a submodule of $W$. Let $V^{\perp} = \{w \in W : \forall v \in V \quad w \cdot v = 0 \}$ where $w\cdot v = w_1v_1 + \ldots + w_nv_n$. Is it true that ${(V^{\perp})}^{\perp} = V$ for all $q \geq 2$?
According to Wikipedia, this holds for finite dimensional inner product space, but I wish to know whether it holds in $\mathbb{Z}_q^n$ where $\cdot$ isn't an inner product.

A:

Yeah, it's true.  Since $\mathbb{Z}/q$ is a principal ideal ring, there is an extension of the Euclidean algorithm to matrices that puts any matrix in Smith normal form.  It means that after an automorphism of $(\mathbb{Z}/q)^n$, any submodule $V$ can be put into a standard form in which it is generated by vectors of the form $d_k e_k$, where $e_k$ is a standard basis vector, $d_k$ is a divisor of $q$, and each $k$ only appears at most once.  In that case you can check directly that $(V^\perp)^\perp$ is no larger than $V$.
(I'm taking the question in the more interesting case in which $q$ might not be prime.)


Q:

Number of neigbour Voronoi cells for a random set of points on S^k or cube [-1, 1]^k?

Consider $S^k \subset  R^{k+1} $.  Sample $N$ points by say uniform distribution. (Example k=120, N=2^24, i.e. N>>k ).
Consider Voronoi cell around each point.
How many neighbours would a cell have ? I mean neigbours are the cells which have non empty intersection. "How many" means average over distribution. (Clearly it is less than N,
but what is it behaviour ? N/C, sqrt(N) or what ?)
Actually I more interested not about the sphere but about the cube: take unit cube $[-1, 1]^k$.
And take randomly some number $N$ of its vertexes.
The same questions.

Motivatation:
As I tried to explain in this MO quest these problems are related to decoding noise signal. This question can be translated in this language as follows - if there chance to do some "preprocessing" such that it would significantly reduce decoding complexity.
I mean in the answer is much smaller than N, then yes, otherwise, not.

A:

When $k=2$, you can use combinatorics to avoid any relation with probability. From Euler formula, one gets that the mean degree of a graph with $N$ vertices on $S^2$ is $6-\frac{12}N$ (see e.g. Proofs from the book, section on Euler formula).
Applying this to the neighbors graph of your tesselation, you get that the average number of neighbors of a cell is bounded by $6$ independently of $N$.
For this you have to rule out cells that touch by a corner only (otherwise the graph need not be planar), but I guess this only happen with null probability.

A:

This was studied by Miles in the seventies. A good reference is Schneider and Weil's book. The relevant results are in section 10.2


Q:

How to query for overlapping date ranges?

I have members who are for a limited time assigned to a team. Members can be assigned to multiple teams. The members create worklogs on a day. Worklogs are assigned to a member, the member is assigned to a team. The intermediate table Membership stores the assignment dates of team members.
I need to query all worklogs related to a specific team during e.g. the first quarter of 2019. The team members could've joined and left during the quarter and only the worklogs during their team assignment should be considered.
class Teamuser(models.Model):
    key = models.CharField(max_length=200, primary_key=True)
    fullname = models.CharField(max_length=200)

class Team(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=200)
    members = models.ManyToManyField(Teamuser, through='Membership')

class Membership(models.Model):
    id = models.IntegerField(primary_key=True)
    memberid = models.IntegerField(null=False, blank=False)
    teamuser = models.ForeignKey(Teamuser, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    dateFrom = models.DateField(null=True, blank=True, default=None)
    dateTo = models.DateField(null=True, blank=True, default=None)

class Worklog(models.Model):
    worker = models.ForeignKey(Teamuser, on_delete=models.PROTECT)
    day = models.DateField(null=True, blank=True, default=None)
    effort = models.IntegerField()
    comment = models.TextField(null=True)

I tried to get first a list of all the users that were assigned during the time frame.
start = date(2019,1,10)
end = date(2019,1,20)
Teamuser.objects.filter(Q(membership__team_id=305), Q(membership__dateFrom__range=[start, end]) | Q(membership__dateTo__range=[start, end]) | Q(membership__dateFrom=None) | Q(membership__dateTo=None))

However, this does not include people that joined a team before the querying date and left afterwards. People with no dateFrom and dateTo are always in the team.
My biggest challenge at the moment is to figure out on which dates the two date ranges (Query for Q1, Memberships of a Teamuser) overlap
I expect an output of all Worklogs a Teamuser created during the timeframe (Q1 2019) while being assigned to the queried team (e.g. only January 2019).

A:

This gets you the users who were team members at some point in the time period considered:
teamusers = (Teamuser.objects
    .filter(
        Q(membership__dateTo__gte=start) | Q(membership__dateTo=None),
        Q(membership__dateFrom__lte=end) | Q(membership__dateFrom=None),
        membership__team_id=305,
    )
    .distinct()
)

This filters for end dates that are null, greater than or equal to the period start, and start dates that are null, lower than or equal to the end date.
But this is at most useful to pre-filter the work log, as you cannot just take the logs of all members in the list in the time period considered and be done with it. You might have work logs that the users posted outside their membership dates.
So you'll have to start from the log table, prefiltering it for the period in question and possibly for the team member list calculated above if you determine that it increases performance.
worklogs = Worklog.objects.filter(day__range=[start, end], worker__in=teamusers)

Then you use a subquery to check in every record whether the user who posted it was a member of the team on that particular date:
from django.db.models import Q, OuterRef, Exists

membership_subquery = Teamuser.objects.filter(
    Q(membership__dateTo__gte=OuterRef('day')) | Q(membership__dateTo=None),
    Q(membership__dateFrom__lte=OuterRef('day')) | Q(membership__dateFrom=None),
    membership__team_id=305,
    teamuser=OuterRef('worker'),
)

worklogs = (worklogs
    .annotate(in_team=Exists(membership_subquery))
    .filter(in_team=True)
)

Now you have a list of all valid work logs, and you can append further processing, like annotating aggregates etc.


Q:

Online tool for diagonalizing matrices?

I need some online tool for diagonalizing 2x2 matrices or at least finding the eigenvectors and eigenvalues of it. I don't like to download any stuf because I'm not able to, some online tool will do the job.
Thanks.

A:

Wolframalpha has an option. Try this: http://www.wolframalpha.com/examples/Matrices.html

A:

Let $A$ be your $2$ by $2$ diagonalizable matrix, let $\lambda$ and $\mu$ be its eigenvalues, and let $I$ be the $2$ by $2$ identity matrix.
If $\lambda=\mu$, then $A=\lambda I$ and there is nothing to do.
If $\lambda\not=\mu$, then the nonzero columns of $A-\mu I$ (such always exist) are $\lambda$-eigenvectors.
[Recall that the eigenvalues of $$\begin{pmatrix}a&b\\ c&d\end{pmatrix}$$ are the roots of $X^2-(a+d)\,X+ad-bc$.]
[There is an obvious generalization to $n$ be $n$ matrices: in the above recipe to get a  $\lambda$-eigenvector, replace $A-\mu I$ by the product of the $A-\mu I$, where $\mu$ runs over the eigenvalues not equal to $\lambda$.]
To prove this in the $2$ by $2$ case, it suffices to check
$$A^2-(a+d)\,A+(ad-bc)\,I=0,$$ which is straightforward. This is (a particular case of) the Cayley-Hamilton Theorem.

A:

Try the Online Matrix Calculator.


Q:

Reinstalling Linux: how to avoid downtime?

My website runs on a dedicated Debian LAMP server . I would like to update the system (let's say I have a pretty old Debian version and I want to reinstall everything from scratch)
What strategy can I use to not have my website down while I am reinstalling everything?
Addendum
Of course I know I can buy another server in the meanwhile and change the DNS whenever it's done. But this doubles my work.
Aren't some service that maybe can act as a proxy-cacher for a limited amount of time? Maybe what does CloudFlare but caching everything not just images.

A:

If you don't want any downtime, then really the only option is to build your new install on separate hardware and when you're happy that it's all working correctly, alter your DNS settings to point to the new server.
If you don't have another physical server, you might consider running your app on a cloud server while you do the upgrade of your physical server.

A:

Have a second server take the load, using a load-balancer or just by re-pointing the IP for the duration of the update. In fact, if you use a load-balancer, you can then leave both servers up afterwards.
This is assuming the site isn't database-dependent. So, given the limited set of facts you gave us, this is my simple answer.

A:

Aren't some service that maybe can act as a proxy-cacher for a limited amount of time?

If your site is purely static, or at least is somewhat useful when setup read-only.  Then you temporarily pay for some web-hosting, and then use something like wget, or similar tools to spider the static portion of your web site.
You could setup a proxy in the cloud, setup squid as a proxy to your site, adjust DNS temporarily so all access goes through the proxy, then configure Squid to operate in offline mode, after you have everything cached.  You would probably want to script something that would have a browser visit all the important pages via the proxy, so everything gets into the cache.


Q:

What role does hymnody play in non-Western churches?

My wife and I were discussing the central role that congregational singing of hymns takes in Western churches, when it dawned on me that I don't real have a good understanding what its like outside of Roman Catholic and Western Protestant circles. I realized I just assumed everybody sang "Amazing Grace," "Tis So Sweet To Trust In Jesus," "Are you washed in the Blood," and all those "traditional Baptist hymns" I think about.  That's not something I could back up, however.
In a Baptist service, for instance, there will be several hymns (and usually one of them has to mention "the blood of Jesus"), that will generally precede the sermon, and almost always a "decision hymn" after the sermon and during the altar call, which the preacher typically uses to drive home the point of the message, and provide time for reflection. Often the theology of the hymns plays a fairly significant role in shaping the theology that parishioners really carry throughout the week
In an Episcopalian one, there are hymns sung during communion, but because the sermon itself comes so early in the order of worship, the songs with the richest theology tend to be the parts of the mass that are sung every week - the Sanctus, the Doxology, etc...
I'm curious to get an understanding of those churches I'm least familiar with:

LDS
Jehovah's Witness
Eastern Orthodox (totally different league)
and just a non-Western perspective altogether.

(Anybody outside the US - I really want to know - when do you sing hymns, and what types do you sing?)
Specifically, what is the role of congregationally sung music - is it used to drive home theological points, used primarily in ritual, or is it not present, in the denominations listed above?
Please feel free to characterize what role congregational singing takes in your churches, and what the purpose of these songs is.

A:

DISCLAIMER: I am from the USA, but I happen to live in a part of the country that has over 20 Eastern Orthodox churches in a close radius, representing numerous nationalities and distinct ethnic expressions of the faith (for instance, we have multiple Romanian, Serbian and Greek Orthodox churches, and we also have Macedonian, Serbian, Ethiopian, Coptic (Egyptian), and American Orthodox churches).
Eastern Orthodox typically have chanting and sung liturgy, and also choirs - usually a capella but sometimes including simple instruments or a "church bell." You must understand that EVERYTHING centers on the Divine Liturgy in Orthodox worship. It is "the work of the people." The traditional expression concerning Orthodox liturgy is "Always everyone, always together." The OCA website says it well:

"The Divine Liturgy is the common action of Orthodox Christians officially gathered to constitute the Orthodox Church. It is the action of the Church assembled by God in order to be together in one community to worship, to pray, to sing, to hear God’s Word, to be instructed in God’s commandments, to offer itself with thanksgiving in Christ to God the Father, and to have the living experience of God’s eternal kingdom through communion with the same Christ Who is present in his people by the Holy Spirit....
Because the Divine Liturgy exists for no other reason than to be the official all-inclusive act of prayer, worship, teaching, and communion of the entire Church in heaven and on earth, it may not be considered merely as one devotion among many, not even the highest or the greatest. The Divine Liturgy is not an act of personal piety. It is not a prayer service. It is not merely one of the sacraments. The Divine Liturgy is the one common sacrament of the very being of the Church Itself. It is the one sacramental manifestation of the essence of the Church as the Community of God in heaven and on earth. It is the one unique sacramental revelation of the Church as the mystical Body and Bride of Christ."

It is important to understand this, because they do not have a "disconnected" view of worship. In other words, they do not view worship as a conglomeration of singing, reading, etc. It is all one Divine Liturgy. Worship is a participatory experience for all Orthodox Christians gathered. Orthodox tend to view Protestant worship as being a show; something that professional worshippers perform as a service for the people. This runs counter to Orthodox theology, where Divine Liturgy is the common work of the people "on behalf of all and for all." You must also understand that the building carries much significance (oblation and altar tables, icon screen, etc.) and this all ties into Orthodox theology. It seems that Protestant worship is disconnected from its theology. It is acceptable to sing songs with little theological content and preach on any chosen topic. Orthodox follow the Church calendar which prescribes what readings from scripture will occur and many aspects of liturgy will tie in to this "theme" or focus for each gathering. Everything in the service is united, and the Church calendar is designed to teach the entire Christian Orthodox faith to participants over time and then reinforce it. It globally unites Orthodox believers because they can go to a different Orthodox church across the world and they will pick up where they left off. I know that in many Protestant churches, even if you go to the same "denomination" down the street it may be a different message and scripture verse being taught. In Orthodox Christianity this is not so - thus the churches are truly united in belief and practice.

"The living experience of the Christian sacramental and liturgical life is a primary source of Christian doctrine. In the liturgy of the Church, the Bible and the Holy Tradition come alive and are given to the living experience of the Christian people. Thus, through prayer and sacramental worship men are “taught by God” as it was predicted for the messianic age (Jn 6:45).
In addition to the living experience of the liturgy, the texts of the services and sacraments provide a written source of doctrine in that they may be studied and contemplated by one who desires an understanding of Christian teachings. According to the common opinion of the Orthodox Church, the sacramental and liturgical texts—the hymns, blessings, prayers, symbols, and rituals—contain no formal errors or deformations of the Christian faith and can be trusted absolutely to reveal the genuine doctrine of the Orthodox Church." (OCA)

Concerning style, here is a source that says it well:

"Eastern Christianity (the Eastern Orthodox, Oriental Orthodox and Eastern Catholic churches) have a very rich and ancient hymnographical tradition.
Eastern chant is almost always a cappella, and instrumental accompaniment is rare. The central form of chant in the Eastern Orthodoxy is Byzantine Chant, which is used to chant all forms of liturgical worship. Exceptions include the Coptic Orthodox tradition which makes use of the sistrum, and the Ethiopian Orthodox Tewahedo Church, which also uses drums, cymbals and other instruments on certain occasions."

The Orthodox Church has been reevaluating the role of music in worship as of late. One source says,

"Russian Orthodox church music has its particularly unique development. Byzantine music remains basically monophonic (single-line unison singing). But part-singing appeared in Lvov and began to spread in Southern Russia and the Ukraine as early as the 15th Century. From this we can trace early experiments with harmonization, and in the 17th Century the influence of the Kievan schools of harmony on Moscow. Choirs of sorts began to be schooled in the Imperial Court, although they sang in small groups and were made up of male singers only.
It was Peter the Great in the 18th Century who gave rise to the Imperial Chapel Choir. The movement to introduce Western European harmonization and the chorale style spread very quickly, initiating the new period of concert-like choir singing. Bortniansky, under the patronage of Catherine the Great, still remains the best example of the composer-conductors and their church choirs of the choral tradition.
By the beginning of the 20th Century there was already a great interest among Church musicians to return to the traditional roots of the canonical chant systems. Kastalsky particularly stands out among them. While choral compositions and choir singing remain popular to this day, among serious students of Church music more and more is sacred singing looked upon as a discipline of liturgical theology rather than simply as a musical art.
This is particularly so in America, as we accept the responsibility for an Orthodox inculturation of a new land, a new language and a new people. As we attempt to find our own style in response to new needs and situations (especially those of the small missions), above all we seek to be anchored to the great Tradition.
This great Tradition, however, insists neither on a rigid formalism nor a return to a hypothetically more primitive practice. There is room in Orthodox culture for both choir singing and congregational participation, for ancient chants and familiar harmonized works, as well as perhaps for new adaptations based on the timbre of the English language, developed from the local materials of our own particular time and place. All of this is possible so long as none of it contradicts our ecclesial identity as the Orthodox Church."

I also found a video showing some 4th-century-style Orthodox worship in Africa. The video features the koboro drum and the sistrum. Here is another video with some chanting/singing like you might hear in an Orthodox church. The Russians have some beautiful chanting as well, listen here. It is heavenly. It should also be noted that Orthodox incorporates all the senses, not just hearing and seeing, but also smell, touch, and taste.
I know I quoted a lot of sources, but I felt they said things better than I could. I know the original question was related to hymnody, but I wanted to make it clear that hymnody is merely a part of the Divine Liturgy in Eastern Orthodox understanding - it is not a separate discipline but an integrated part of the whole. It is difficult to fully answer this question without first discussing all aspects of Worship in the Orthodox faith (of which Divine Liturgy is only one). The hymns tie into the greater Liturgy and worship experience, which are informed by Holy Tradition and centered on Christ, Who is our Song.


Q:

Returns zero for all values retrieved from the parse database

I'm using parse backend to store and retrieve the datas for my android app, the storing gets done properly but i have problem in retrieving it. I just went through the parse documentation to retrieve the result but what i get is just 0 for all the retrieved values..im suret that the class exists in the parse cloud with valid values but still i get 0 for all the queries.. this is my code to save:
    Toast.makeText(getApplicationContext(),"writing to parse",Toast.LENGTH_SHORT).show();
    ParseObject dataObject = new ParseObject("Score");
    dataObject.put("correct",correctAnswers);
    dataObject.put("wrong",wrongAnswers);
    dataObject.put("percent", percentage);
    dataObject.saveInBackground();

this is how i get back the saved data
ParseQuery<Score> query = ParseQuery.getQuery("Score");
    try {
        List<Score> scoreList = query.find();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    query = ParseQuery.getQuery("Score");
    final Activity ctx = this;
    query.findInBackground( new FindCallback<Score>() {
        @Override public void done(List<Score> scoreList, ParseException e) {
            if ( e == null ) {
                ParseObject dataObject = ParseObject.create("Score");
                int p = dataObject.getInt("correct");
                int q = dataObject.getInt("wrong");
                int r = dataObject.getInt("percent");
                Toast.makeText(ExamRecordActivity.this,String.valueOf(p),Toast.LENGTH_SHORT).show();
                Toast.makeText(ExamRecordActivity.this,String.valueOf(q),Toast.LENGTH_SHORT).show();
                Toast.makeText(ExamRecordActivity.this,String.valueOf(r),Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ctx,
                        "Error updating questions - please make sure you have internet connection",
                        Toast.LENGTH_LONG).show();
            }
        }
    });

A:

Inside the done method you are creating a new by calling ParseObject dataObject = ParseObject.create("Score"); and then trying to read values from it without putting any in.
I don't know what the structure of your class is but you need to be iterating through List<Score> scoreList in order to get the queried data.


Q:

no aparece grafica con dos consultas php a mi base de datos

Estoy realizando un proyecto de un medidor de temperatura analógico que vuelca la fecha y la medida a una base de datos y quería hacer en php una gráfica con highcharts consultando la fecha y la medida para representarlo en un gráfico de lineas.
La consulta funciona (la probé por separado, apunta a una columna de la db llamada fecha y otra llamada temperatura) pero me ocurre una cosa curiosa: tengo dos consultas distintas, una para el eje x (categories) y otra para el y (data). Si pongo solo una de los dos consultas, ya sea data o categories, la gráfica aparece (las adjunto abajo), pero si pongo las dos juntas, no muestra ninguna gráfica.
No soy mas que un novato en programación y no encuentro donde esta el fallo. ¿Podríais ayudarme? Mil gracias
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Highcharts Example</title>

<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');

$servername = "localhost";
$database = "estacion_meteo";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$result = mysqli_query ($conn,"SELECT * FROM datos");

?>

A:

Tu error es que abres dos bucles sin necesidad. Me refiero a esto: while ($row=mysqli_fetch_array($result). Es preciso entender que cuando obtienes los datos, los cuales en este caso se encuentran en $result, lo que tienes ahí es un puntero  hacia los datos, y cada vez que aplicas un  fetch mueves el puntero. Si tú aplicas el while dos veces significa que la segunda vez el puntero estará ya vacío, puesto que en el primer while ya lo recorriste completo. En consecuencia, tienes que obtener todos los datos dentro del primer while.
Prueba del siguiente modo. La idea aquí es obtener los datos de la fila temperatura dentro del único while, guardarlos en la variable $temperaturas y luego colocarlos dentro del elemento data correspondiente.
Dado que el código es algo confuso puede que no sea exactamente así y haya que adaptarlo. Al menos lo que se ve es que dentro de data iría un array se temperaturas. Si no funciona agradezco que muestres en la pregunta un ejemplo del objeto final que debe construirse para poder ayudarte mejor. La clave es usar el  while  una sola vez, para sacar de él los datos que necesites. El error es, como necesitas los datos en dos partes distintas, haber usado el while dos veces.
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Highcharts Example</title>

<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');

$servername = "localhost";
$database = "estacion_meteo";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$result = mysqli_query ($conn,"SELECT * FROM datos");
$temperaturas=array();
?>

EDIT
Propuesta basada en tu respuesta
Aunque funcione, el código no está optimizado haciendo dos veces la
  misma consulta. Puedes probar algo así:
#Creamos dos variables para concatenar los valores de cada dato diferenciado
$categories="categories: [";
$data="data: [";

$sql = "SELECT * FROM datos";
$result=mysqli_query($conn,$sql);
while ($registros=mysqli_fetch_assoc($result))
{
  #Se concatena el dato de cada columna a la variable que corresponde
  $categories.= "$registros[fecha] ,";
  $data.= "$registros[temperatura] ,";
}
#Se cierra cada variable
$categories.="]";
$data.="]";

#Se imprimen las variables
echo $categories;
echo $data;


Q:

Por que eu deveria criar um método estático e não um que poderia instanciar a classe e utilizar esse método?

Eu realmente não vejo diferença nessas duas utilizações de métodos. Alguém poderia ser mais especifico comigo e me informar sobre isso?

A:

Um método estático deve ser criado caso faça sentido tê-lo sem ter uma instância do Objeto.
Exemplo simples: em uma classe Geladeira você pode ter um método estático double converterCelsiusFahrenheit(double celsiu) mesmo que não tenha uma geladeira. Já o método void adicionarItem(Item item) está referenciando uma geladeira em específico, por isso não deveria ser estático, já que precisa de uma instância.


Q:

Conditionally loading ad code based on device screen size using javascript

How to conditionally display ads (via an ad server) to different screen size for mobile devices?
I don't want to set the display to none for hiding content, as this will skew the ad impression count.
I want to inject the ad code (eg. ) into div using client-side javascript without jQuery.
For example,

If width < 768px
   inject ad code for mobile
else
   inject ad code for tablet

How do I implement this idea?
And how will situation be handled when device rotation taking place when device width changes from less than 768px to grater then 768px?

A:

So, two things to cover:
One way that you could do this would be to simply have the JS capture the screen size and to then report that to your server when asking for an ad. The server can then make the decision on which ad to serve.
You talk about screen rotation and you have tagged media-queries in your question. @media are CSS (not JS) features that allow you to tailor your look/feel based on screen size. It would be up to you to ensure that the ads you serve can be somehow displayed both vertically and horizontally - you wouldn't want to have to load new ads every time the device changes orientation.
Detecting screen size completely accurately can very on device and how it is reported. However, for JavaScript world, this SO post covers what you need to know.


Q:

Xpath - Extracting multiple specific differnt parts of text strings from one text node

I have three samples of text nodes that and I want to extract three different parts of the text, using a universal x-path.
First

                This is an amazing game from the company Midway Games. Excellent gameplay. Very good game.

Second

                New Line Cinema distributed this movie in 1995.

Third

                New game from 2011, with new 3D graphics. This game was made by NetherRealm Studios.

The extraction should be either Midway Games or New Line Cinema or NetherRealm Studios
Note that the text node allways include just one company, never two or three (just one).
My try is from this question but the problem is that it dosen't work nor include all three companies.
substring('Midway Games',1,12*contains(//p[@class='product-summary']/following-sibling::text()[1], 'Midway Games'))

A:

As the input will only contain one of them, you can use concat to join the results.
concat(
  substring('Midway Games', 1,
      12*contains(//p[@class='product-summary'], 'Midway Games')),
  substring('Line Cinema', 1,
      11*contains(//p[@class='product-summary'], 'Line Cinema')),
  substring('NetherRealm Studios', 1,
      19*contains(//p[@class='product-summary'], 'NetherRealm Studios'))
)

You can remove the line breaks that I added for readability as you want.
I had to fix the query you provided: the text nodes are no following-siblings, but children. Your XPath processor will query the (concatenated) text nodes below that element anyway as contains works on strings.


Q:

Create dictionary where keys are from a list and values are the sum of corresponding elements in another list

I have two lists L1 and L2. Each unique element in L1 is a key which has a value in the second list L2. I want to create a dictionary where the values are the sum of elements in L2 that are associated to the same key in L1.
I did the following but I am not very proud of this code. Is there any simpler pythonic way to do it ?
L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
W = range(len(L)) # as L2

d = { l:[] for l in L }
for l,w in zip(L,W): d[l].append(w)
d = {l:sum(v) for l,v in d.items()}

EDIT:
Q: How do I know which elements of L2 are associated to a given key element of L1?
A: if they have the same index. For example if the element 7 is repeated 3 times in L1 (e.g. L1[2] == L1[7] == L1[8] = 7), then I want the value of the key 7 to be L2[2]+L2[7]+L2[8]

A:

You can use enumerate() in order to access to item's index while you loop over the list and use collections.defaultdict() (by passing the int as it's missing function which will be evaluated as 0 at first time) to preserve the items and add the values while encounter a duplicate key:
>>> from collections import defaultdict

>>> d = defaultdict(int)
>>> for i,j in enumerate(L):
...     d[j]+=i
...
>>> d
defaultdict(<type 'int'>, {2: 6, 3: 4, 4: 15, 5: 5, 7: 17, 8: 9, 9: 10})


Q:

ЧТО и ТО — клитики или нет?

Скажите, пожалуйста, являются ли слова "что" и "то" в пословице "Что посеешь, то и пожнешь" фонетическими, то есть имеющими ударения? Или они всё-таки примыкают к последующим словам?

A:

Думаю, что это самостоятельные слова с ударением. В русском языке проклитики и энклитики в основном служебные слова - предлоги, союзы, частицы. Вот фразового ударения на них нет, оно падает на сказуемые.


Q:

Style one single column with flexbox

Maybe I want something impossible.
I want a website with only a single column styled with flexbox. The purpose is that only one column stretches its height to the footer regardless the size of the content of the column. Something like below structure:

I try to reach that with this code (I am using bootstrap):

       stuff...

       stuff...

       Stuff...

          Stuff..

       Stuff

And then adding in the CSS this specific for the col-c and col-c-child:
.col-c {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.col-c-child {
  flex: 1;
}

But is not working.
Any idea?
THE SOLUTION:

Create a row for the header, other for the content and other for the footer, that is - don't have everything in the same row.
Build a div-wrapper englobing col-a, col-b and col-c with display:flex and flex-direction: row;
get rid of col-c-child
col-c with flex: 1;

Thanks to @jelleB who elucidated me for part of it.

A:

Put the header and the footer in different rows.
You should build a div below col-a (without content)
Use min-height: 100% on the row    where you put col-a/col-b/col-c in

Give this a shot


Q:

Most performant way to write, read and delete (not update) data to a SQL Server database in .net

I need to insert rows rows into a database, then in another thread read those rows and then (in a separate call delete them).
Normally I would just break out Entity Framework for this.  But I need this to be fast.  Really fast.
A row would be an bigint, bigint and a varchar(max).
Is there a faster way that Entity Framework?  If so, what is it?
(I am going against SQL Server 2008 R2)

A:

There is some good info on the Dapper ORM page about this.
See section Performance of SELECT mapping over 500 iterations - POCO serialization and below. It only discusses SELECTs, but you can extrapolate from this to a certain degree.
For example, you can see that Entity Framework is pretty much the worst way to go, in terms of query speed.
Method                             Duration    Remarks
Hand coded (using a SqlDataReader) 47ms
Dapper ExecuteMapperQuery<Post>    49ms
ServiceStack.OrmLite (QueryById)   50ms
PetaPoco                           52ms        Can be faster
BLToolkit                          80ms
SubSonic CodingHorror              107ms
NHibernate SQL                     104ms
Linq 2 SQL ExecuteQuery            181ms
Entity framework ExecuteStoreQuery 631ms

A:

Raw ADO.NET is the fastest, but I would choose Dapper as a micro-ORM. It is blazingly fast, and helps you a lot in the development.
However, it is important to know that the primary reason why Dapper or similar would be the fastest, is primarily because of your control, you can carefully craft the best performing SQL queries.
I would not bother to think much about the data access technology, other than you need something, that brings you close to the actual SQL and don't enforce too many abstractions upon you. Use your time to think about the database, indexes layout, transaction processing and query optimization. That is where you will find the primary performance gains.


Q:

Get nodes from xml files

How to parse the xml file?
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
    <loc>link</loc>
    <lastmod>2011-08-17T08:23:17+00:00</lastmod>
</sitemap>
<sitemap>
    <loc>link</loc>
    <lastmod>2011-08-18T08:23:17+00:00</lastmod>
</sitemap>
</sitemapindex>

I am new to XML, I tried this, but it seems to be not working :
        XmlDocument xml = new XmlDocument(); //* create an xml document object.
        xml.Load("sitemap.xml");
        XmlNodeList xnList = xml.SelectNodes("/sitemapindex/sitemap");
        foreach (XmlNode xn in xnList)
        {
            String loc= xn["loc"].InnerText;
            String lastmod= xn["lastmod"].InnerText;
        }

A:

The problem is that the sitemapindex element defines a default namespace.  You need to specify the namespace when you select the nodes, otherwise it will not find them.  For instance:
XmlDocument xml = new XmlDocument();
xml.Load("sitemap.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("s", "http://www.sitemaps.org/schemas/sitemap/0.9");
XmlNodeList xnList = xml.SelectNodes("/s:sitemapindex/s:sitemap", manager);

Normally speaking, when using the XmlNameSpaceManager, you could leave the prefix as an empty string to specify that you want that namespace to be the default namespace.  So you would think you'd be able to do something like this:
// WON'T WORK
XmlDocument xml = new XmlDocument();
xml.Load("sitemap.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("", "http://www.sitemaps.org/schemas/sitemap/0.9"); //Empty prefix
XmlNodeList xnList = xml.SelectNodes("/sitemapindex/sitemap", manager); //No prefixes in XPath

However, if you try that code, you'll find that it won't find any matching nodes.  The reason for this is that in XPath 1.0 (which is what XmlDocument implements), when no namespace is provided, it always uses the null namespace, not the default namespace.  So, it doesn't matter if you specify a default namespace in the XmlNamespaceManager, it's not going to be used by XPath, anyway.  To quote the relevant paragraph from the Official XPath Specification:

A QName in the node test is expanded into an expanded-name using the
  namespace declarations from the expression context. This is the same
  way expansion is done for element type names in start and end-tags
  except that the default namespace declared with xmlns is not used: if
  the QName does not have a prefix, then the namespace URI is null (this
  is the same way attribute names are expanded). It is an error if the
  QName has a prefix for which there is no namespace declaration in the
  expression context.

Therefore, when the elements you are reading belong to a namespace, you can't avoid putting the namespace prefix in your XPath statements.  However, if you don't want to bother putting the namespace URI in your code, you can just use the XmlDocument object to return the URI of the root element, which in this case, is what you want.  For instance:
XmlDocument xml = new XmlDocument();
xml.Load("sitemap.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("s", xml.DocumentElement.NamespaceURI); //Using xml's properties instead of hard-coded URI
XmlNodeList xnList = xml.SelectNodes("/s:sitemapindex/s:sitemap", manager);


Q:

c# Delegate.BeginInvoke() and thread ID

let's say we have some simple code like this :
private static void Main()
{
    Console.WriteLine("Main thread {0}\n", Thread.CurrentThread.ManagedThreadId);

    Action asyncCaller1 = () => LongPerfomingTask(5);
    Action asyncCaller2 = () => LongPerfomingTask(3);

    var asyncResult1 = asyncCaller1.BeginInvoke(null, null);
    var asyncResult2 = asyncCaller2.BeginInvoke(null, null);

    asyncResult1.AsyncWaitHandle.WaitOne();
    asyncResult2.AsyncWaitHandle.WaitOne();

    Console.WriteLine("Done");
}

private static void LongPerfomringTask(int seconds)
{
    Thread.Sleep(TimeSpan.FromSeconds(seconds));

    Console.WriteLine("Thread {0} finished execution", Thread.CurrentThread.ManagedThreadId);
}

Delegate.BeginInvoke() does not create a thread, It's executing code in a caller's thread when it is in idle state, right?So, why the output of this sample application is like this :
Main thread 1

Thread 4 finished execution
Thread 3 finished execution
Done

A:

No, Delegate.BeginInvoke uses the thread pool. Always. There's no concept of "executing in the caller's thread when it's idle" unless you're thinking of adding tasks to a UI message queue... were you getting confused with Control.BeginInvoke / Dispatcher.BeginInvoke?
In this case you've got a console app - there's no message pumping going on to start with.


Q:

Creating a static Settings class from inside that class but non static fields not updating

So I have settings file for my project that looks like the following.
@Component
public class Settings {
    private transient final BuildProperties buildProperties;
    private static Settings settingsStatic;
    private String TF_VERSION = "EMPTY";

    private static final Logger LOGGER = LoggerFactory.getLogger(Settings.class);
    private final String REPO_TF_SUBSCRIPTION =
         "git::https://github.xxx.com/xxxxx/xxxx//subscription?ref=" + TF_VERSION);

    @Autowired
    private Settings(BuildProperties buildProperties) {
        this.buildProperties = buildProperties;
        TF_VERSION = this.buildProperties.getVersion();
        LOGGER.info("TF_VERSION is {}", this.buildProperties.getVersion());
        settingsStatic = this;
    }

    public static String getTerraformSubscriptionRepository() {
        return settingsStatic.REPO_TF_SUBSCRIPTION;
    }

}

The Logger outputs the correct version ie. 3.4.0, but when I call getTerraformSubscriptionRepository() it comes back with TF_VERSION=empty instead of what I expected, 3.4.0.
Can anyone explain to me why that would be happening.

A:

private String TF_VERSION = "EMPTY";
private final String REPO_TF_SUBSCRIPTION =
     "git::https://github.xxx.com/xxxxx/xxxx//subscription?ref=" + TF_VERSION);

You initialize REPO_TF_SUBSCRIPTION with TF_VERSION = "EMPTY", but because REPO_TF_SUBSCRIPTION is final, you can't modify it later, so it always be the same object, even if you modify TF_VERSION


Q:

Set div height to window height

I'm using the ASP.NET template and trying to set my content to take the full height of my window, but I can't achieve it. I have one container and 2 sibling divs inside it. Setting the bottom div to height 100% causes it to overflow the container.
I am using Bootstrap too.
I can only lower it's height percentage to lower value, but isn't there a better way?
I added a screenshot and a fiddle:
http://jsfiddle.net/ob1g0752/
HTML:

    test

    test

 footer

CSS:
body
{
    min-height:100%;
    min-width:100%;
}
html
{
    height:100%;
}

EDIT
Sorry, I published an old version of the fiddle, this is the updated one. Watch the yellow border overflows the container.
http://jsfiddle.net/ob1g0752/4/

A:

Removing the margin and padding will help, you can also add box-sizing: border-box; to account for borders and padding when setting widths. Also I'm not sure if you wanted to make your footer stick to the bottom of the page, but I did that along with the other fixes in this fiddle:
http://jsfiddle.net/ob1g0752/2/


Q:

C++ program to print counting numbers

In case the title is not precisely revealing what I want to do, the following is my problem.
I want to write a c++ program in a Linux or Mac terminal to print numbers that keeps counting from 1, 2, 3 ... at the same position under a command line mode. For example, it is like displaying the number of percentage when your work is progressing(e.g. downloading something, installing software...).
I wrote a simple for-loop to print numbers and use usleep(1000); for a delay of 1 second before printing next number. Then I use cout << "\b"; trying to move cursor back to display coming number at the same position. However I fail to create the effect that I want, the numbers are printed in a line.
I am not a skillful c++ programmer and know very limited on programming in a terminal environment. Can anyone help to give me hint or sample code for this function? Thanks!!

A:

If you are in Linux Terminal you can also use the following code,
system("clear");
cout<<"\b";
cout<<Your_Number;

// Repeat this in a loop and call the delay function


Q:

How to check if punctuation exists in a given amount of characters and if it does cut the text there - PHP?

I wish to check if there is a fullstop or question mark (i.e two needles) in the first 100 characters of an excerpt. If there is one then the excerpt would be cut off at the full stop, else it would be cut off at 100 characters.
Now I have the following which checks the position of the the needle: if it is under 100 characters then the excerpt is cut there, else the excerpt is cut at 100 characters with "...". The issue I have is that I wish to check for multiple needles, I have tried various methods such as looping and preg_match, but can get neither to work. Very new to php, so any pointers are much appreciated.
<?php
    ob_start();
    the_excerpt();
    $excerpt = ob_get_clean();
    $excerpt = preg_replace('/<.*?>/', '', $excerpt);;
    ?>
    <?php

    $needle = '.';
    $position = stripos($excerpt, $needle);

    if($position < 100) {
        $offset = $position + 0;
        $position2 = stripos ($excerpt, $needle, $offset);
        $first_two = substr ($excerpt, 0, $position2);
        echo $first_two . '.';
    }

    else {
        $cut = substr( $excerpt, 0, 100 );

        $excerpt = substr( $cut, 0, strrpos( $cut, ' ' ) ) . '...';

        echo $excerpt;
    }
?>

A:

I would try something like this. It needs lesser loops, and makes it possible to easily add needles. Cut the string at 100 characters right away. It is not going to be longer, there is no need to search the whole string.
<?php
    ob_start();
    the_excerpt();
    $excerpt = ob_get_clean();

    $maxLength = 100;
    $excerpt   = substr(preg_replace('/<.*?>/', '', $excerpt), 0, $maxLength);

    $needles    = ['.','?'];
    $offset     = min($maxLength, strlen($excerpt));
    $lnf        = $offset; // to store last needle found

    for ($index = 0; $index < $offset; $index++) {
      if (in_array($excerpt[$index], $needles)) {
         $lnf = $index + 1;
      }
    }

    $excerpt = substr($excerpt, 0, $lnf);

    ?>


Q:

test command symfony with phpunit

I create some basic command with symfony3.2 to generate some newsletter periodically
I'm dealing with some issue when i want to test my symfony command with phpunit 5.5.4.
It fail from the beginning:
    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output){

        $output->writeln("<info>Script start</info>");
        //...
        $output->writeln("<info>done</info>");
     }

with this unit test:
use MyBundle\Command\MyCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class MyCommandTest extends KernelTestCase
{

    public function testExecute(){

        $kernel = static::createKernel();
        $kernel->boot();

        $application = new Application($kernel);
        $application->add(new MyCommand());

        $command = $application->find('generate:newsletter');
        $commandTester = new CommandTester($command);
        $commandTester->execute(array(
            'command' => $command->getName()
        ));

        $output = $commandTester->getDisplay();
        $this->assertContains('done',$output);
    }
}

I follow this step by step but in my case i get :
Error: Call to a member function writeln() on string

MyBundle/Command/MyCommand.php:197
vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:262
vendor/symfony/symfony/src/Symfony/Component/Console/Tester/CommandTester.php:84
MyBundle/Command/MyCommandTest.php:34

It seems like commandTester don't put correct parameter in execute method from MyCommand.
I'm wondering if it's not CommandTesterClass issue.
That's why i'm here, to share with you that and find some solution together.
Thank you in advance

A:

Method 'getDisplay()' returns a string as you can see from the Api doc:
http://api.symfony.com/3.0/Symfony/Component/Console/Tester/CommandTester.html and you're assigning that string to your $output variable.
I think what you need is 'getOutput()'


Q:

Replacing all char's in String, except for whitespaces

I'm trying to replace all char's in a String with "-", except for the whitespaces.
"This is a test" should become "---- -- - ----" and "Test" should become "----"

It's probably a simple REGEX, but i'm not able to see how to do it, regex is not my strong suit.

A:

You can use:
String repl = input.replaceAll("[^ ]", "-");

OR:
String repl = input.replaceAll("\\S", "-");

Here \\S will anything but a white-space whereas [^ ] will match anything but a space.


Q:

Thymeleaf's layout:fragment not working after packaged in jar

So, I am writing a Spring boot app with Thymeleaf as my template engine.
When I run my project through Spring Tool Suite, everything works as it should.
However, when i run mvn clean package and run jar that is generated, my layout:fragment stops working, saying it cannot resolve it:

org.thymeleaf.exceptions.TemplateInputException: Error resolving
  template "Layout", template might not exist or might no t be
  accessible by any of the configured Template Resolvers (index)

My layout.html:
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org">

    <head>
        <title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE" >my Site</title>
        <meta charset="UTF-8"/>
    </head>
    <body onload="init()">
        <header>
            <nav class="navbar navbar-inverse">
                <!-- Navigation bar -->
            </nav>
        </header>
        <section layout:fragment="vsebina" style="padding: 25px;"></section>
    </body>
</html>

and my index.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        layout:decorate="~{layout}"
        layout:decorator="Layout">

    <head>
        <title>Index</title>
    </head>
    <body>
        <section layout:fragment="vsebina">
            ...
            Content of my index page
            ...
        </section>
    </body>
</html>

and my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mypackage</groupId>
    <artifactId>mySite</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>mySite</name>
    <description></description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml -->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.21</version><!--$NO-MVN-MAN-VER$ -->
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

It seems odd that in one case it works and in another it doesn't. Or am I doing something wrong?

A:

Apparently the problem was in html tag:
<html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        layout:decorate="~{layout}"
        layout:decorator="Layout">

This was needed to change into this:
<html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        layout:decorate="~{layout}"
        layout:decorator="layout">

layout:decorator="Layout" to layout:decorator="layout"
In Spring Tool Suite the capital L didn't caused problems, but when the app was packaged into jar, it started to cause problems.


Q:

Failed installing pyaudio on Google Colab with "ERROR: Failed building wheel for pyaudio"

Trying to install pyaudio on Google Colab but got an error "ERROR: Failed building wheel for pyaudio".
!apt install libasound2-dev portaudio19-dev libportaudio2 libportaudiocpp0 ffmpeg libav-tools
!pip install pyaudio

I got this error:
Collecting pyaudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Building wheels for collected packages: pyaudio
  Building wheel for pyaudio (setup.py) ... error
  ERROR: Failed building wheel for pyaudio
  Running setup.py clean for pyaudio
Failed to build pyaudio
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
ERROR: Command "/usr/bin/python3 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-000dzv_9/pyaudio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-tvs_aja7/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-000dzv_9/pyaudio/

A:

I just need to remove libav-tools from apt install and run this command again.
!apt install libasound2-dev portaudio19-dev libportaudio2 libportaudiocpp0 ffmpeg

Now pyaudio is installed successfully.


Q:

Non-Galois number fields extension of prime degree

Let $E/F$ be an extension of number fields of degree $p$ prime which I know to be NON-Galois. By the fundamental theorem of Galois Theory, I can say that $|\operatorname{Aut}(E/F)|<p$, but can I say more about $|\operatorname{Aut}(E/F)|$?
Thank you in advance to whoever will help me.

A:

How about this argument:
Your set of automorphisms is a group, and its fixed field $k$ not only satisfies $F\subset k\subset E$, but also has $\vert\text{Aut}(E/F)|=[E:k]$. That’s the theorem that when you have a finite group of automorphisms of a field, the order of the group is the degree of the big field over the fixed field. Since $[E:k]=1$ necessarily, your automorphism group is trivial.


Q:

configure Logger via global config file

I'd like to have 1 configuration file that contains information about how/where/what logger in particular class should log.
Example:
class Foo
package myApp;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

class Foo {
    static final Logger logger = Logger.getLogger(Foo.class.getName());

    public static void main(String[] args) throws IOException {

        FileInputStream fis =  new FileInputStream("C:\\path\\to\\myApp.log.properties");
        LogManager.getLogManager(). readConfiguration(fis);

        logger.log(Level.INFO, "Msg message");

        Bar obj = new Bar();

        obj.doSth();
}

class Bar
package myApp;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Bar {

    static final Logger logger = Logger.getLogger(Bar.class.getName());

    public Bar() {
    }

    public void doSth() {
        logger.log(Level.WARNING, "Msg message");
    }
}

File myApp.log.properties
handlers =
config   =

myApp.Foo.handlers           = java.util.logging.ConsoleHandler
myApp.Foo.useParentHandlers  = false
myApp.Foo.level              = INFO

myApp.Bar.handlers           = java.util.logging.ConsoleHandler
myApp.Bar.useParentHandlers  = false
myApp.Bar.level              = INFO

Output:
Jul 23, 2014 1:27:12 PM myApp.Bar doSth
WARNING: Msg message

As you can see, the log record for Foo is missing, i guess it's  because logger is static and is created before configuration for LogManager is loaded and set.
Could you please suggest solution where log record is printed for Foo's logger? Also with a static logger and without using commandline parameter -D configFile when the program is executed?

A:

In your example, LogingToFile.doSth is called instead of Bar.doSth.  Modify your config file to include:
myApp.LogingToFile.handlers           = java.util.logging.ConsoleHandler
myApp.LogingToFile.useParentHandlers  = false
myApp.LogingToFile.level              = INFO

Or add new Bar().doSth(); to your main method.
Reading through the LogManager source code it appears that Handlers are only loaded when the logger is created after the configuration is set.  This is bug JDK-8033661
readConfiguration does not cleanly reinitialize the logging system.  The listed workarounds are:

Do not use per-logger handlers in your log configuration file
Do not call readConfiguration() or readConfiguration(InputStream), but store the configuration in a file and load it on JVM startup
Configure your logging through API calls

Given your constraints, the workaround will be to load the configuration before creating the loggers.
class Foo {

    static {
        try (FileInputStream fis = new FileInputStream("C:\\path\\to\\myApp.log.properties")) {
            LogManager.getLogManager().readConfiguration(fis);
        } catch (IOException ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    static final Logger logger = Logger.getLogger(Foo.class.getName());

    public static void main(String[] args) throws IOException {
        logger.log(Level.INFO, "Msg message");

        Bar obj = new Bar();

        obj.doSth();
    }
}


Q:

Hibernate: Multiple select queries made by Hibernate for Fetch mode Eager

I have just started using Hibernate in my application. Also I'm using JPA repository for using custom query. I have multiple entities which have relationships between them. I have used Fetch mode as 'EAGER' on the join column and also using Cache. I observed that Hibernate is making multiple select queries to fetch each entity and not doing it in a single query.
Below is an entity:
@Entity
@Table(name = "entity_a")
public class EntityA implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    ...

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "entity_a")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<EntityB> entityB = new HashSet<>();

I'm fetching my entity as below, using JPA custom queries:
EntityA entityA = entityARepository.findOneById(id);

Hibernate issues a select query for the above statement.
Whenever I do a entityA.getEntityB() it issues another select statement on EntityB. How to avoid this. How can I get both entities in a single select using Hibernate?

A:

Does EntityB contain a field named entity_a? The name should be exactly as declared in the mappedBy attribute.
In general, JPA providers are required to honor the FetchType.EAGER mode. This seems to be a misconfiguration issue. Even so, while the JPA provider is required to load eager associations eagerly, there is no guarantee it will be done in a single query. There is a Hibernate-specific annotation that can be used as a hint: @Fetch(FetchMode.JOIN). Try it out and see if it works.


Q:

Принципы SOLID доступным языком на ПРОСТЫХ примерах кода С#

Всюду где я смотрел, все написано слишком сложно для понимания. И я решил сам написать простое для понимания описания принципов SOLID вместе с примерами. А заодно и детальнее разобраться с ними.
Если у кого-то при прочтении возникнут уточнения/критика/предложения по улучшению, то прошу писать в коментарии или отдельным ответом. Ну, или же, напрямую править мой ответ.
Моя основная цель вопроса/ответа именно в том, что бы написать максимально доступном для людей любого уровня:

С максимально простыми и короткими примерами. (всегда всем влом разбираться в куче чужого кода)
С минимальным количеством терминологии. Максимально простым языком.

Ясно что статей по теме - море. Но простых для понимания и с короткими листингами кода МАЛО.
Лично я не нашел ни одной.

A:

SOLID - это принципы ООП. Важно понимать, что это рекомендации, но никак не догмы. Применять НЕ обязательно. Так же нужно понимать, что иногда следование одному из принципов может нарушать другой принцип.
Следствие применения принципов:

Больше кода
Но зато этот код будет легче дорабатывать и тестировать(если правильно применить)

Есть еще принцип YAGNI - You Aint Gonna Need It (Тебе это не нужно). Идея в том, что если у тебя на данную секунду нету обьективных причин применять какой-то принцип или паттерн здесь, то его применять не нужно вообще. На примере SOLID: если тебе не нужно дорабатывать и развивать код в будущем(проэкт на 1 вечер, например) -- пиши код проще и без применения SOLID. Попытка создать гибкое решение на ранних стадиях разработки очень часто является созданием переусложненного решения.
Вернемся к нашим овцам:
SOLID - это аббревиатура:

SRP : Single responsibility principle - "У класса должна быть только одна причина для изменения"
OCP : Open/Closed principle - Программные сущности(классы, модули, функции и т.п.)  должны быть открытыми для расширения, но закрытыми для модификации.
LSP : Liskov substitution principle - возможность вместо базового типа подставить любой его подтип.
ISP : Interface segregation principle - Принцип разделения интерфейсов
DIP : Dependency inversion principle - Инверсия зависимостей (Зависеть нужно от абстракций)

Постараемся выяснить и понять их на примерах языка c#.
Я буду идти НЕ ПО ПОРЯДКУ.

Single responsibility. - "У класса должна быть только одна причина для изменения". Звучит очень расплывчасто, да?
PS: "Принцип единой обязанности/ответственности" совсем звучит неинтуитивно, поэтому советую так не запоминать.
Причины для изменения логики работы класса:

Изменение отношений между классами
Введение новых требований или отмена старых.

Суть этого принципа заключается в том, что функционал класса должен быть целостным, обладать высокой логической связностью. Если у класса много ответвенности(много функций "из разных сфер"), то и меняться он будет очень часто. Таким образом, если класс имеет больше одной ответственности, то это ведет к хрупкости дизайна и ошибкам в неожиданных местах при изменениях кода. Любой сложный класс должен быть разбит на несколько простых составляющих, отвечающих за определенный аспект поведения.
Возьмем за пример Bird. Есть птицы, которые  умеют летать, а есть те, которые НЕ летают. Будет странным, если мы создадим экземпляр Страуса или Киви, которые смогут летать. То есть вместо класса
public class Bird
{
    public void Fly() { }
}

У нас должны быть 3 класса:
public class Bird
{
     public void Jump() { }
}

public class BirdFlying: Bird
{
     public void Fly() { }
}

public class BirdNonFlying: Bird
{
    public void Run() {}
}

Нюансы применения:

Объединение ответственностей является общепринятой практикой и в этом нет ничего плохого, до тех пор пока это легко обслуживать. То есть не нужно фанатично дробить классы -- это усложняет работу с проэктом точно так же, как и НЕ применение этого принципа.
Если у вы делаете игру и у вас только летающие птицы, то, конечно же, не имеет смысла делать подобное дробление как в примере.
Если размер вашего класса начинает разбухать, то стоит подумать а не нужно ли разделить этот класс на несколько классов.
класс решает задачи разных уровней абстракции (например разбирает json-объект и анализирует его содержимое) - явный признак что это идет не по принципу.
интерфейс класса слишком разнороден и содержит методы, отвечающие за слабосвязанные логически операции.
класс или интерфейс содержит несколько методов со схожей семантикой, которые используются разными клиентами

Interface segregation - это предоставление каждому клиенту минимального (в идеале - отдельного!) интерфейса.
Рассмотрим код:
interface IMachine
{
    public bool print(List<Item> item);
    public bool staple(List<Item> item);
    public bool fax(List<Item> item);
    public bool scan(List<Item> item);
    public bool photoCopy(List<Item> item);
}

class Machine : IMachine
{
   public bool print(List<Item> item){} //Печатает все документы

   public bool staple(List<Item> item){} //Скрепляет степлером

   public bool fax(List<Item> item) {} //Отправляет факсом документы

   public bool scan(List<Item> item) {} //Сканирует документы

   public bool photoCopy(List<Item> item) //Делает копии документов
}

Проблемы кода:

Перекомпилирование всего кода, даже, при маленьком изменении.
Клиент получит доступ ко многим "левым" методам, даже, если он заинтересован только в печати(например)

По принципу ISP нам нужно разделить один интерфейс на несколько: IPrinter , IStaple , IFax , IScan , IPhotoCopy
И, раз уж, у нас есть универсальная машина которая имплементирует все перечисленные, то создать под нее интерфейс, который унаследуется от них.
interface IMachine : IPrinter, IFax, IScan, IPhotoCopy,IStaple
{
    public bool print(List<Item> item);
    public bool staple(List<Item> item);
    public bool fax(List<Item> item);
    public bool scan(List<Item> item);
    public bool photoCopy(List<Item> item);
}

А так же добавить конструктор класса в Machine
public  Machine(IPrinter printer, IFax fax, IScan scan, IPhotoCopy photoCopy, IStaple staple)
{
    this.Printer = printer;
    this.fax = fax;
    this.scan = scan;
    this.photoCopy = photocopy;
    this.staple = staple;
}

Тогда создание такой универсальной машины будет таким:
var allOneClient  = new Machine(
                        new Printer(),
                        new Fax(),
                        new Scanner(),
                        new PhotoCopy(),
                        new Staple() );

Реализуя так, мы получаем следующие преимущества:

Клиент имеет доступ исключительно к тем методам, которые нужны клиенту. Про другие он не знает.
При повторном компилировании проэкта будут перекомпилированы лишь те блоки, в которых были изменения.

Open/Closed - Программные сущности  должны быть открытыми для расширения, но закрытыми для модификации.
Что это значит?
Закрытыми для модификации означает: единственная причина, по которой вы можете менять код класса\функции\модуля - это непосредственно изменение заложенной в него функции или фикс ошибок работы этой функции. Других причин быть не может.
Открыты для расширения означает: если вам надо, чтобы ваш класс\функция\модуль могли выполнять заложенные функции в новом окружении - они должны это поддерживать без изменения их кода.
Допустим, у нас есть класс для сортировки массива
public class BubbleSorter
{
    public void Sort(int[] data)
    {
        int n = data.Length;
        for (int i = 0; i < n - 1; i++)
            for (int j = 0; j < n - i - 1; j++)
                if (data[j] > data[j + 1])
                {
                    int temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
    }
}

Этот метод умеет сортировать только целые числа.
Если наша программа уже сейчас нуждается в таком же методе но не только для целых чисел(или будет нуждатся в будущем наверняка) -- это и есть наша точка расширения.
Мы используем существующие в дотнете интерфейсы и перепишем немного код:
public class BubbleSorter<T>
{
    IComparer<T> _comparer;

    public BubbleSorter(IComparer<T> comparer)
    {
        _comparer = comparer;
    }

    public void Sort(T[] data)
    {
        int n = data.Length;
        for (int i = 0; i < n - 1; i++)
            for (int j = 0; j < n - i - 1; j++)
                if (_comparer.Compare(data[j], data[j + 1]) > 0)
                {
                    var temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
    }
}

Этими изменениями мы добились многого, а именно:

Все что можно сортировать мы можем сортировать через наш метод: целые числа, числа с плавающей точкой, строки.
если нужно сортировать по убыванию, а не возрастанию, нам не нужно менять код сортировщика или создавать такую же функцию для обратной сортировки.

Нюансы применения:

Слишком усердное применение принципа так же плохо сказывается на результате как и не применение принципа. Слишком абстрактный и универсальный код будет слишком плохим для разбора вами или другими людьми и создает слишком большое число уровней абстракции, в котором сложно разобраться.
Даный пример написан из предположения, что не нужно будет сортировать другие данные окроме массивов в даном проэкте.
Даный пример написан умышленно для изменения оригинального массива данных. То есть все изменения делаются в оригинальном обьекте массива. Не нужно реализовать то, что нам лишь теоретически может потребоваться.

Второй пример применения принципа: Через наследование.
Есть у нас класс, который обрабатывает CSV (Comma Separated Value). То есть пишет таблицу в текстовый файл где кома - это разделитель ячеек в строке, а переход на новую строку это новая строка таблицы [вообще там все сложнее, но это для простоты понимания]
Если вдруг нам понадобится такой же класс, но который еще и заголовки столбцов пишет, то нам нужно будет просто унаследоваться от этого класса, а не изменять базовый.
public class Csv
{
    //Some methods
}

public class CsvWithHeader: Csv
{
    //header realization
}

Этот кусок написан на основе ответа Что такое принцип открытости и закрытости?
Если интересно, там есть еще третий пример применения даного принципа через применение Декоратора.

Liskov substitution - идея реализации "ПРАВИЛЬНОГО" полиморфизма. То есть нужно реализовать наследование подтипов так, что бы была возможность вместо базового типа подставить любой его подтип.
Иногда это сложно сделать. Рассмотрим сложность реализации подобного на примере:
public interface IDuck
{
   void Swim();
   // contract says that IsSwimming should be true if Swim has been called.
   bool IsSwimming { get; }
}
public class OrganicDuck : IDuck
{
   public void Swim() { }
   bool IsSwimming { get{}}
}
public class ElectricDuck : IDuck
{
   bool _isSwimming;

   public void Swim()
   {
      if (!IsTurnedOn)
        return;

      _isSwimming = true;
      //swim logic
   }

   bool IsSwimming { get { return _isSwimming; } }
}

Допустим у нас есть некий метод, который должен что-то делать с утками. Не важно что. public void DoSomethingWithDuck(IDuck: duck) {}.
Здесь сложность применения принципа лежит в том, что электрическая утка может поплыть только в том случае, если она включена. То есть, если мы в этот метод засунем ВЫКЛЮЧЕННУЮ электрическую утку и вызовем duck.Swim(); то она не сможет поплыть. То есть в даном случае LSP соблюдается только при первом взгляде, но на практике этот принцип не соблюдается.
Конечно, это можно пофиксить костылем внутри этого метода в виде:
if (duck is ElectricDuck)
{
    ((ElectricDuck)duck).TurnOn();
}
duck.Swim();

Но это будет именно костылем.
Правильное решение при котором будет слюблюдаться принцип - изменить электрическую утку таким образом, что бы она включалась автоматически при вызове метода .Swim();.
Второй способ - не делать электрическую утку "родственником" органической вовсе.

Dependency inversion. Всюду этот принцип обьясняется как "Модули верхнего уровня не должны зависеть от модулей нижнего уровня. И те и другие должны зависеть от абстракций".  Как по мне, то эту фразу понять довольно сложно. Что же это означает на практике?
Обратимся к автору принципа (Боб Мартин), и коротко он говорит "Зависеть нужно от абстракций, а не от чего-то конкретного". Применяя этот принцип, одни модули можно легко заменять другими, всего лишь меняя модуль зависимости, и тогда никакие перемены в низкоуровневом модуле не повлияют на высокоуровневый.

Не должно быть переменных, в которых хранятся ссылки на конкретные классы.
Не должно быть классов, производных от конкретных классов.
Не должно быть методов, переопределяющих метод, реализованный в одном из базовых классов.
Но при этом вполне нормальная зависимость от "родных" классов языка. То есть зависимость от String вполне нормальное явление. Если же мы пишем классы сами, то они могут быть изменчивыми. Именно от таких классов мы и не хотим зависеть напрямую.

На примере это может выглядеть следующим образом:
public class MySQLConnection
{
   public bool Connect()
   {
         //Коннектимся к MYSQL бд
   }
}

public class PasswordReminder
{
    private MySQLConnection _dbConnection;

    public void PasswordReminder (MySQLConnection dbConnection)
    {
        _dbConnection = dbConnection;
    }
}

Класс PasswordReminder зависит от MySQLConnection. Но более высокуровневый PasswordReminder не должен зависеть от более низкуровневого модуля MySQLConnection.
Если нам нужно изменить подключение с MySQLConnection на MongoDBConnection, то придётся менять прописанное в коде внедрение конструктора в класс PasswordReminder.
Класс PasswordReminder должен зависеть от абстракций, а не от чего-то конкретного. Но как это сделать?
public interface IDbConnection
{
    public Connect();
}

public class DbConnection: IDbConnection
{
    public bool Connect()
    {
        //Коннектимся к MYSQL бд
    }
}

public class PasswordReminder
{
    private IDbConnection _dbConnection;

    public void PasswordReminder (IDbConnection dbConnection)
    {
        _dbConnection = dbConnection;
    }
}

Как следствие этих изменений PasswordReminder() зависит только от абстракции. Мы можем приконектится к MongoDB вместо MYSQL изменением всего одного метода -- Connect() Или же создать MongoDBConnection и унаследовать от IDbConnection;


Q:

Why do we need *.lib files?

I don't seem to understand the need of *.lib files. Let's say I have 3 *.c files:
module1.c
module2.c
module3.c
myheaders.c

In each .c file we have 2 functions. Now if I call function x in module3.c from module1.c, module1.c knows about function x by looking in myheaders.c.
So if I compile this in VS I get a shiny little portable *.exe with no *.lib file attached, so why and when does one need *.lib files?

A:

*.lib files are for other programmers who want to use your functions in their own programs.
*.exe files are for end users who just want to run your program.

A:

Libraries can be made from groups of related functions that have been tested.  They allow you to reuse code without having to go through the compilation stage each time.
Dynamic or Shared libraries allow you to upgrade parts of your executable without recompiling the executable or altering it.
In larger projects, validation of a program is a large portion of the schedule.  Libraries that have already been tested will shorten the schedule and make everybody happy.


Q:

How were windows originally conceived?

I am aware of the common types of windows, (Hamming, Hanning, Kaiser, Tukey, etc etc). However while many books describe them - almost none tell me just how exactly they were derived.
What is so holy about the hamming window? What about the hanning? I understand that they all play on the ratio of mainlobe width VS sidelobe attenuation, but how exactly were they derived?
The motivation for my question, is because I am trying to figure out if one can design their own windows, that also play off main lobe width and sidelobe energy.

A:

This is only a partial answer, but there's a lecture online where Hamming talks about how he came up with his eponymous window. Starting at roughly 15:15 gives the full context.
With a reasonably entertaining story, he credits John Tukey with inventing the theory of windows (for spectrum analysis). However, he introduces the whole subject in the context of using Lanczos sigma factors to reduce Gibbs phenomenon. In addition, in The Art of Doing Science and Engineering (based on the same lectures), he describes how his window is a variation on the Hann window, which he claims was used by von Hann in economics (long before its application in signal processing). That suggests the history goes much further back, depending on how you want to define it.
The book where Tukey first named the Hamming window is The Measurement of Power Spectra from the Point of View of Communications Engineering. Given Hamming's assertion that Tukey invented the theory of windows, it would probably be a good place to start for a deeper understanding of how to design new ones. I think the book is just a reprint of Part I and Part II of his Bell System Technical Journal article, so it's available online.

A:

Here is another partial answer, mostly about designing custom windows. I came up with this while doing something that (as I know now but didn't then) is called "windowing in the frequency domain." Then, after reading some original papers on windowing, I figured that it was probably the way that some windows were conceived in the first place, but I don't have any real background knowledge.
Start with a rectangular window and look at its Fourier transform, the sinc function:

Now, scale and (frequency-)shift two of them so the sides lobes tend to cancel each other out when added together:

(Result in green; sorry for the bad quality and useless legend.)
As you can see, side lobes are not only reduced in general, they also roll off much more quickly.
With "windowing in the frequency domain," the shifting and scaling is closely related to what actually happens in practice. But you are probably more interested in a time-domain representation, which is easy to obtain by applying appropriate formulas for the frequency shifts. It simplifies to $\cos(\pi t)$.
Repeat this process, and you get better and better roll-off, at the cost of a wider main lobe:

This simplifies to $(\cos(\pi t))^2$ in the time domain, which is precisely a Hann window. In general, repeating this $n$ times yields $(\cos(\pi t))^n$. $n=4$ is a special case of a Blackman window, and all even $n$ belong to the Blackman-Harris family.
Among Blackman-Harris windows, these yield the fastest side lobe roll-off. (I started writing down a proof of this, but didn't even finish it because how to calculate roll-off and other parameters seems to be common knowledge among experts.)
If you want to optimize something else than roll-off, you can start with a window that has sufficient roll-off, then do something similar to the above, but scale and shift in a different way (usually using three terms instead of two). This will keep the roll-off exactly the same, but it allows you to reduce the first side lobes, for example.
Hope this helps. Have fun.

A:

Most well-known windows were designed in a more or less ad-hoc way, based on some notion of smoothness in the time-domain. As far as I know there are two windows that are optimal in some sense: The Chebyshev-window which minimizes the maximum sidelobe level (not energy!), and the prolate-spheroidal window, which maximizes the energy ratio between mainlobe and sidelobes. There is an interesting paper about window-design in the frequency domain. It discusses an algorithm which minimizes the sidelobe energy subject to constraints on the maximum sidelobe level, i.e. it is a mix between Chebyshev and prolate-spheroidal window. This is the paper: A new optimal window by J.W. Adams.


Q:

limits involving a piecewise function, Prove that if $c \ne 2$, then f does not have a limit at $x = c$.

$$f(x) = \begin{cases} (x-2)^3 & \text{if $x$ is rational }  \\
(2-x) & \text{if $x$ is irrational }
\end{cases}$$
(i) Prove that if $c \ne 2$, then f does not have a limit at $x = c$.
(ii) Prove that $\lim_{x\to2} f (x)$ exists.
Hi all, i'm not very sure how to approach this question. For part i), i think i'm suppose to find a rational sequence $x_n$ and an irrational sequence $y_n$ such that $x_n \rightarrow c$ & $y_n\rightarrow c$. But $\lim_{n\to \infty}f(x_n) \ne \lim_{n\to \infty}f(y_n)$. Would letting $x_n = \frac{1}{n}$ and $y_n=\frac{1}{\sqrt{n}}$ suffice?
I'm clueless as to how to answer part ii). Would appreciate any hints or advice. Thanks in advance.

A:

For part $(i)$ you're on the right track, but note that we are concerned with $x_n, y_n$ converging to any arbitrary $c$. Note that your $x_n, y_n$ both converge to $0$ (also that $y_n$ is necessarily even a sequence of irrationals - consider $n = 4$). I'm guessing you are to come up with the sequences yourself, and I leave but a hint for you here:

If $c$ is rational consider adding to $c$ some rational sequence that converges to $0$ i.e. find an $a_n$ such that $\{a_n\} \subset \mathbb{Q}$ and $a_n \to 0$.
If $c$ is irrational consider first a sequence of decimal approximations for $x_n$ (that is the $n^{th}$ term of $x_n$ has $n$ decimal places expanded out) and for $y_n$ simply consider adding on the same sequence $a_n$ as above, will $c + a_n$ be irrational always?

Once you have done this then note that you will have $\lim_{n \to \infty} f(x_n) = (c - 2)^3$ and $\lim_{n \to \infty} = (2 - c)$. Now note $f$ is continuous at $c$ iff the limit is the same no matter how you approach it (meaning, no matter what sequence you use to approach $c$). If $c \neq 2$ what do you get above?
As for $(ii)$, we can use the sequential characterization of continuity. That is, $f : \mathbb{R} \to \mathbb{R}$ is continuous at $c$ iff for any $c_n \to c$ we have
$$
\lim_{n \to \infty} f(c_n) = f(c)
$$
Now theres three possible types of sequences when talking about rational and irrational sequences:

Completely rational sequence (all elements of the sequence are themselves rational)
Completely irrational sequence (all elements of the sequence are themselves irrational)
Mixed: Some elements are rational, some are irrational

Now when considering the case of $c = 2$ what is the limit of a completely rational sequence? What about a completely irrational sequence? As for this third category of sequences, the proof really depends on the level of rigor your professor/teacher wants. If you clue me in on how precise you want this to be I can help you out.


Q:

how to group and filter on aggregate in SSRS

I have a requirement to report the number of people who have more than one record in the dataset for my SSRS report and I can't quite get how to filter on the grouping.
So if the dataset results are:
ID     PersonID    FileID
1      1234         abc
2      7890         ade
3      5647         aer
4      1234         xyz

I would like to report 1.  There is one person who has more than 1 record.
Is there an expression or something I can use to do this?
Thank you.

A:

You can use LookupSet and CountDistinct function to get the required count, however you will need the textbox used to show the calculation be in a scope.
If you want to show the number of persons with more than one record as a total in your table use this expression:
=CountDistinct(
IIF(
  LookupSet(
    Fields!PersonID.Value,Fields!PersonID.Value,
    Fields!ID.Value,"DataSetName"
  ).Length>1,Fields!PersonID.Value,Nothing)
)

Set it outside any group scope:

However if you want to show the number of persons with more than one record outside your tablix in a textbox, you can add an additional tablix and delete the necessary rows and columns to leave only one textbox then set the dataset property to the dataset name you are using and use the same expression.

It should produce:

Note my dataset has more rows to ilustrate the functionality. In the right side there is only one textbox with the count.
Let me know if this helps.


Q:

Facebook Face Pile Using HTML5 Instead of iFrame

Is it possible to use a Facebook Face Pile pointing to an APP-ID instead of a HREF through the JavaScript API? For example, what would the JavaScript equivalent of the iFrame code:

A:

To show how many friends are using your website/app, just use the HTML5 example generated at https://developers.facebook.com/docs/reference/plugins/facepile/ and then remove the data-href attribute.  Example:

The data-href attribute signifies that you want to show how many people have liked that specific URL instead.


Q:

Ubuntu 15.10 apparently stuck on kernel 3.16.0-38 generic

Yesterday, I have run my Ubuntu partition for the first time in atleast 5 months. I have ran
sudo apt-get update && sudo apt-get dist-upgrade

Which took about 2 hours to run. This morning, I ran the command again, as I normally do. It didn't give me any updates, but once I changed from the MA servers to the US servers, it gave me a few updates. I then ran
uname -r

which gave me the following result:
3.16.0-38-generic

indicating that the kernel did not upgrade to 4.2 or 4.1.
My question is: How do I upgrade the kernel to the following releases?
Thanks!

A:

Please run the command sudo apt-get install linux-generic
This will add the meta-package linux-generic to your list of installed applications, and attempt to bring your kernel to the version specified in the repositories for Ubuntu 15.10


Q:

KeyEvent special Keys (like mute)

I'm currently trying to create a little remote-app for Android to control a MediaPlayer (like Rythmbox) on my PC.
Most media-players understand the special keys on my keyboard (like "play/pause" or "next/previous"). My idea is that the Android App sends a command (like "pause") to the PC. On the PC runs a normal Java-Application which receives this commands and simulates a key-press of this special button.
The advantage would be that you can use this App on all platforms for every player which supports this special keys (and they are on almost every new USB-Keyboard).
I searched the JavaDocs for a constant in the KeyEvent-class, but I can't find any. Does anyone know how to simulate a press of one of those buttons and if this is even possible with Java?
Additional library's are okay with me, too, as long as there is no other solution.
Also, I know i should use a Robot to simulate the key-press and this works for all normal keys on my keyboard. I simply can't find any way to simulate a key press on those special keys.

A:

So, I think it's not possible to do this with pure Java. I tried something else to find out which key-code the special keys have, but this small program only returns 0 for those keys (it works for "normal" keys):
public class GetKeycode implements KeyListener{

    private JFrame f;
    private JLabel feld;

    public GetKeycode(){
        f = new JFrame("GetKeycode");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.addKeyListener(this);
        feld = new JLabel();
        f.add(feld);
        f.pack();
        f.setVisible(true);
    }

    @Override
    public void keyReleased(KeyEvent e) {
        feld.setText(e.getKeyCode()+"");
    }

    public static void main(String[] args) {
        new GetKeycode();
    }

    // Unused:
    @Override public void keyPressed(KeyEvent e) {}
    @Override public void keyTyped(KeyEvent arg0) {}

}

I hope this will be implemented in future versions of the JRE. But at the moment, there seems to be no solution for this.
Thanks for all the answers anyways.


Q:

Annoying SNAPSHOT releases in Grails list-plugin-updates command

Is there a way to tell the Grails list-plugin-updates command to ignore SNAPSHOT releases?
bash-3.2$ grails list-plugin-updates
Plugins with available updates are listed below:
-------------------------------------------------------------
<Plugin>            <Current>         <Available>
resources           1.2.8             1.2.9-SNAPSHOT
remote-pagination   0.4.6             0.4.7
platform-core       1.0.0             1.0.1-SNAPSHOT
mongodb             2.0.1             3.0.1
mail                1.0.5             1.0.6-SNAPSHOT
joda-time           1.4               1.5-SNAPSHOT
hibernate           3.6.10.15         3.6.10.16-SNAPSHOT

There have been many times when a "real" update has been obscured by a SNAPSHOT release, so I still have to check the Grails website to see the current versions.  We are building a production system and almost never want to include a SNAPSHOT release of any plugin.
Documentation:
http://grails.org/doc/latest/ref/Command%20Line/list-plugin-updates.html

A:

Not currently no but it seems like it should be ignoring snapshots so feel free to raise a JIRA issue (and even contribute a fix!)


Q:

How can I prevent a user from browsing to certain web sites in a WebBrowser control?

I have a simple web browser embedded in an application that allows a user to search Wikipedia, and I'm trying to prevent the user from browsing to other websites outside wikipedia (e.g. by clicking an external link the references). Right now, I'm using this simple code:
this.textBoxAddress.Text = this.webBrowser.Url.ToString();
if (this.webBrowser.Url.Host != "en.wikipedia.org")
{
    this.webBrowser.Visible = false;
    this.labelErrorMessage.Visible = true;
}
else
{
    this.webBrowser.Visible = true;
    this.labelErrorMessage.Visible = false;
}

This code works, except the page is already loaded when it's run. If I put this code into the _Navigating event to try to preemptively stop the user before the page is loaded, it fails because the web browser control doesn't update the Url property until after the page is loaded.
The reason I don't like this code is because the page has already loaded when it's called, so any errors in that page (e.g. script errors, which display a popup) show, even though the web page does not.
I've read sources that say not to use the WebBrowser control, for various reasons, but in this case, security isn't a major issue. I also don't need to worry about the end-user doing something, since this application is an in-house application that has literally only one user, and he won't bypass the security.
Disabling all other pages in IE's settings is not a solution either, because this user utilises IE for other surfing, and the intranet sites of this organisation run on IE as well (and those addresses change, so simply allowing all of them would be difficult to anticipate).

A:

Subscribe to the WebBrowser.Navigating event. Check the WebBrowserNavigatingEventArgs.Url property and set WebBrowserNavigatingEventArgs.Cancel=true if it's not wikipedia.


Q:

Quantikz side by side and titles

I have these 3 quantum circuits and want to put the three side by side. Is there a way to do it? I'm using the quantikz package.
Is there also a way to put titles in the circuits?
\begin{quantikz}
& \ctrl{1} & \qw \\
\lstick{$\ket{0}$} & \targ{} & \qw
\end{quantikz}

\begin{quantikz}
& \ctrl{2} & \qw \\
& \ctrl{1} & \qw \\
\lstick{$\ket{0}$} & \targ{} & \qw
\end{quantikz}

\begin{quantikz}
& \gate{X} & \ctrl{2} & \gate{X} & \qw \\
& \gate{X} & \ctrl{1} & \gate{X} & \qw \\
\lstick{$\ket{0}$} & \qw & \targ{} & \gate{X} & \qw
\end{quantikz}

A:

This solution adds titles using tabular.  Unfortunately, tabular objects to the use of & in quantikz, so I had to store them in saveboxes.
It should be noted that one can also put saveboxes inside tikz nodes, in case you want to add titles overlapping the quantikz images.  Not sure what good [remember picture] would do if you can't name components.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{quantikz}

\begin{document}

\begin{figure}
\centering
\sbox0{\begin{quantikz}
& \ctrl{1} & \qw \\
\lstick{$\ket{0}$} & \targ{} & \qw
\end{quantikz}}%
\sbox1{\begin{quantikz}
& \ctrl{2} & \qw \\
& \ctrl{1} & \qw \\
\lstick{$\ket{0}$} & \targ{} & \qw
\end{quantikz}}%
\sbox2{\begin{quantikz}
& \gate{X} & \ctrl{2} & \gate{X} & \qw \\
& \gate{X} & \ctrl{1} & \gate{X} & \qw \\
\lstick{$\ket{0}$} & \qw & \targ{} & \gate{X} & \qw
\end{quantikz}}%
\begin{tabular}{ccc}
Title A & Title B & Title C \\
\usebox0 & \usebox1 & \usebox2
\end{tabular}
\end{figure}

\end{document}


Q:

SVN Checkin Failure(sqlite[S5]: database is locked)

I am facing this issue intermittently when I am trying to check-in files
svn ci -m "commit message" file
Warning: post commit FS processing had error:
sqlite[S5]: database is locked

Some more info
Server side OS --> Centos6.5 and svn version 1.8.5
Client Side OS --> Centos 5.11 and svn version 1.7.7

I already check some forums and these are the suggestion but it doesn't resolve my issue
1: Check server load(Server is fairly idle when I faced this issue..checked load average,IO and memory utilization)
2: There is a longer commit is in progress at that time
3: Both server and client are in same geographic location

As the error is intermittent and I checked svn repo file is there(i.e file checked in properly)so I am not sure what is the issue.Any help is really appreciated.

A:

I believe this is a client side, and not server side error, based on your comments it seems you are using file based svn, so the only database that can be locked is on the client.
Try this
$ cd /my/repository/.svn
$ mv wc.db wc.db.old
$ sqlite3 wc.db.old
sqlite> .backup main wc.db
sqlite> .exit

now you have a new wc.db that should not have any locking errors
If it all works OK, delete wc.db.old
If not you can always
$ mv wc.db.old wc.db

and you will be right back where you stated before I Posted this .....
but it should work ....


Q:

Determine if current user is in Administrators group (Windows/Python)

I want certain functions in my application to only be accessible if the current user is an administrator.
How can I determine if the current user is in the local Administrators group using Python on Windows?

A:

You could try this:
import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()