text:
Q: Lined-paper line spacing, and redefining the math environment (The description is kind of long, questions are at bottom)
I'm currently using a lined-paper style, thus need all the contents to be strictly sticking to the line.
I've changed the \baselineskip, have removed the vertical space of itemized environment using enumitem package, and have made some other adjustments, so for now pure text and most in-line math look just fine. However, the displayed math always break the correct line spacing. I tried the code below, but this isn't really helping.
\abovedisplayshortskip=0pt%
\belowdisplayshortskip=0pt%
\abovedisplayskip=0pt%
\belowdisplayskip=0pt%

To avoid manually fixing using \vspace{} every time, I write a "\protectbox" macro to produce line spacing of integer multiple of \baselineskip, which looks like this:
\RequirePackage{calc}
\makeatletter
\newlength{\@temp@length}
\newlength{\protectboxskip}
\newcommand{\protectbox}[2][0]{% the first parameter is an offset of length, the second is the content
    % measure the height of contents
    \setbox0=\vbox{%
        \abovedisplayshortskip=0pt%
        \belowdisplayshortskip=0pt%
        \abovedisplayskip=0pt%
        \belowdisplayskip=0pt%
        #2}%
    \@temp@length=\ht0 \advance\@temp@length by \dp0%
    % calculate the number of lines needed to place the content
    \setlength{\@temp@length}{\numexpr\@temp@length/1864679\relax cm + #1\baselineskip}%
    \setlength{\protectboxskip}{0.5\@temp@length}%
    \vspace{\protectboxskip}%
    \vspace{-0.3\baselineskip}%
    \par\noindent%
    \begin{minipage}[c][\baselineskip]{\linewidth}%
        \abovedisplayshortskip=0pt%
        \belowdisplayshortskip=0pt%
        \abovedisplayskip=0pt%
        \belowdisplayskip=0pt%
        #2%
    \end{minipage}%
    \vspace{\protectboxskip}%
    \vspace{0.3\baselineskip}%
}
\makeatother

Now I can use \protectbox to surround the math environment, so that texts following it are well positioned on the line.
However, sometimes there're so many equations that I want this to be applied automatically. Thus I redefined the equation and equation* environment as follows:
\RequirePackage{amsmath}
\RequirePackage{environ}
\let\MYequation\equation
\let\endMYequation\endequation
\RenewEnviron{equation}{%
\protectbox[-1]{%
\begin{MYequation}%
    \BODY%
\end{MYequation}}%
}
\makeatletter
\RenewEnviron{equation*}{%
\protectbox[-1]{%
\begin{MYequation}%
    \st@rredtrue \global\@eqnswfalse% this is copied from amsmath.sty
    \BODY%
\end{MYequation}}%
}
\makeatother

These two environments work just fine. However, use of \[ ... \] will produce an error (the .log file says it's an "emergency stop", but there's no detail). I find out that \[ ... \] is defined by
\DeclareRobustCommand{\[}{\begin{equation*}}
\DeclareRobustCommand{\]}{\end{equation*}}

Thus I think it should behave exactly like the equation*, but it's not.
I also tried to redefine the $$ ... $$ since in markdown we usually use this for displayed math and I'm also using the markdown package. The code looks like this:
\catcode`$=\active
\makeatletter
\protected\def${\@ifnextchar$\@doubledollar\@singledollar}
\def\@doubledollar$#1$${\[#1\]}
\def\@singledollar#1${\(#1\)}
\makeatother

However the compiler throws an error
Package tikz: Sorry, some package has redefined the meaning of the math-mode dollar sign. This is incompatible with tikz and its calc library and might cause unrecoverable errors.

Now finally the questions:
1. (The most important) Is there some cleverer way to solve the lined-paper-style alignment problem? I think my solution for alignment is somewhat ugly, but after a lot of searching, I did not find other solutions.
2. Is there some way to integrate the \protectbox into math environments $$ ... $$, \[ ... \], etc?
3. Why does environment* work but \[ ... \] produce errors?

A: As have answered here: my answer to another question, it can be done as follows:
% \protectbox<optional, space ajust>{optional, height}{content}
\newlength{\protectboxskip}
\NewDocumentCommand\protectbox{D<>{0}om}
{
  \IfNoValueTF{#2}%
  {% Height not given
    % measure the height
    \setbox0=\vbox{%
    \abovedisplayshortskip=0pt%
    \belowdisplayshortskip=0pt%
    \abovedisplayskip=0pt%
    \belowdisplayskip=0pt%
    #3}%
    \@temp@length=\ht0 \advance\@temp@length by \dp0%
    % assign the height
    \setlength{\@temp@length}{\numexpr\@temp@length/\baselineskip\relax\baselineskip + #1\baselineskip}%
  }%
  {% Height given
    \setlength{\@temp@length}{#2\baselineskip-\baselineskip}%
  }
  \setlength{\protectboxskip}{0.5\@temp@length}%
  % space above
  \vspace{\parskip}%
  \vspace{\baselineskip}%
  \vspace*{\protectboxskip}%
  \vspace*{-0.2\baselineskip}%
  \vspace{-\parskip}%
  \vspace{-\baselineskip}%
  \par%
  \noindent%
  % the content
  \begin{minipage}[c][\baselineskip]{\linewidth}%
  \abovedisplayshortskip=0pt%
  \belowdisplayshortskip=0pt%
  \abovedisplayskip=0pt%
  \belowdisplayskip=0pt%
  #3%
  \end{minipage}%
  % space after
  \vspace{\protectboxskip}%
  \vspace{0.2\baselineskip}%
}

% Redefine equation and equation*
\let\equation\equation
\let\endequation\endequation
\RenewEnviron{equation}{%
\addtocounter{equation}{-1}
\protectbox<0>{%
\begin{equation}%
  \BODY%
\end{equation}}%
\par\noindent%
}
\RenewEnviron{equation*}{%
\protectbox<0>{%
\addtocounter{equation}{-1}
\begin{equation}%
  \st@rredtrue \global\@eqnswfalse%
  \BODY%
\end{equation}}%
\par\noindent%
}

% Redefine \[...\]
\def\[#1\]{\begin{equation*}#1\end{equation*}}

This isn't perfect, but it does work. The final result is like this:


text:
Q: Myth: Will low light reduce spawn rates? We should all be familiar with high enough light levels being used to completely prevent mobs from spawning in a location, but I am curious if it's a myth that there's any difference in the odds of mobs spawning when there's low enough light to allow spawns as opposed to no light whatsoever.
Let's say, for example, you have a single room, completely closed off from the outside, suspended in an otherwise void world. The walls and ceiling of this room are made of solid stone, but the floor is made entirely of glowstone. A default skeleton spawner block is floating 12 blocks above the floor with its spawn area fully inside the room. You can imagine that since the light is so far down from the spawner that skeletons should still be able to spawn anywhere in the spawn area (since spawner block rules allow things to spawn in midair) but would the spawn rates be better if the floor did not emit light at all?
I have researched this on the Minecraft wiki and found that there is only mention of what prevents the mob spawn, and nothing in the chain of conditions about reducing the mob spawn's odds of success when light exists in low levels. You can find all sorts of mob grinder build videos where the operators run on the assumption that the room ought to be pitch black for best spawn rates, claiming that you should allow no light from your collection room or your redstone wiring to filter into the spawning area. Could this assumption actually be just a myth we need to validate/bust?
Please substantiate your response. Personal experience and hearsay are okay, but good sources/statistics earn best answer.

A: Now I built your example in 1.8 (I'm guessing You're using 1.8) And my results were... interesting.
Now first the mobs did spawn inside this little room as you can see by this image:
Now if you consider that hostile mobs only spawn if the light level is 7 or lower then yes. In theory this is true. BUT, In most cases of me just removing the glowstone and just me standing looking at how many spawn I would say that having no light source helps but it doesn't help a whole lot. I hope you found this helpful for whatever you're doing with this =D

redpajama_set_name: RedPajamaStackExchange


text:
Q: Html que se ve entre corchetes. que es un shortcode? espero vuestra ayuda. Me he encontrado con una web que posee una estructura que no me es nada familiar. Se trata de una supuestamente tabla, pero me es incomprensible e imposible modificarlo. Por favor, ¿Me pueden decir de qué se trata este código para mirar alguna documentación?. Gracias.

A: En Wordpress eso se conoce como shortcode (cuya traducción literal sería código corto  o código abreviado).
Se trata de una API, como lo define la propia documentación, te pongo aquí parte de la documentación traducida, ya que no existe versión en castellano:
La API de shortcode
La API Shortcode es un conjunto simple de funciones para crear códigos abreviados de WordPress para usar en publicaciones y páginas. Por ejemplo, el siguiente shortcode (en el cuerpo de una publicación o página) agregaría una galería de fotos de imágenes adjuntas a esa publicación o página:
[gallery]

La API permite a los desarrolladores de complementos crear tipos especiales de contenido (por ejemplo, formularios, generadores de contenido) que los usuarios pueden adjuntar a ciertas páginas agregando el código abreviado correspondiente en el texto de la página.
La API Shortcode facilita la creación de códigos cortos que admiten atributos como este:
[gallery id="123" size="medium"]

La API maneja todo el análisis complicado, eliminando la necesidad de escribir una expresión regular personalizada para cada shortcode. Se incluyen funciones de ayuda para configurar y recuperar atributos predeterminados. La API admite códigos cortos de cierre automático y de cierre.
Como inicio rápido para aquellos que tienen prisa, he aquí un ejemplo mínimo del código PHP requerido para crear un código corto (shortcode):
//[foobar]
function foobar_func( $atts ){
    return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

Esto creará un shortcode [foobar] que retornará la cadena "foo and bar"
Veamos un ejemplo con atributos:
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
    $a = shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
    ), $atts );

    return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );

Esto crea un código corto [bartag] que admite dos atributos: ["foo" y "bar"]. Ambos atributos son opcionales y tomarán las opciones predeterminadas [foo = "something" bar = "algo más"] si no se proporcionan. El shortcode retornará foo = {el valor del atributo foo}.
Visión general
Los códigos cortos se escriben proporcionando una función de controlador. Los controladores de shortcode son muy similares a los filtros de WordPress: aceptan parámetros (atributos) y devuelven un resultado (la salida de shortcode).
Los nombres de shortcodes deben estar en minúsculas y se pueden usar todas las letras, pero los números y guiones bajos también deberían funcionar bien. Ten cuidado con el uso de guiones (guiones), será mejor que no los uses.
La función add_shortcode se utiliza para registrar un controlador de shortcode. Toma dos parámetros: el nombre del shortcode (la cadena utilizada en el cuerpo de una publicación) y el nombre de la función de devolución de llamada.
Se pasan tres parámetros a la función de devolución de llamada de shortcode. Puedes elegir usar cualquier número de ellos, incluido ninguno.

*

*$atts: una matriz asociativa de atributos o una cadena vacía si no se proporcionan atributos

*$content: el contenido adjunto (si el shortcode se usa en su forma adjunta)

*$tag: la etiqueta de código corto, útil para funciones de devolución de llamada compartidas

La llamada a la API para registrar el controlador de shortcode se vería así:
add_shortcode( 'myshortcode', 'my_shortcode_handler' );

Cuando se muestra the_content, la API de shortcode analizará cualquier shortcode registrado como "[myshortcode]", separará y analizará los atributos y el contenido, si corresponde, y les pasará la función correspondiente del controlador de shortcode. Cualquier cadena devuelta (sin echo) por el controlador de shortcode se insertará en el cuerpo de la publicación en lugar del shortcode mismo.
Los atributos de shortcode se ingresan así:
[myshortcode foo="bar" bar="bing"]

Estos atributos se convertirán en una matriz asociativa como la siguiente, que se pasará a la función del controlador como su parámetro $atts:
array( 'foo' => 'bar', 'bar' => 'bing' )

Las claves de la matriz son los nombres de los atributos; Los valores de la matriz son los valores de atributo correspondientes. Además, la entrada cero ($atts[0]) contendrá la cadena que coincide con la expresión regular de código corto, pero SOLO SI es diferente del nombre de devolución de llamada. Vea la discusión de los atributos, a continuación.
Manejo de atributos
La matriz sin procesar $atts puede incluir cualquier atributo arbitrario especificado por el usuario. (Además, la entrada cero de la matriz puede contener la cadena que fue reconocida por la expresión regular; consulta la nota a continuación).
Para ayudar a establecer los valores predeterminados para los atributos faltantes y eliminar los atributos que tu shortcode no reconoce, la API proporciona una función shortcode_atts().
shortcode_atts() se parece a la función wp_parse_args, pero tiene algunas diferencias importantes. Sus parámetros son:
shortcode_atts( $defaults_array, $atts );

Se requieren ambos parámetros. $defaults_array es una matriz asociativa que especifica los nombres de atributos reconocidos y sus valores predeterminados. $atts es la matriz de atributos sin procesar que se pasa al controlador de shortcode. shortcode_atts() devolverá una matriz normalizada que contiene todas las claves de $defaults_array, completadas con valores de la matriz $atts si está presente. Por ejemplo:
$a = shortcode_atts( array(
    'title' => 'My Title',
    'foo' => 123,
), $atts );

Si $atts contuviera una matriz ('foo' => 456, 'bar' => 'something'), la $a resultante sería matriz ('title' => 'My Title', 'foo' => 456) . El valor de $atts['foo'] sobre-escribe el valor predeterminado de 123. $atts['title'] no está establecido, por lo que se usa el valor predeterminado 'My Title'. No hay ningún elemento 'bar' en la matriz predeterminada, por lo que no se incluye en el resultado.
Los nombres de los atributos siempre se convierten en minúsculas antes de pasarlos a la función de controlador. Los valores permanecen intactos. [myshortcode FOO="BAR"] produce $atts = array ('foo' => 'BAR').
Un código de idioma sugerido para declarar valores predeterminados y analizar atributos en un controlador de código corto es el siguiente:
function my_shortcode_handler( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'attr_1' => 'attribute 1 default',
        'attr_2' => 'attribute 2 default',
        // ...etc
    ), $atts );
}

Esto analizará los atributos, establecerá valores predeterminados, eliminará los atributos no compatibles y almacenará los resultados en una variable de matriz local denominada $a con los atributos como claves: $a['attr_1'], $a['attr_2'] ... En otras palabras, la matriz de valores predeterminados se aproxima a una lista de declaraciones de variables locales.

Ver la documentación oficial para otro tipo de información más avanzado de shortcode...

Creo que con esto ya tienes una idea de la potencialidad de shortcode y cómo funciona.
En el enlace original hay más detalles que deberías leer, sobre todo si vas a trabajar con shortcode (programándolos o modificándolos). Cabe decir que los shortcode no son exclusivos de plugins, puedes programar tus propios shortcodes sin necesidad de ningún plugin. Con que lo registres en functions.php o en el archivo donde se registran las funciones según tu tema o framework, el shortcode funcionará.
En mi sitio los uso mucho, me han servido por ejemplo para automatizar muchísimo contenido o para crear una pasarela entre mis páginas o posts de Wordpress y mi servidor. Con un shortcode te puedes abrir paso a código de servidor con suma facilidad (recuerdo que cuando empecé con WP tuve que instalar un plugin para poder escribir funciones de PHP en mis plantillas Wordpress ... en esa época ignoraba la existencia de shortcode y estoy encantando de haberlos conocido).


text:
Q: Nginx reverse proxy multiple services to multiple ports I learned about Nginx yesterday and to be more accurate I learned for the first time all the topics covered on the following urls:

*

*Initial Server setup with ubuntu 16.04

*How to install and secure mongodb on ubuntu 16.04

*How to add swap space on ubuntu 16.04

*How to backup restore and migrate a mongodb database on ubuntu

*How to install Nginx on ubuntu 16.04

*How to secure nginx with let's encrypt on ubuntu 16.04

*How to install node js on ubuntu 16.04

*How to setup a node js application for production on ubuntu 16.04
But I'm still here...stuck,
Where I am

I'm editing this Nginx config file: /etc/nginx/sites-available/default
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        server_name mysite.mydomain.com;
        ssl_dhparam /etc/ssl/certs/dhparam.pem;

        location / {
                proxy_pass http://localhost:8080;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

    listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/mysite.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/mysite.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
}

My Goal

*

*To have two nodejs http(s??) servers listening on 2 local ports

*Reverse-proxy them to two https ports

*Profit

So to transform this:

http://localhost:8080/ & http://localhost:8181

To this

https://mysite.domain.com/ & https://mysite.domain.com:1337/

Basically I'm trying to setup a parse server alongside with a node webapp
and I don't want the paths to collide so I want them on different public ports.
Sample node webapp server:
const app = express();

app.use(compression());
app.use(express.static(path.resolve(__dirname, '../dist')));
app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname, '../dist/index.html'));
});

app.listen(8181);

Thanks, in advance.


text:
Q: grayt_autoStartup = true, According to http://www.webspellchecker.net/samples/grayt-ckeditor-plugin.html
the statement  CKEDITOR.config.grayt_autoStartup = true; should activate "GrammarAsYouType (GRAYT) for CKEditor 4+" grammer service on the editor
Their demo code did not even show the spelling button on my local test.
The code from http://sdk.ckeditor.com/samples/spellchecker.html did show the spelling options but not grammer.
Tried to add to the config:"grayt_autoStartup = true," like the "scayt_autoStartup: true," works, but then the entire UI was gone and no spell or grammar check.
Any one has a spelling AND grammar working in a local deployment?
Thanks in advance

A: You are right - GRAYT for CKEditor can be started like this:
grayt_autoStartup: true

For adding spelling button to CKEditor UI you need the following:
CKEDITOR.config.toolbar = [{
    name: 'editing',
    items: ['Scayt']
}];

There is no separate button for GRAYT. So you will have button only for SCAYT.

*

*jsfiddle: https://jsfiddle.net/jalners/j4ytgb2v/


text:
Q: how to parse request URL in simple server in Perl which listen to port here is the request URL http://localhost:9009/?comd&user=kkc&mail=kkc@kkc.com
what are the modification need to do in the server perl script.
server-Perl-script
use IO::Socket;
use Net::hostent;       # for OO version of gethostbyaddr
$PORT = 9009;           # pick something not in use
$server = IO::Socket::INET->new( Proto     => 'tcp',
                                 LocalPort => $PORT,
                                 Listen    => SOMAXCONN,
                                 Reuse     => 1);

die "can't setup server" unless $server;
print "[Server $0 accepting clients]\n";
     while ($client = $server->accept())
     {
       $client->autoflush(1);
       print $client "Welcome to $0; type help for command list.\n";
       $hostinfo = gethostbyaddr($client->peeraddr);
       printf "[Connect from %s]\n", $hostinfo ? $hostinfo->name : $client->peerhost;
       print $client "Command? ";
       while ( <$client>) {
         next unless /\S/;       # blank line
            if (/comd/i )        { print  $client `dir`;      }
       } continue {
          print $client "Command? ";
       }
       close $client;
       print "client closed";
     }

A: I assume that your script is not for production, but for homework or testing sometime. There are multiple very efficient web server solutions in/with Perl like Apache with CGIs or mod_perl, HTTP::Server::Simple and PSGI/Plack.
You'll also typically use a framework like Dancer, Mojo or Catalyst which does most of the boring standard stuff for you:
use Dancer;

get '/' => sub {
    return 'Hi there, you just visited host '.request->host.
        ' at port '.request->port.' asking for '.request->uri;
};

Back to your question: Your script is a interactive server while HTTP has a strict request and response structure:

*

*Client connects to server

*Client sends a request

*Server sends a response

You need to remove the interactive part and just wait for the client to start the conversation:
use IO::Socket;
use Net::hostent;       # for OO version of gethostbyaddr
$PORT = 9009;           # pick something not in use
$server = IO::Socket::INET->new( Proto     => 'tcp',
                                 LocalPort => $PORT,
                                 Listen    => SOMAXCONN,
                                 Reuse     => 1);

die "can't setup server" unless $server;
print "[Server $0 accepting clients]\n";
     while ($client = $server->accept())
     {
       $hostinfo = gethostbyaddr($client->peeraddr);

       # Read request up to a empty line
       my $request;
       while ( <$client>) {
         last unless /\S/;
         $request .= $_;
       }

       # Do something with the request

       # Send response
       print $client "Status: 200 OK\r\nContent-type: text/plain\r\n\r\n".$request;

       close $client;
       print "client closed";
     }

The server reads the full request from the client and returns a minimized HTTP header plus the original request.


text:
Q: Order of element in symmetric group with order greater than $2 n$ What is the smallest positive integer $n$ s.t $S_{n}$ has an element of order greater than $2 n$.
By brute force, I have figured out than for $n = 9$, this condition is true.
Is there any other way to figure this out?

A: First, every element in $S_n$ is a product of disjoint cycles. If $a \in S_n$ is an element, $a= c_1 \cdots c_m$ where the $c_1, \ldots, c_m$ are disjoint cycles of length $l_i$ for $1 \leq i \leq m$, then $\mathrm{ord}(a)= lcm(l_i)$.
For obvious reasons, given an $a \in S_n$ as above, we have $\sum_{i=1}^m l_i \leq n$. This now becomes a combinatorical problem:
In $S_2$ we find maximum order $2$, in $S_3$ we find maximum order $3$, in $S_4$ we find maximum order $4$, in $S_5$ we find maximum order $2 \cdot 3=6$, in $S_6$ we find maximum order $6$, in $S_7$ we find maximum order $3 \cdot 4 = 12$, in $S_8$ we find maximum order $5\cdot 3 = 15$, in $S_9$ we find maximum order $4 \cdot 5  = 20 > 18 = 2 \cdot 9$.
An element of order $20$ in $S_9$ is given for example by $(1234)(56789)$.


text:
Q: Visual Studio Code align function parameters on multiple lines If a Javascript (or Typescript) function signature has multiple lines of arguments (can happen easily in Typescript, with longer type names), Visual Studio Code indents like this after I hit return:

I would prefer it line up the arguments, like this:

Is there a setting somewhere to do this automatically, so I don't have to manually indent the code?
(I also want to do this for function calls.)

A: Probably check out some linters if they can do it for you. Search in Extensions for plugins such as eslint or tslint.


text:
Q: Java: Get current Date and Time from Server not System clock In my Java program, I need to create an instance of the current moment in time. I use
Date date = new Date();

This gives me the current date and time as per the host machine's system clock. Is there any way I can get the current date and time from an online server? The world time server perhaps?
I have seen this post and it describes what I want but I'm afraid I need more help than what's provided there.
In a nutshell, I want to get a date and time that is not dependant on the host machine's system clock.
Thanks!

A: You could have a look at the Java NTP Client demo available at
http://www.docjar.com/html/api/examples/ntp/NTPClient.java.html
and some example code that utilizes this client
http://www.docjar.com/html/api/examples/ntp/TimeClient.java.html
It's about 170 lines of well documented java code.

A: Local network
If your machine is connected to a local network, connect to some machine acting as a trustworthy time server. You could write your own such time server.
Network Time Protocol
Or you could use the well-worn Network Time Protocol (NTP) with existing server and client implementations bundled with most any OS. For more on this, see the accepted Answer by aioobe.
Consider placing that time server computer in network's DMZ so as to updates from time servers on the Internet such as the pool.ntp.org project or those provided by the United States federal government (NIST).
Internet
If your machine is connected to the internets, connect to a trustworthy time server. As discussed above, use a custom protocol such as a web service, or use NTP.
This is discussed in the Question, how to make my java app get global time from some online clock.
See also Questions: Java NTP client, and Java client for time server, such as Network Time Protocol (NTP).
Radio Clock
Obtain a radio clock with a USB connection for output of current time  synchronized by a time code transmitted by a radio transmitter connected to a time standard such as an atomic clock. Transmitters are broadcasting in many countries all over the world.
The Meinberg Global company, at least, offers several such devices.

GPS
Similar to the radio clocks above, a receiver of GPS (Global Positioning System) signals might also capture and relay the time signal. Or perhaps GALILEO, GLONASS or other Radionavigation-satellite service.

Sundial
Position a sundial outside a window. Attach a webcam to the computer in question. Position the webcam in the window. Write an app to interpret the time of day from current image of the sundial.

Caveat: This solution does not function in Seattle.

java.time.Clock
To harness any of these suppliers of the current moment, write a subclass of the abstract java.time.Clock class.
You can pass your Clock implementation as an argument to the various java.time methods. For example, Instant.now( clock ).
Instant instant = Instant.now( yourClockGoesHere ) ;

For testing purposes, note the alternate implementations of Clock available statically from Clock itself: fixed, offset, tick, and more.
Avoid the legacy date-time classes from the earliest versions of Java, such as Date & Calendar. These troublesome classes are entirely supplanted by the java.time classes.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A: Normally servers sync their time regulary with online time servers. So your server time should be accurate. If not, contact your admin.
To get e.g. the GMT time, use the Calendar and TimeZone classes.


text:
Q: Update context value after API call I'm using React 16.3 Context API, I'm setting loggedin: bool & user: Object value using context, also using PrivateRoute for logged in user.
Here is a brief code.
// AuthContext JS
import React from "react";

const AuthContext = React.createContext();

class AuthProvider extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isLoggedIn: false,
            user      : null
        };

        this.setAuth = this.setAuth.bind(this);
    };

    setAuth(isLoggedIn = false, userData = null) {
        this.setState({
            isLoggedIn: isLoggedIn,
            user      : userData
        });
    }

    render() {
        return (
            <AuthContext.Provider
                value={ {...this.state, setAuth: this.setAuth} }>
                { this.props.children }
            </AuthContext.Provider>
        );
    }
}

const AuthUser = AuthContext.Consumer;

export {AuthContext, AuthProvider, AuthUser};

function PrivateRoute({component: Component, ...rest}) {
    return (
        <AuthUser>
            {
                ({isLoggedIn}) => (
                    <Route
                        { ...rest }
                        render={ props =>
                            (
                                isLoggedIn ? (
                                    <Component { ...props } />
                                ) : (
                                    <Redirect
                                        to={ {
                                            pathname: "/login",
                                            state   : {from: props.location}
                                        } }
                                    />
                                )
                            )
                        }
                    />
                )
            }
        </AuthUser>
    );
}

// App JS
class App extends Component {
    render() {
        return (
            <HashRouter>
                <AuthProvider>
                    <Switch>
                        <Route exact path="/login" name="Login Page" component={ Login } />
                        <Route exact path="/register" name="Register Page" component={ Register } />
                        <Route exact path="/404" name="Page 404" component={ Page404 } />
                        <Route exact path="/500" name="Page 500" component={ Page500 } />

                        <PrivateRoute path="/" component={ DefaultLayout } />
                    </Switch>
                </AuthProvider>
            </HashRouter>
        );
    }
}

export default App;

// Login JS
class Login extends Component {
    handleSubmit(values) {
        const opts = {
            "email"   : "test@example.com",
            "password": "test123"
        };

        let _this = this;

        fetch("API_URL", {
            method: "post",
            body  : JSON.stringify(opts)
        })
            .then(
                (response) => {
                    return response.json();
                }
            ).then(
            (data) => {
                _this.setState({
                    isAuth: true,
                    user  : data.data.user
                });
                _this.props.history.replace("/dashboard");

            }
        );
    }

    render() {
        console.log(this.state.isAuth);
        return (
            <AuthUser>
                {
                    ({isLoggedIn, setAuth}) =>
                       (
                                    <Redirect to="/dashboard" />
                                ) : (
 // Login Page

                       )
                }
            </AuthUser>
        );
    }
}

How do I update/call setAuth function of consumer
If I call setAuth from render function, it will give warning & loop over setState
Any Help!

A: In the handleSubmit function in the Login file, instead of calling
    this.setState({
        isAuth: true,
        user: data.data.user
    });
you should call the setAuth function provided by the context and update the user auth and data in the context there:
this.context.setAuth(true, data.data.user)

In order to use this.context, you may need to change from using context consumer to contextType:
static contextType = AuthContext

A: You have implement a higher order component that help component consume context value as props.
The following withContextAsProps HOC provides an example:
function withContextAsProps(Context, Component) {
    function WithContextAsProps(prop) {
       return (
         <Context>
          {value => <Component {...value} />}
         </Context>
       );
    }
    const componentName = Component.displayName || Component.name || 'Component';
    const contextName = Context.displayName || Context.name || 'Context';
    WithContextAsProps.displayName = `With${contextName}Context(${componentName})`;
    return WithContextAsProps;
}

In Login component, the HOC can be used to make isAuth and setAuth value from AuthUser context consumer available as props in the Login component.
class Login extends Component {
  handleSubmit = values => {
     //...

    fetch("API_URL", {
        method: "post",
        body  : JSON.stringify(opts)
    })
        .then(response => response.json())
        .then(
          data => {
            this.props.setAuth(true, data.data.user);
            this.props.location.assign("/dashboard");

        }
    );
  }

  render() {
    return this.props.isAuth ?
                      <Redirect to="/dashboard" />
                      :
Login Page
;
  }
}

export default withContextAsProps(AuthUser, Login);


text:
Q: Outlook 2016 - show sent messages in conversation list on the left I use the conversation view so I can keep track of threads, but it's confusing not seeing my own replies in the list. Is there a way to get it to show my replies by default?
I can see my replies if I click a thread and then click the Conversation arrow shaped button. But what I want is to see my replies in the thread list on the left by default.

A: I have the same problem in Outlook 2011 for Mac; I think this configuration is not possible.
As shown in the following links from the MS documentation, it looks like the option exists for the Windows version, but it is not available in the Mac OS X version. As you alluded to, (your own) sent messages appear in in "reading pane" but do not render in the message list.
One workaround is to automatically BCC yourself on everything. Enable this by Outlook menu -> Preferences... -> Email section -> Composing -> Format and account section -> enable "When sending messages, automatically BCC myself." This will have the effect of putting a copy of messages you send into your Inbox, so they will render in the conversation view/pane. I'm not sure if this will result in duplicate messages rendering in the "reading pane" for conversations. I'm personally not willing to do this, but it should/does work.
Until or unless...

*

*I'm missing something, or

*I learn some fancy keyboard shortcut or other UI trick, or

*Give up my convictions and BCC myself on everything (which does render properly),

this interface (and its inconsistency) is unusable. Back to Apple Mail for me.

A: I found the answer!  It involves using the applescript editor to get it to work.
http://joe.blog.freemansoft.com/2016/02/received-and-sent-messages-in-single.html

*

*Run Outlook

*Highlight the Mailbox we are going to include, Inbox or Sent. We want to get this mailbox's folder id.

*Start a Mac Spotlight search

*Enter ~applesoft~ AppleScript Editor and Enter to bring up the applesoft editor.

*Enter the following in the applescript editor and run it
on run {}
tell application "Microsoft Outlook"
get selected folder
end tell
end run

It should return the results of the execution mail folder id 109 of
  application "Microsoft Outlook" Do the same thing for the other
  mailbox.  My mailbox numbers were 109 (Inbox) and 112 (Sent)

*

*Click on the Search field in the upper right hand corner of the Outlook view.

*This will enable the search tab and ribbon

*Select the Search tab

*Make sure you are still have a normal mailbox selected (not a Smart Folder)

*Select "All Mail" in the Ribbon Bar

*Press the Advanced search button in the ribbon

*Select Raw Query from the drop list.

*Enter the following query, replacing 109 and 112 with the mailboxes numbers retrieved above.
com_microsoft_outlook_folderID == 109 || com_microsoft_outlook_folderID == 112

*Press Enter.  The message list should populate with the combined content of the two folders. Conversations in this combined Index/Sent
  folder will include both inbound and outbound messages.

*Press Save Search in the Search ribbon bar and enter the name of your new Smart Folder.

Another helpful link was a list of all the Raw Query keys:
https://gist.github.com/EmilVarona/78ae2aff409922686ebff4cea785aed4
<?xml version="1.0" encoding="UTF-8"?>
<schema version="1.0" xmlns="http://www.apple.com/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.apple.com/metadata file:///System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.framework/Resources/MetadataSchema.xsd">
  <!--
    Compiled from /Applications/Microsoft\ Outlook.app/Contents/Library/Spotlight/Microsoft\ Outlook\ Spotlight\ Importer.mdimporter/Contents/Resources/schema.xml
    with info from http://xensoft.com/search-mac-outlook-2011-mail-with-raw-queries/
  -->
      <types>
        <type name="com.microsoft.outlook15.contact">
            <allattrs>
                kMDItemTitle
                kMDItemPhoneNumbers
                kMDItemEmailAddresses
                kMDItemInstantMessageAddresses
                kMDItemContentModificationDate
                com_microsoft_outlook_recordID
                com_microsoft_outlook_folderID
                com_microsoft_outlook_accountID
                kMDItemCity
                kMDItemStateOrProvince
                kMDItemCountry
                com_microsoft_outlook_flag
                com_microsoft_outlook_nickname
                com_microsoft_outlook_company
                com_microsoft_outlook_department
                com_microsoft_outlook_jobTitle
                com_microsoft_outlook_homeURL
                com_microsoft_outlook_workURL
                com_microsoft_outlook_bloodType
                com_microsoft_outlook_spouse
                com_microsoft_outlook_customFld1
                com_microsoft_outlook_customFld2
                com_microsoft_outlook_customFld3
                com_microsoft_outlook_customFld4
                com_microsoft_outlook_customFld5
                com_microsoft_outlook_customFld6
                com_microsoft_outlook_customFld7
                com_microsoft_outlook_customFld8
                com_microsoft_outlook_homeStreet
                com_microsoft_outlook_homeCity
                com_microsoft_outlook_homeState
                com_microsoft_outlook_homeZip
                com_microsoft_outlook_homeCountry
                com_microsoft_outlook_firstName
                com_microsoft_outlook_lastName
                com_microsoft_outlook_suffix
                com_microsoft_outlook_title
                com_microsoft_outlook_notes
                com_microsoft_outlook_workStreet
                com_microsoft_outlook_workCity
                com_microsoft_outlook_workState
                com_microsoft_outlook_workZip
                com_microsoft_outlook_workCountry
                com_microsoft_outlook_otherStreet
                com_microsoft_outlook_otherCity
                com_microsoft_outlook_otherState
                com_microsoft_outlook_otherZip
                com_microsoft_outlook_otherCountry
                com_microsoft_outlook_interests
                com_microsoft_outlook_japanese
                com_microsoft_outlook_birthday
                com_microsoft_outlook_anniversary
                com_microsoft_outlook_customDate1
                com_microsoft_outlook_customDate2
                com_microsoft_outlook_children
                com_microsoft_outlook_furigana_full_name
                com_microsoft_outlook_firstNameFurigana
                com_microsoft_outlook_lastNameFurigana
                com_microsoft_outlook_companyFurigana
                com_microsoft_outlook_spouseFurigana
                com_microsoft_outlook_childrenFurigana
                com_microsoft_outlook_interests
                com_microsoft_outlook_projects
                com_microsoft_outlook_categories
                com_microsoft_outlook_primaryCategory
                com_microsoft_outlook_flagged
                com_microsoft_outlook_isgroup
                com_microsoft_outlook_hasStartDate
                com_microsoft_outlook_startDate
                com_microsoft_outlook_hasDueDate
                kMDItemDueDate
                com_microsoft_outlook_has_reminder
                com_microsoft_outlook_completed
                com_microsoft_outlook_completedDate
            </allattrs>
            <displayattrs>kMDItemTitle
                kMDItemPhoneNumbers
                kMDItemEmailAddresses
                kMDItemInstantMessageAddresses
                kMDItemContentModificationDate
            </displayattrs>
        </type>
        <type name="com.microsoft.outlook15.event">
            <allattrs>com_microsoft_outlook_has_text_content
                kMDItemTextContent
                kMDItemTitle
                com_microsoft_outlook_recordID
                com_microsoft_outlook_folderID
                com_microsoft_outlook_accountID
                kMDItemCoverage
                kMDItemDueDate
                com_microsoft_outlook_hasStartDate
                com_microsoft_outlook_hasDueDate
                com_microsoft_outlook_startDate
                com_microsoft_outlook_endDate
                kMDItemWhereFroms
                kMDItemComment
                com_microsoft_outlook_timeZone
                com_microsoft_outlook_recurrence
                com_microsoft_outlook_recurring
                com_microsoft_outlook_allDay
                com_microsoft_outlook_has_reminder
                com_microsoft_outlook_freeBusy
                com_microsoft_outlook_free_busy_value
                com_microsoft_outlook_parentRecordID
                kMDItemContactKeywords
                kMDItemKeywords
                kMDItemProjects
                com_microsoft_outlook_projects
                com_microsoft_outlook_categories
                com_microsoft_outlook_primaryCategory
                com_microsoft_outlook_attendees
                com_microsoft_outlook_attendee_emails
            </allattrs>
            <displayattrs>kMDItemTitle
                kMDItemCoverage
                kMDItemDueDate
                kMDItemWhereFroms
           </displayattrs>
        </type>
        <type name="com.microsoft.outlook15.message">
            <allattrs>kMDItemTitle
                com_microsoft_outlook_recordID
                kMDItemContentCreationDate
                com_microsoft_outlook_messageSent
                com_microsoft_outlook_messageReceived
                com_microsoft_outlook_priority
                com_microsoft_outlook_flag
                com_microsoft_outlook_unread
                kMDItemContentModificationDate
                kMDItemCoverage
                kMDItemKeywords
                kMDItemProjects
                com_microsoft_outlook_has_text_content
                kMDItemTextContent
                kMDItemAuthors
                kMDItemRecipients
                com_microsoft_outlook_folderID
                com_microsoft_outlook_junkLikelihood
                com_microsoft_outlook_size
                com_microsoft_outlook_newsAccountID
                com_microsoft_outlook_accountID
                com_microsoft_outlook_repliedTo
                com_microsoft_outlook_forwarded
                com_microsoft_outlook_redirected
                com_microsoft_outlook_toRecipients
                com_microsoft_outlook_toEmailAddresses
                com_microsoft_outlook_ccRecipients
                com_microsoft_outlook_ccEmailAddresses
                com_microsoft_outlook_bccRecipients
                com_microsoft_outlook_bccEmailAddresses
                com_microsoft_outlook_attachments
                com_microsoft_outlook_has_attachments
                com_microsoft_outlook_has_mentioned_me
                com_microsoft_outlook_projects
                com_microsoft_outlook_categories
                com_microsoft_outlook_primaryCategory
                com_microsoft_outlook_flagged
                com_microsoft_outlook_author_email_addresses
                com_microsoft_outlook_recpient_email_addresses
                com_microsoft_outlook_isFromMailingList
                com_microsoft_outlook_hasStartDate
                com_microsoft_outlook_startDate
                com_microsoft_outlook_hasDueDate
                kMDItemDueDate
                com_microsoft_outlook_has_reminder
                com_microsoft_outlook_completed
                com_microsoft_outlook_completedDate
            </allattrs>
            <displayattrs>kMDItemContentCreationDate
                kMDItemAuthors
                kMDItemRecipients
                kMDItemCoverage
                kMDItemContentModificationDate
            </displayattrs>
        </type>
        <type name="com.microsoft.outlook15.note">
            <allattrs>kMDItemTitle
                com_microsoft_outlook_recordID
                kMDItemContentCreationDate
                kMDItemContentModificationDate
                com_microsoft_outlook_has_text_content
                kMDItemTextContent
                kMDItemKeywords
                kMDItemProjects
                com_microsoft_outlook_folderID
                com_microsoft_outlook_accountID
                com_microsoft_outlook_projects
                com_microsoft_outlook_categories
                com_microsoft_outlook_primaryCategory
            </allattrs>
            <displayattrs>kMDItemTitle
                kMDItemContentCreationDate
                kMDItemContentModificationDate
            </displayattrs>
        </type>
        <type name="com.microsoft.outlook15.task">
            <allattrs>com_microsoft_outlook_has_text_content
                kMDItemTextContent
                kMDItemTitle
                com_microsoft_outlook_recordID
                kMDItemContentModificationDate
                kMDItemComment
                com_microsoft_outlook_recurring
                com_microsoft_outlook_recurrence
                com_microsoft_outlook_recurrence_type
                com_microsoft_outlook_priority
                com_microsoft_outlook_folderID
                com_microsoft_outlook_accountID
                kMDItemProjects
                com_microsoft_outlook_projects
                com_microsoft_outlook_categories
                com_microsoft_outlook_primaryCategory
                com_microsoft_outlook_hasStartDate
                com_microsoft_outlook_startDate
                com_microsoft_outlook_hasDueDate
                kMDItemDueDate
                com_microsoft_outlook_has_reminder
                com_microsoft_outlook_completed
                com_microsoft_outlook_completedDate
            </allattrs>
            <displayattrs>kMDItemTitle
                kMDItemDueDate
            </displayattrs>
        </type>
    </types>
</schema>

Hope that helps.
Another related link: http://blog.stevex.net/2011/03/outlook-2011-smart-folder-with-raw-query/
Info on mdl query syntax: https://developer.apple.com/library/archive/documentation/Carbon/Conceptual/SpotlightQuery/Concepts/QueryFormat.html
Value examples that you can make a raw query against.
com_microsoft_outlook_accountID                = 1
com_microsoft_outlook_author_email_addresses   = (
    "*** Email address is removed for privacy ***"
)
com_microsoft_outlook_categories               = (
    98
)
com_microsoft_outlook_completed                = 0
com_microsoft_outlook_flagged                  = 0
com_microsoft_outlook_folderID                 = 108
com_microsoft_outlook_forwarded                = 0
com_microsoft_outlook_has_attachments          = 0
com_microsoft_outlook_has_mentioned_me         = 0
com_microsoft_outlook_has_reminder             = 1
com_microsoft_outlook_has_text_content         = 1
com_microsoft_outlook_hasDueDate               = 0
com_microsoft_outlook_hasStartDate             = 0
com_microsoft_outlook_messageReceived          = 2016-09-01 20:46:56 +0000
com_microsoft_outlook_messageSent              = 2016-09-01 20:46:54 +0000
com_microsoft_outlook_primaryCategory          = 98
com_microsoft_outlook_priority                 = 0
com_microsoft_outlook_recordID                 = 646385
com_microsoft_outlook_recpient_email_addresses = (
    "*** Email address is removed for privacy ***"
)
com_microsoft_outlook_redirected               = 0
com_microsoft_outlook_repliedTo                = 0
com_microsoft_outlook_size                     = 4
com_microsoft_outlook_toEmailAddresses         = (
    "*** Email address is removed for privacy ***"
)
com_microsoft_outlook_toRecipients             = (
    "GUPTA, Sunil"
)
com_microsoft_outlook_unread                   = 1
kMDItemAlternateNames                          = (
    "/Users/i804008/Library/Group Containers/UBF8T346G9.Office/Outlook/Outlook 15 Profiles/Main Profile/Data/Messages/143/8F74F504-DF2B-40C7-8AFE-7AF73D95486D.olk15Message"
)
kMDItemAuthors                               = (
    "Wu, Will"
)
kMDItemContentCreationDate                     = 2016-09-01 20:46:56 +0000
kMDItemContentModificationDate                 = 2016-09-01 20:47:02 +0000
kMDItemContentType                             = "com.microsoft.outlook15.message"
kMDItemContentTypeTree                         = (
    "com.microsoft.outlook15.message",
    "public.email-message",
    "public.message",
    "public.data",
    "public.item"
)
kMDItemDateAdded                               = 2016-09-01 20:47:01 +0000
kMDItemDisplayName                             = "aabbccdd"
kMDItemFSContentChangeDate                     = 2016-09-01 20:47:02 +0000
kMDItemFSCreationDate                          = 2016-09-01 20:47:01 +0000
kMDItemFSCreatorCode                           = ""
kMDItemFSFinderFlags                           = 0
kMDItemFSHasCustomIcon                         = (null)
kMDItemFSInvisible                             = 0
kMDItemFSIsExtensionHidden                     = 0
kMDItemFSIsStationery                          = (null)
kMDItemFSLabel                               = 0
kMDItemFSName                               = "8F74F504-DF2B-40C7-8AFE-7AF73D95486D.olk15Message"
kMDItemFSNodeCount                             = (null)
kMDItemFSOwnerGroupID                          = 1694527156
kMDItemFSOwnerUserID                           = 718023034
kMDItemFSSize                               = 4583
kMDItemFSTypeCode                              = ""
kMDItemKind                               = "olk15_message"
kMDItemLastUsedDate                            = 2016-09-01 20:46:56 +0000
kMDItemLogicalSize                             = 4583
kMDItemPhysicalSize                            = 8192
kMDItemRecipients                              = (
    "GUPTA, Sunil"
)
kMDItemTitle                               = "aabbccdd"
kMDItemUseCount                               = 1
kMDItemUsedDates                               = (
    "2016-09-01 04:00:00 +0000"
kMDItemOwnerUserID                    = 718023034
com_microsoft_outlook_accountID        = 1
com_microsoft_outlook_allDay           = 0

A: I know this answer comes a little bit too late, but I found a quick and dirty workaround, which doesn't really interfere too much with a normal workflow.
Just add yourself as a recipient of your own emails.
Simple as that. You will see your own answers in the conversation mode thread, since you will actually receive these emails. Your name will show as the sender so it's easy to see these are actually sent replies.
Not ideal, but it works and it's a non-intrusive workaround while we wait for Microsoft to fix what I can only describe as an annoying bug

A: I had the same problem with my PC when I upgraded Outlook.  I was able to resolve it by going to File/Account Settings and then changing by default email account, rebooting and then changing it back and rebooting.  All works fine in both Inboxes!

A: Seems to be fixed on Outlook 16.53

A: Try Thunderbird which manage threads the right way since many years ( probably more than 10 )
View > Sort by > Threaded

As a collateral benefit Thunderbird is an open source software thus you can trust it because you can check. I used it at a large scale company ( ~ 3000 users ). Compared with Outlook, Mail, Thunderbird was the one with the less support questions and the less malware attacks ( on a more than 10 years security supervising ). On the other hand the loser was… ; I let you guess it as an easy game .
The future of Thunderbird is unsure, but I am still using it to provide me a common and efficient interface to many web mail servers which are much too slow to work with ( Gmail… ).

A: Try:
File: Options: Mail - check "Enable preview for Rights protected emails"

A: Go to accounts settings and check the box Use Cached Exchange Mode, close outlook and reopen


text:
Q: can not exclude files from input in doxygen I want to generate a file list with gcc -M which delivers something like the following which works fine:
../active_var/timervar.h \
../active_var/universal_var.h \
../chrono_timer/chrono_timer.cpp \
/home/bla/foreign_components/gmock-1.7.0/fused-src/gmock/gmock.h \
/home/bla/foreign_components/gmock-1.7.0/fused-src/gmock-gtest-all.cc \
/home/bla/foreign_components/gmock-1.7.0/fused-src/gmock_main.cc \
/home/bla/foreign_components/gmock-1.7.0/fused-src/gtest/gtest.h \
../../mtp/index_tuple.h \
../observer/observer_with_stop_marker.h \
test_bugfixing.cpp \
test_counter.cpp \

I give this files to the
INPUT = <files as listed above >

This works as expected.
Now I simply want to ignore the files coming from /home/bla/foreign_components/
I tried:
EXCLUDE = */home/bla/foreign_components/*

or
EXCLUDE = /home/bla/foreign_components/

or
EXCLUDE = /home/bla/foreign_components/*

nothing works!
I tried the same with all above listed patterns with the EXCLUDE_PATTERNS
Also no effect.
Is this feature simply broken in doxygen or can files which are explicitly listed in files not be filtered out?
I am using doxygen version: 1.8.10

A:
can files which are explicitly listed in files not be filtered out?

I think so.
You can generate your INPUT list by filtering gcc -M output:
gcc -M | grep -v "/home/bla/foreign_components"


text:
Q: How do I start a Windows GUI App with a GitHub Self-Hosted Action Runner? My action is running fine, but is not starting any GUI application.
Here is the action's code:
name: Python package

on: [push]

jobs:
  build:

    runs-on: self-hosted

    steps:
    - uses: actions/checkout@v2
    - name: Run with python
      run: |
       .\BasementRenovator.py

Is there anything specific about running GUI applications via self-hosted action runners?


text:
Q: Express - get value of path matching string Question
I've got several nested routers, and would like to get access to the whole string that the request's path matched. It's a little hard to say with english, so take a look at this code:
const express = require('express')
const app = express()
const router1 = express.Router()
const router2 = express.Router()

// set up router 2 paths
router2.get('/path2/:param2', (req, res, next) => {
  const someVar = req.something // the value I'll talk about in a second
  return res.status(200).send({ someVar })
})

// set up router1 paths
router1.use('/path1/:param1', router2)

// connect the routers behind a base url
app.use('/api/v1', router1)

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

If I were to make a GET request with:
curl -X GET http://localhost:3000/api/v1/path1/myparam1/path2/myparam2

I want that to return an object like this:
{
  "someVar": "/api/v1/path1/:param1/path2/:param2"
}

Context
I have middleware in my app which logs the path to an elasticsearch cluster, and I'd like the cluster to group paths by the string they used to match the request, rather than the request itself. That way I can get a visual of which request endpoints are being hit the most.

A: // you need to set mergeParams: true on the router,
// if you want to access params from the parent router
var router1 = express.Router({mergeParams: true});


text:
Q: jQuery onClick load page to div doesn't work in browser, but works in Dreamweaver I'm having a problem and I don't know what I'm doing wrong. I have a button (menu link) that I'd like to click to load file content into said div. When I click it in Dreamweaver live view it works without any problem, but it doesn't work in Chrome browser. JS works in Chrome, I've done a test jquery popup window.
jQuery:

HTML:
Test

In Dreamweaver it works like it's supposed to be. On button click it loads przesuniecie.html content into content div.
Thanks for any help


text:
Q: Can I use "whether" instead of "if" in this sentence?
In the past, some experts wondered if Tut died in a chariot crash.

Can I use whether to take the place of "if" in this sentence?

A: The replacement is always tricky! It depends on the context. The meaning may change entirely if we interchange if and whether in all cases. Here is the general rule -

Use whether to show that there are two possible alternatives and use if if you have a conditional sentence.

For example:

In the past, some experts wondered whether Tut died in a chariot crash or from food poisoning.

In that case, we use whether, because the sentences is discussing two alternatives. However, in your case, it's interchangeable.
Useful information here.

A: If expects a yes/no answer and whether expects the answer to be one of two alternatives.
For example:

Experts want to know whether Tut died in a chariot crash or falling from his horse.

They know he died in one of these two ways, and they want to know which.
In other words, the options are

*

*he died in a chariot crash, or

*he died falling from his horse

Experts want to know if Tut died in a chariot crash or falling from his horse.

They want to know whether he died in one of these two ways (not caring which), or whether he died in some other unspecified way.
In other words, the options are

*

*he died in either a chariot crash or falling from his horse, or

*he neither died in a chariot crash nor falling from his horse

More examples:

I asked X if he had a cat or a dog and he told me he did.
  I asked X whether he had a cat or a dog and he told me he had a cat.

In your sentence, because you have only one alternative, you can use either if or whether; they're interchangeable.


text:
Q: Is OpenHardwareMonitor  reliable when used with c# ? What I mean is that I didn't find any other source code for c# of other programs that monitor the hardware on the pc.
I wonder if the values that I am getting from the openHardwareMonitor are relaible enough?
Thanks.

A: Hello you can also try with this code plex library and compare results
http://managedupnp.codeplex.com/

A: there are few people do the things in C#, they use C++, C, or VB.
so if you want to do this, you can try the windows APIs.
by the way, it's easy to call the windows APIs in C#


text:
Q: NetBeans building failure | make Error 1 I get the following errors while building my project (game with C++/SFML):
cd '/home/osboxes/NetBeansProjects/Prueba'
/usr/bin/make -f Makefile CONF=Debug
"/usr/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make[1]: Entering directory '/home/osboxes/NetBeansProjects/Prueba'
"/usr/bin/make"  -f nbproject/Makefile-Debug.mk dist/Debug/GNU-Linux/prueba
make[2]: Entering directory '/home/osboxes/NetBeansProjects/Prueba'
mkdir -p dist/Debug/GNU-Linux
g++     -o dist/Debug/GNU-Linux/prueba build/Debug/GNU-Linux/AABBCollidable.o build/Debug/GNU-Linux/AABBCollisionDetector.o build/Debug/GNU-Linux/AnimatedSprite.o build/Debug/GNU-Linux/Animation.o build/Debug/GNU-Linux/ConvexCollidable.o build/Debug/GNU-Linux/ConvexCollisionDetector.o build/Debug/GNU-Linux/ConvexShape.o build/Debug/GNU-Linux/Director.o build/Debug/GNU-Linux/Entry.o build/Debug/GNU-Linux/Event.o build/Debug/GNU-Linux/EventManager.o build/Debug/GNU-Linux/FileLogger.o build/Debug/GNU-Linux/GuiElement.o build/Debug/GNU-Linux/GuiSystem.o build/Debug/GNU-Linux/Label.o build/Debug/GNU-Linux/LabelButton.o build/Debug/GNU-Linux/ResourceManager.o build/Debug/GNU-Linux/State.o -L/usr/lib/x86_64-linux-gnu -lsfml-window -lsfml-system -lsfml-graphics -lsfml-audio
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function `_start':
collect2: error: ld returned 1 exit status
nbproject/Makefile-Debug.mk:79: recipe for target 'dist/Debug/GNU-Linux/prueba' failed
make[2]: *** [dist/Debug/GNU-Linux/prueba] Error 1
make[2]: Leaving directory '/home/osboxes/NetBeansProjects/Prueba'
nbproject/Makefile-Debug.mk:76: recipe for target '.build-conf' failed
make[1]: *** [.build-conf] Error 2
make[1]: Leaving directory '/home/osboxes/NetBeansProjects/Prueba'
nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 2s)

I have installed NetBeans IDE 8.1 with SFML libraries. I tried to fix it by clearing cache from NetBeans and then restart IDE but still does the same errors.
My project was compiled with Standard C++ compiler (C++11 version).

Hope you could help me. Thanks by the way...


text:
Q: How the constructor is working within another class here is a use of static class object inside another class along with a scope resoution operator now i'm not sure whether the static object or the scope resolution operator is the reason that the constuctor from a different class is also invoked.
the code is:
class A
{
    public:
        A()
        {
            cout<<"A's constructor"<<endl;
        }
};
class B
{
    static A a;
    public:
        B()
        {
            cout<<"B's constructor";
        }
        static A get()
        {
            return a;
        }
};
A B :: a;

thus along with the main part
int main()
{
    B b;

    A a1=b.get();

    A a2=b.get();

    A a3=b.get();

}

And here is the output:
A's constructor
B's constructor

Another query is that whether the get function is actually doing anything?

A: Define one more constructor, the copy constructor, in the class A. For example
A( const A & ) { cout << "A's copy constructor" << endl; }

and you will get the following output
A's constructor
B's constructor
A's copy constructor
A's copy constructor
A's copy constructor

That is the first constructor is called to create the static object of the class A die to its definition
A B :: a;

Then within main there is created an object of the type B. And ion these statements
A a1=b.get();

A a2=b.get();

A a3=b.get();

there are created three object of the type A using the copy constructor.


text:
Q: How to show the error causing the 'There has been a critical error on your website'? I'm getting the error: 'There has been a critical error on your website. Learn more about debugging in WordPress.'.
How do I display which error I'm getting in the frontend?
I have these three lines in my wp-config.php-file:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', true );
define( 'WP_DEBUG_LOG', true );

It surprises me that enabling WP_DEBUG, doesn't show it.
I can (however) still find the errors in /wp-content/debug.log, - but it's just an extra step in development, having to open that file and find the error.
How do I just get the proper error displayed on the page, - and not hid away in that debug.log-file?
I can see that WP_DEBUG is enabled, since this:
echo '<pre>';
print_r( WP_DEBUG);
echo '</pre>';
die();

... returns: 1.

A: Ahh! I found it.
If I did this:
phpinfo();
die();

Then I could see that 'display errors` was set to off.
So if I added this in the top of my functions.php: ini_set('display_errors', 1);, then it started showing the errors.


text:
Q: Calculating Repayment Rate Using Excel Goal: Considering the date of disbursement cohort, I need the month with the lowest repayment rate in 2018 (loans repaid on time)? Using pivot table

id
principal_disbursed
principal_repaid
due_date
repayment_date
credit_officer

1
$334
$334
12/10/2017
17/10/2017
John

2
$184
$184
10/11/2018
20/10/2018
Maria

3
$417
$417
18/08/2017
24/08/2017
Maria

4
$500
$500
04/08/2017
14/07/2017
Maria

5
$250
$250
04/08/2017
06/08/2017
John

6
$250
$250
02/08/2017
24/07/2017
Frank

7
$500
$500
04/08/2017
12/08/2017
John

8
$417
$417
10/08/2017
08/08/2017
Maria

9
$334
$334
05/08/2017
09/08/2017
Frank

10
$500
$500
01/08/2017
05/08/2017
Maria

11
$400
$400
08/08/2017
10/08/2017
Frank

12
$500
$500
10/08/2017
29/07/2017
Frank

13
$500
$500
10/08/2017
14/08/2017
John

14
$500
$500
12/08/2017
30/07/2017
Frank

15
$484
$484
04/08/2017
07/08/2017
Maria

16
$167
$167
13/08/2017
14/08/2017
Frank

17
$334
$334
09/08/2017
22/08/2017
John

18
$450
$450
06/09/2017
05/09/2017
Maria

19
$500
$500
09/09/2017
17/09/2017
Maddy

20
$250
$250
23/08/2017
16/08/2017
John

21
$250
$250
07/09/2017
16/08/2017
Frank

22
$167
$167
10/09/2017
12/09/2017
Maria

23
$500
$500
15/08/2017
17/08/2017
Maria

24
$250
$250
12/08/2017
06/09/2017
Frank

25
$500
$500
13/08/2017
19/08/2017
Maria

26
$250
$250
13/09/2017
21/08/2017
Maria

27
$250
$250
14/09/2017
03/09/2017
Frank

28
$500
$500
16/09/2017
06/09/2017
John


text:
Q: User.Identity.Name is null everytime with MongoDB Token Based auth I created project using Asp.Net Core 2.1 Web API (MongoDB) and used token based authentication. User.Identity.Name is getting null. Also User.Claims is showing "Enumeration yielded no results".
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(config.Value.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
    new Claim(ClaimTypes.Name, UserDtos.Id.ToString()),
    new Claim(JwtRegisteredClaimNames.Sub, user.Id),
        new Claim(JwtRegisteredClaimNames.UniqueName, user.Id),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    }),
    Expires = DateTime.UtcNow.AddDays(7),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
UserDtos.Token = tokenHandler.WriteToken(token);


text:
Q: System.IO.Directory.GetFiles() not retrieving any files in C#? I'm simply trying to retrieve all the files in a certain directory.
if (System.IO.Directory.Exists(dir_path)) //this line passes
{
    //The following files array is empty although there's clearly files
    string[] files = System.IO.Directory.GetFiles(dir_path);
}

Is there a way to copy over all the subdirectories, with all files still in their respective subdirectories when copied over?

A: Based on your comment "The directory has 2 non-empty subdirectories", the Directory.GetFiles(string) overload does not recursively check subdirectories and would not pick up those files.
Instead try using Directory.GetFiles(dir_path, "*", SearchOption.AllDirectories) which will grab files in subdirectories as well.

A: Try to run Visual Studio as an administrator. If the code runs successfully, then there may be some access privileges issue on the folder being accessed.


text:
Q: how can i use the wait_for command to look out for two different reactions in discord.py? I've got a bot which asks users if they are sure they entered the right information, showing them what they entered. I would like them to react with thumbs up for correct, and thumbs down for incorrect, but I can't seem to get the code to look out for both at once. Here's what I have... does anyone know how to do it?
def isUser(reaction, user):
    return user == ctx.author and (str(reaction.emoji) == '' or str(reaction.emoji) == '')

try:
    reaction, user = await bot.wait_for('reaction_add', timeout=60, check=isUser)
except asyncio.TimeoutError:
    await msg.edit(embed=embedEnd)
else:
    for i in msg.reactions:
        if i.emoji == '':
            if i.count > 1:
                await msg.edit(embed=embedFin)
        elif i.emoji == '':
            if i.count > 1:
                await msg.edit(embed=embedEnd)

msg is my bot's message.
embedFin is the embed i want to show when they react with .
embedEnd is the embes i want to show when they react with .
bot is commands.Bot().
let me know if you need more info! thanks :D

A: def isUser(reaction, user):
    return user == ctx.author and (str(reaction.emoji) == '' or str(reaction.emoji) == '')

try:
    reaction, user = await bot.wait_for('reaction_add', timeout=60, check=isUser)
except asyncio.TimeoutError:
    await msg.edit(embed=embedEnd)
else:
    if str(reaction.emoji) == '':
        await msg.edit(embed=embedFin)
    else:
        await msg.edit(embed=embedEnd)


text:
Q: Problems making "at" sign with Spanish keyboard Just did a clean install of Linux on an HP Pavilion that had Windows 10.
My keyboard is set up for Spanish language, but I am having trouble making the "at" sign @ the way I am accustomed to (i.e. Ctrl + Alt + Q).
Other keys seem to work fine (accents, degree symbol, umlauts, Ñ, etc)
Anyone have a solution to this problem, aside from using the unicode method? It is so many keys to press.


text:
Q: Deploying Code and Managing configuration with Terraform Just to give context:

*

*I am planning to use Terraform to bring up new separate environments with ec2 machines, elb etc. and then maintaining configuration as well.
Doing that with terraform and using AWS provider sounds fairly simple.

Problem 1:
While launching those instances I want to install few packages etc. so that when Terraform launches the instances (servers) things/ apps should be up and running.
Assuming the above is up and running:
Problem 2:
How do I deploy new code on the servers in this environment launched by Terraform?
Should I use for eg. ansible playbooks/chef recipes/puppet manifests for that? or Terraform gives some other options/ways?

A: Brief answers:

Problem 1: While launching those instances I want to install few packages etc. so that when Terraform launches the instances (servers) things/ apps should be up and running.

A couple of options:

*

*Create an AMI of your instance with the installed packages and specify that in the resource.

*Use the user data script to install the packages that you need when the instance starts.

*Use ansible playbooks/chef recipes/puppet to install packages once the instance is running (e.g. creating an opsworks stack with terraform)

Problem 2: How do I deploy new code on the servers in this environment
  launched by Terraform? Should I use for eg. ansible playbooks/chef
  recipes/puppet manifests for that? or Terraform gives some other
  options/ways?

Not the intended use case for terraform, use other tools like jenkins or aws services like codepipeline or codedeploy. Ansible/chef/puppet can also help (e.g. with opsworks)


text:
Q: Sprite Kit - Notifier that a node is leaving the screen Is there a event/notification in Sprite Kit that tells me when a node is leaving the screen?
Lets say I want a coloured circle to appear on top when it left the screen at the bottom. Which means I need to know when it is leaving the screen.

A: You will need to check for yourself I think,
- (void)update:(NSTimeInterval)currentTime {

    if (node.position.y > screenHeight+nodeSize){ // need to define first, of course
          // do something like NSLog(); or [removeFromParent] or whatever =)
    }
}

A: Sprite kit does not generate a notification when a sprite leaves screen. You will need to add your own test. Here's an example...
- (void) update:(NSTimerInterval)currentTime
{
    CGPoint newPosition = CGPointMake(node.position.x, node.position.y);

    if (node.position.y > maxY+node.size.y/2) {
        newPosition.y = minY;
    }
    else if (node.position.y < minX-node.size.y/2) {
        newPosition.y = maxY;
    }

    if (node.position.x > maxX+node.size.x/2) {
        newPosition.x = minX;
    }
    else if (node.position.x < minX-node.size.x/2) {
        newPosition.x = maxX;
    }
    node.position = newPosition;


text:
Q: type mismatch in flexboxlayout I am using Google FlexBox in my project. When I set my it to recyclerview I get an error typemismatch.
Here is the code that I have error
    val flexBox = FlexboxLayoutManager(this).apply {
        flexWrap = FlexWrap.WRAP
        flexDirection = FlexDirection.ROW
        alignItems = AlignItems.STRETCH
    }
    mRecyclerViewMyGroups.apply {
        layoutManager = flexBox
        adapter = mMyGroupsAdapter
    }

I get the typemismatch in flexBox in the line layoutManager = flexBox
what is the mistake I have made how to resolve that

A: Try changing your FlexBox version in gradle.build.
From FlexBox's GitHub

Note that starting from 1.1.0, the library is expected to use with AndroidX. Please migrate to AndroidX if you use 1.1.0 or above.
Please use 1.0.0 if you haven't migrated to AndroidX.

I used FlexBox 1.1.0 and encountered the same error, change it to 1.0.0 and the error is gone.

A: just changed the code to the below and it worked,
    val flexlayout = FlexboxLayoutManager(FlexDirection.ROW)
    mRecyclerViewMyGroups.layoutManager = flexlayout


text:
Q: Mongodb cursor method sort /**
 * @param $key
 * @param $value
 * @param $collection
 * @return array | \MongoDB\Driver\Cursor
 */
static function simpleSelect($key, $value, $collection)
{
    $con = \Core\Model\Mongo::getConnect();

    $query = new \MongoDB\Driver\Query(
        array(
            $key => $value
        )
    );

    return $con->executeQuery(\Core\Helper::getDb()['mongodb']['db'] . '.' . $collection, $query);
}

I develop class, for mongodb driver. And I have trouble, how to I can call function sort for mongoDB, for example https://docs.mongodb.com/manual/reference/method/cursor.sort/ in this documentation I read what cursor have sort but in php \MongoDB\Driver\Cursor class don't have sort method...

I fixed this by modified my code
/**
 * @param $key
 * @param $value
 * @param $collection
 * @return array | \MongoDB\Driver\Cursor
 */
static function simpleSelect($key, $value, $collection)
{
    $con = \Core\Model\Mongo::getConnect();

    $query = new \MongoDB\Driver\Query(
        array(
            $key => $value
        ),
        array('sort' => array('time' => -1))
    );

    return $con->executeQuery(\Core\Helper::getDb()['mongodb']['db'] . '.' . $collection, $query);
}

method query have 2 parameters, options this is array can contain sort, ordered and other options for collection. But this is not finish code because I want create new method for set sorting and other option.

A: In PHP the syntax used to sort a Mongodb collection is
// Sort on field x, ascending
$cursor->sort(array('x' => 1));

Your code can be modified to :-
static function simpleSelect($key, $value, $collection)
{
    $con = \Core\Model\Mongo::getConnect();

    $query = new \MongoDB\Driver\Query(
        array(
            $key => $value
        )
    );
    $cursor = $con->executeQuery(\Core\Helper::getDb()['mongodb']['db'] . '.' . $collection, $query);
   $cursor->sort(array('x' => 1));
   return $cursor;
}


text:
Q: Docker : sharing /dev/snd on multiple containers leads to "device or resource busy" When adding host device (--device /dev/snd) to a Docker container, I sometimes encounter Device or resource busy errors.
Example
I have reproduced the issue with a minimal example involving audio (alsa). Here's my Dockerfile (producing an image docker-device-example) :
FROM    debian:buster

RUN     apt-get update \
 &&     apt-get install -y --no-install-recommends \
            alsa-utils \
 &&     rm -rf /var/lib/apt/lists/*

I am running the following command (speaker-test is a tool to generate a tone that can be used to test the speakers), with /dev/snd shared :
docker run --rm \
    -i -t \
    --device /dev/snd \
    docker-device-example \
    speaker-test

Issue
When running the previous command, a pink noise is played, but only under some conditions :

*

*if I am not playing any sound on my host : for example, if I'm playing a video, and that even if the video is paused, the command fails

*if I am not running another container accessing the /dev/snd device

It looks like the /dev/snd is "locked" when used, and if that is the case, I got the following output (the error is represented by the last 2 lines) :
speaker-test 1.1.6

Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
Using 16 octaves of pink noise
ALSA lib pcm_dmix.c:1099:(snd_pcm_dmix_open) unable to open slave
Playback open error: -16,Device or resource busy

And, vice versa, if the pink noise is played (on the container), then I cannot play any sound on my host (Ubuntu). But commands on my host does not fail with the same message. Instead, the command on the host (like aplay test.wav to play a simple sound) is blocked indefinitely (even when the container is shutdown afterwards).
I tried to debug by running strace aplay test.way, and the command seems to be blocked on the poll system call :
poll([{fd=3, events=POLLIN|POLLERR|POLLNVAL}], 1, 4294967295

Question
How can I play sounds from 2 (or more) different containers, or from my host and a container, at the same time?
Additional info
I've reproduced the issue with /dev/snd, but I don't know if similar things happen when using other devices, or if it's just related to sound devices or to alsa.
Note also that when running multiple speaker-test or aplay commands simultaneously and all on my host (no containers involved), then all sounds are played.

A: I can't tell how to solve this with ALSA, but can provide 2 possible ways with pulseaudio. If these setups fail, install pulseaudio in image to make sure dependencies are fullfilled.
ALSA directly accesses sound hardware and blocks access to it for other clients. But it is possible to set up ALSA to serve multiple clients. That has to be answered by someone else. Probably some ALSA dmix plugin setup is the way to go.

*

*Pulseaudio with shared socket:

Create pulseaudio socket:
pactl load-module module-native-protocol-unix socket=/tmp/pulseaudio.socket

Create /tmp/pulseaudio.client.conf for pulseaudio clients:
default-server = unix:/tmp/pulseaudio.socket
# Prevent a server running in the container
autospawn = no
daemon-binary = /bin/true
# Prevent the use of shared memory
enable-shm = false

Share socket and config file with docker and set environment variables PULSE_SERVER and PULSE_COOKIE. Container user must be same as on host:
docker run --rm \
    --env PULSE_SERVER=unix:/tmp/pulseaudio.socket \
    --env PULSE_COOKIE=/tmp/pulseaudio.cookie \
    --volume /tmp/pulseaudio.socket:/tmp/pulseaudio.socket \
    --volume /tmp/pulseaudio.client.conf:/etc/pulse/client.conf \
    --user $(id -u):$(id -g) \
    imagename

The cookie will be created by pulseaudio itself.

*Pulseaudio over TCP:

Get IP address from host:
# either an arbitrary IPv4 address
Hostip="$(ip -4 -o a | awk '{print $4}' | cut -d/ -f1 | grep -v 127.0.0.1 | head -n1)"

# or especially IP from docker daemon
Hostip="$(ip -4 -o a| grep docker0 | awk '{print $4}' | cut -d/ -f1)"

Run docker image. You need a free TCP port, here 34567 is used.
(TCP port number must be in range of cat /proc/sys/net/ipv4/ip_local_port_range and must not be in use. Check with ss -nlp | grep 34567.)
docker run --rm \
    --name pulsecontainer \
    --env PULSE_SERVER=tcp:$Hostip:34567 \
    imagename

After docker run get IP of container with:
Containerip="$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' pulsecontainer)"

Load pulseaudio TCP module authenticated with container IP:
pactl load-module module-native-protocol-tcp  port=34567 auth-ip-acl=$Containerip

Be aware that the TCP module is loaded after container is up and running. It takes a moment until pulseaudio server is available for container applications.
If TCP connection fails, check iptables and ufw settings.

A How-To summarizing these setups: https://github.com/mviereck/x11docker/wiki/Container-sound:-ALSA-or-Pulseaudio


text:
Q: which of the following statements are true and why? which of the following statements are true and why?

*

*Any two irreducibles in any UFD are associates.

*If $D$ is a PID, then $D[x]$ is a PID.

*In any UFD, if $p|a$ for an irreducible $p$, then $p$ itself appears in every factorization of $a$.

can anyone help me to find the proofs and counter examples of the above as reasons.thanks for your time.

A: Hint 1) Look at $\Bbb Z$.
Hint 2) Look at $D=\Bbb Z$.
Hint 3) Let $u$ be any unit besides 1, and $q=pu$ is also prime. Now $p|q$. Does $p$ appear in the factorization of $q$ as just $q$? (I am not totally sure what counts as a factorization to you, so this is the best hint I can think of!)


text:
Q: ui.bootstrap.tabs how to know which tab is active in angularjs controller I have two tabs in my tab set on html:
<tabset justified="true" style="padding:13px">
    <tab heading="Static profit" >
        content one
    </tab>
    <tab heading="Dinamic profit" >
        content two
    </tab>
</tabset>

My question is how to know in controller which tab is active. I want show/hide outside div depending of active tab.

A: Try like this
<tabset justified="true" style="padding:13px">
    <tab heading="Static profit" ng-click="onTabSelect('tab1')" >
        content one
    </tab>
    <tab heading="Dinamic profit" ng-click="onTabSelect('tab2')">
        content two
    </tab>
</tabset>

js
$scope.onTabSelect=function(tabName){
  console.log(tabName);
}


text:
Q: Why doesn't Spring's PathMatchingResourcePatternResolver match "*" with nothing? I am trying to get a properties file from within a zip file.  I need to use a wild card, because I will want to match either "my.properties" or "my_en.properties".  I create a ResourcePatternResolver like so:
ClassLoader loader = MyClass.class.getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader);

I succeed when I try to retrieve the "my.properties" file using no wild card:
resolver.getResource("file:C:/somePath/a.zip/META-INF/my.properties").exists()

returns true.  However, if I add a wild card to the file name, it fails, e.g.,
resolver.getResource("file:C:/somePath/a.zip/META-INF/my*.properties").exists()

returns false.  What can I do to match and retrieve either file?  I am trying to do this in a webapp within Tomcat.

A: The documentation is unclear about this, but the getResource method does not use PathMatcher internally to resolve the resource (that means that no wildcard is allowed), try getResources(String locationPattern) instead.
For example :
Resource[] resources = resolver.getResources("file:C:/somePath/a.zip/META-INF/my*.properties");

for(Resource resource : resources) {
  // do something for each resource found
}

A: The official documentation explains it:

No Wildcards:
In the simple case, if the specified location path does not start with
  the "classpath*:" prefix, and does not contain a PathMatcher pattern,
  this resolver will simply return a single resource via a getResource()
  call on the underlying ResourceLoader. Examples are real URLs such as
  "file:C:/context.xml", pseudo-URLs such as "classpath:/context.xml",
  and simple unprefixed paths such as "/WEB-INF/context.xml". The latter
  will resolve in a fashion specific to the underlying ResourceLoader
  (e.g. ServletContextResource for a WebApplicationContext)

For trying anti-patterns, have a look at:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html

A: How suggest Sébastien Helbert getResource and getResources works very different in fact if you see the original Spring Code you can see a this code:
public class PathMatchingResourcePatternResolver implements ResourcePatternResolver {

....
@Override
    public Resource getResource(String location) {
        return getResourceLoader().getResource(location);
    }

    @Override
    public Resource[] getResources(String locationPattern) throws IOException {
        Assert.notNull(locationPattern, "Location pattern must not be null");
        if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
            // a class path resource (multiple resources for same name possible)
            if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
                // a class path resource pattern
                return findPathMatchingResources(locationPattern);
            }
            else {
                // all class path resources with the given name
                return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
            }
        }
        else {
            // Generally only look for a pattern after a prefix here,
            // and on Tomcat only after the "*/" separator for its "war:" protocol.
            int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
                    locationPattern.indexOf(':') + 1);
            if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
                // a file pattern
                return findPathMatchingResources(locationPattern);
            }
            else {
                // a single resource with the given name
                return new Resource[] {getResourceLoader().getResource(locationPattern)};
            }
        }
    }
...
}

reading the Spring code is clear that getRersources use the AntPattern and geetResource no. I fell it right because with a Wildcards is implicit that you want a multi result and not only one, get resource do not works because it do not take an the common opinion of if I have more that one I take the first, it just do not works because it is no been think in order to works for take the first in case of multi result, it is just a choice.
For this reason the your use case, use the wildcard, can be achieved using the getResources() method
I hope that it can help you to take the right method.


text:
Q: Multiple Domain in single VPS using VHOST I want to create multiple sites in one vps, example sites on port 80 use www.domain1.com and on port 8080 use www.domain2.com. can nginx or anything handle that?
i have tried to use port forwarding, but is not working well
my nginx.conf
server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  domain1.com;
        root          /var/www/html;

        # Load configuration files for the default server block.
        #include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }

        # PHP
            location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;

        }

    }

and my virtualhost.conf
#Virual Host
    server {
         listen 8080;

         access_log /var/log/nginx/nginx-access.log;
         error_log /var/log/nginx/nginx-error.log;

        # Root
         root /var/www/web2/public;
         index index.php index.html index.htm;

         # server name
         server_name domain2.com;

         location / {
                try_files $uri $uri/ /index.php?$query_string;
         }

         # PHP
         location ~ \.php$ {
                 try_files $uri =404;
                 fastcgi_split_path_info ^(.+\.php)(/.+)$;
                 fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                 fastcgi_index index.php;
                 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                 include fastcgi_params;

         }

  }

if possible, how the way?

A: You can run both domains on port 80. you don't need to change port to 8080.
In nginx.conf change server_name from domain1.com back to default_server;
In your /etc/nginx/conf.d/ directory create two config files, domain1-com.conf and domain2-com.conf
donain1-com.conf
server {
listen  80;
server_name domain1.com www.domain1.com;
access_log            /var/log/nginx/domain1-com-access.log;
error_log             /var/log/nginx/domain1-com-error.log;

     root /var/www/web1/public;
     index index.php index.html index.htm;

   # PHP
     location ~ \.php$ {
             try_files $uri =404;
             fastcgi_split_path_info ^(.+\.php)(/.+)$;
             fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
             fastcgi_index index.php;
             fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
             include fastcgi_params;

     }

}

domain2-com.conf
server {
listen  80;
server_name domain2.com www.domain2.com;
access_log            /var/log/nginx/domain2-com-access.log;
error_log             /var/log/nginx/domain2-com-error.log;

     root /var/www/web2/public;
     index index.php index.html index.htm;

   # PHP
     location ~ \.php$ {
             try_files $uri =404;
             fastcgi_split_path_info ^(.+\.php)(/.+)$;
             fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
             fastcgi_index index.php;
             fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
             include fastcgi_params;

     }

}


text:
Q: AWS Lambda Python package - no module named redis I have a python package that I would like to upload to AWS Lambda.
The package works on two different machines with no dependencies issues at all.
However, when uploading the same folder to AWS Lambda, I get the following error:

Unable to import module 'tweet_analyzer_python/lambda_handler': No module named redis

Here is a list of the files in the package:
.
|-- event.json
|-- lambda_handler.py
|-- redis
|   |-- client.py
|   |-- client.pyc
|   |-- _compat.py
|   |-- _compat.pyc
|   |-- connection.py
|   |-- connection.pyc
|   |-- exceptions.py
|   |-- exceptions.pyc
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- lock.py
|   |-- lock.pyc
|   |-- sentinel.py
|   |-- utils.py
|   `-- utils.pyc
|-- redis-2.10.5-py2.7.egg-info
|   |-- dependency_links.txt
|   |-- installed-files.txt
|   |-- PKG-INFO
|   |-- SOURCES.txt
|   `-- top_level.txt
|-- retrying-1.3.3-py2.7.egg-info
|   |-- dependency_links.txt
|   |-- installed-files.txt
|   |-- PKG-INFO
|   |-- requires.txt
|   |-- SOURCES.txt
|   `-- top_level.txt
|-- retrying.py
|-- retrying.pyc
|-- six-1.10.0-py2.7.egg-info
|   |-- dependency_links.txt
|   |-- installed-files.txt
|   |-- PKG-INFO
|   |-- SOURCES.txt
|   `-- top_level.txt
|-- six.py
`-- six.pyc

For double-checking, I have downloaded the same zip file that was uploaded to AWS Lambda and put it on a clean linux machine.
When running:

python tweet_analyzer_python/lambda_handler

I had no issues at all.
Can someone explain me what am I doing wrong?
Thanks!

A: When you run 'lambda_handler.py' locally you are running a main methods within the python file. The lambda function however calls the lambda_handler method within lambda_handler.py directly.
Your lambda handler is not configured to run 'lambda_handler.lambda_handler' and is failing on 'tweet_analyzer_python/lambda_handler'
Either :

*

*1) rename lambda_handler.py to tweet_analyzer_python or

*2) change your lambda handler to 'lambda_handler.lambda_handler'

To change your handler; go your lambda in AWS, select configuration, and update the handler and save the function.
Also ensure your redis dep is packaged in your zipped lambda function.


text:
Q: WebHdfs could not reslove hostname while GET operation I am trying to fetch a file using WebHdfs by Postman my GET request is:
http://xxx.xx.xx.xx:50070/webhdfs/v1/user/hduser/json/json_record.json?op=OPEN
I am getting a dns_unresolved_hostname error. On the other hand if I do op=LISTSTATUS I am getting the correct result.
Is there something wrong in the request :
http://xxx.xx.xx.xx:50070/webhdfs/v1/user/hduser/json/json_record.json?op=OPEN


text:
Q: Incorporating a Custom Grid with the Rally SDK There are a few things that the custom grid does that you cannot do with tables in the Rally SDK-- specifically re-ranking items.
For an app that I am making, incorporating a custom grid would work well, but I would like to be able to configure them programatically-- e.g. set up column names and widths, query parameters, etc. and then have that be a portion of my app-- I might set up a few grids in the app with different query parameters.
It that possible?

A: It's not possible.  Yet.
We are working hard on a shiny new App SDK based on the Ext JS Framework.  It will have a lot of the same features you are familiar with in Rally (like the grid w/ re-ranking, inline editing, etc).
Watch for it later this spring/summer!


text:
Q: Inverse DFT - Matlab vs OpenCv I'm trying to convert some Matlab code to OpenCv and have problems with inverse FFT. Codes in MATLAB and OpenCV gives different results.
In MATLAB:
A = [ 1 2 3; 4 5 6;  7 8 9; 10 11 12]; %simplest matrix I can think of
mask = [0 1 0 0; 0 1 0 0; 0 1 0 0]';

F = fft(A,[],1);
F(~mask) = 0;
real(ifft(F,[],1))
ans =
-1.5000  -1.5000  -1.5000
-1.5000  -1.5000  -1.5000
1.5000   1.5000   1.5000
1.5000   1.5000   1.5000

OpenCV:
Mat A = (Mat_<float>(4,3) <<  1,2,3,
                            4,5,6,
                            7,8,9,
                            10,11,12);

transpose(A,A); //transpositions to make DFT on columns like in MATLAB
Mat transformed;
dft(A,transformed,DFT_ROWS|DFT_COMPLEX_OUTPUT);  // Applying DFT
Mat mask = (Mat_<float>(4,3) << 0,0,0,
                            1,1,1,
                            0,0,0,
                            0,0,0);
transpose(transformed,transformed);
vector<Mat> transformed_splitted;
split(transformed, transformed_splitted);
transformed_splitted[0] = transformed_splitted[0].mul(mask);
transformed_splitted[1] = transformed_splitted[1].mul(mask);
merge(transformed_splitted,transformed);
transpose(transformed,transformed);
idft(transformed,transformed,DFT_ROWS|DFT_REAL_OUTPUT|DFT_SCALE);
transpose(transformed,transformed);
cout << transformed;

output:
[-3 -3 -3 ;
-3 -3 -3 ;
3 3 3 ;
3 3 3 ]

It seems to me, that there is something wrong with scaling. Funny thing is that for matrix 5x3 results from both codes are the same. For 8x3 additionaly some results differ. How can I obtain same results from both IFFT?
This question is also asked in my edited post here:Matlab FFT vs OpenCv DFT


text:
Q: jQuery.css cannot set repeating-linear-gradient I'm trying to make it by this code:
var $li = $('#marks').find('li[data-id=111222333]'),
color = 'rgb(' + $li.css('background-color').match(/\d+/g).map(function (i) {
    return (+i > 100 ? ((+i + 33) > 255 ? i : +i + 33) : +i + 99);
}).join(',') + ')',
gradient = 'repeating-linear-gradient(45deg, '+$li.css('background-color')+', '+$li.css('background-color')+' 3%, '+color+' 3%, '+color+' 6%);';
$li.css({'background-image': gradient});

But it doesn't works... I'm also trying this:
$li.css({'background': gradient});
$li.css('background', gradient);
$li.css('background-image', gradient);
$li[0].style.background = gradient;
$li[0].style.backgroundImage = gradient;

Butt result is same... Any ideas?!
UPD. Try here https://jsfiddle.net/kk77x3ru/

A: It's because you have an unnecessary ; char in your gradient. Get rid of that
gradient = 'repeating-linear-gradient(45deg, '+$li.css('background-color')+', '+$li.css('background-color')+' 3%, '+color+' 3%, '+color+' 6%)';

UPDATED FIDDLE


text:
Q: Webpack-dev-server creates js files next to src-file instead of compiling into target bundle-file About to setup a workflow with webpack for angular 2. Everything works fine so far compiling the typescript files into a target file.
Also the webpack-dev-server runs good and autocompiles the target-file as soons as i make changes to one of the src-files.
But: It not only compiles it the target file, dev-server also creates a js file right next to the changed source-ts file. This is kinda annoying since I'd like to keep the src clean. Any Idea how to prevent this?
This is the webpack.config.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = [{

name: 'angular',
entry: './src/app/main.ts',
output: {
    path: './build/',
    filename: 'js/app.bundle.js'
},
module: {
    loaders: [{
        test: /\.jade$/,
        loader: 'raw!jade-html'
    }, {
        test: /\.ts$/,
        loader: 'ts-loader'
    }]
},
resolve: {
    extensions: ['', '.js', '.ts']
},
plugins: [
    new HtmlWebpackPlugin({
        template: './src/index.html',
    })
]

}]

A: You IDE could be taking over some of the compilation. Make sure you have such a line on tsconfig.json
"compileOnSave": false

Also if all your files are typescript and don't have .js files. Its a good practice to ignore *.js files in the main folder src/app. Add the line to you .gitignore
app/src/**/*.js