How can I center a ScrollPane that wraps a fixed-sized Canvas in a BorderPane?

Question: In a JavaFX application I need to center a fixed-sized Canvas wrapped by a StackPane, then a ScrollPane, within a BorderPane. The problem is that when I include the ScrollPane, the component tree is no longer centered in the middle of the center area of the BorderPane. One solution I tried is to fix the max size of the ScrollPane. This works (the components become centered), but creates a different problem: when the viewport area is insufficient in any one dimension (say, width), both scrollbars will appear anyways. Because  ScrollPane's size is bounded, the extra space occupied by the scrollbar in one dimension will cause the viewport to shrink in the other dimension and the max size property, required for centering, will prevent allowing more space for it.
Here is a working demonstration of the problem:
public final class Minimal extends Application {

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

    @Override
    public void start(Stage stage) {
        Canvas canvas = new Canvas(200,200) {
            @Override
            public boolean isResizable() {
                return false;
            }
        };

        StackPane pane = new StackPane(canvas);
        pane.setStyle("-fx-border-insets: 4; -fx-border-style: solid;");
        ScrollPane scroll = new ScrollPane(pane);
        // scroll.setMaxSize(212, 212); // Imperfect Solution
        BorderPane root = new BorderPane();
        root.setCenter(scroll);
        stage.setScene(new Scene(root));
        stage.show();
    }
}

With the line commented out, when resized, the frame shows up as:

If I fix the max size: then both scroll bars show up at once (notice how the vertical one is not necessary:

The closest I found was this question, which does not really have an answer. Unfortunately, this solution, which seems to work well in Swing, does not appear to do anything since I'm already using a wrapper (the StackPane), and it's not helping. I'm hoping there's a solution that exclusively relies on layouts, without having to revert to writing listeners for resize events or binding to size properties, etc.
Comment: Are you saying that when the window is made larger than the Canvas requires, you want the Canvas to be centered?  Do you want it centered horizontally, vertically, or both?
Answer: Let the StackPane fill the entire ScrollPane.  The StackPane will then center the canvas for you:

The stackpane will attempt to resize each child to fill its content area. If the child could not be sized to fill the stackpane (either because it was not resizable or its max size prevented it) then it will be aligned within the area using the alignment property, which defaults to Pos.CENTER.

Thus, all you need to do is set the ScrollPane's 'fitTo…' properties, so the StackPane will fill it:
scroll.setFitToWidth(true);
scroll.setFitToHeight(true);


UWP - SoftwareBitmap para Stream

Question: Eai pessoal,
Estou utilizando MediaFrameReader para capturar os frames de uma câmera USB em uma aplicação UWP, o retorno do evento FrameArrived me retorna um objeto do tipo SoftwareBitmap, tendo esse frame eu verifico se existe rosto humano utilizando FaceDetector, ao detectar essas faces eu pretendo utilizar o SDK do FaceId para verificar se este rosto está cadastrado, entretanto o SDK exige que eu envie uma imagem em estado de Stream, como eu posso fazer essa conversão?
Muito obrigado!
Answer: Pode optar por utilizar o BitmapDecoder, como no exemplo:
var stream = new InMemoryRandomAccessStream();
ImageEncodingProperties properties = ImageEncodingProperties.CreateJpeg();
await _mediaCapture.CapturePhotoToStreamAsync(properties, stream);
var decoder = await BitmapDecoder.CreateAsync(stream);
SoftwareBitmap sfbmp = await decoder.GetSoftwareBitmapAsync();

Comment: The first code is not possible, because I could not use Image in UWP, but the second and third gave me the necessary light to execute the code, updated as an answer!

Thanks a lot, I lost 2 days looking for this!
Comment: @RePinheiro I just updated the answer, I'm glad it worked.
Answer: Conversão:
        SoftwareBitmap frameBitmap = frame.SoftwareBitmap;
        WriteableBitmap bitmap = new WriteableBitmap(frameBitmap.PixelWidth, frameBitmap.PixelHeight);
        frameBitmap.CopyToBuffer(bitmap.PixelBuffer);
        var stream = new InMemoryRandomAccessStream();
        await bitmap.ToStream(stream, BitmapEncoder.JpegEncoderId);
        var detect = await faceClient.Face.DetectWithStreamAsync(stream.AsStream());

UWP - SoftwareBitmap para Stream


Como faço para linkar uma imagem no PHP?

Question: if($formaCombate == "patk")
{
    if($patk1 > $patk2)
    {
        echo "Jogador 1 Ganhou!";
    }
    elseif ($patk1 < $patk2)
    {
         echo "Vitória do jogador 2";
    }
    else
    {
        echo "";
}

Gostaria de linkar uma imagem em cada echo.
Comment: if($formaCombate == "patk")
{
 if($patk1 > $patk2)
 {
  echo "Jogador 1 Ganhou!";
 }
 elseif ($patk1 < $patk2)
 {
   echo "Vitória do jogador 2";
 }
 else
 {
  echo "";
}
Comment: Isso aqui está errado `` ... o certo é algo assim: ``
Comment: entendi, vou tentar, obrigada
Comment: Deu erro na syntax da ultima linha :(
Comment: Marque a resposta que resolveu seu problema como aceita veja como em https://i.stack.imgur.com/evLUR.png e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Comment: Eu ainda não entendi realmente o que você quer... Acho que você poderia tentar explicar melhor a finalidade ou aceitar uma das respostas abaixo..
Comment: @NathaliaScatena Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: No PHP não tem jeito porque a linguagem não trabalha com isto, mas em HTML tem jeito e está errado no seu código. O PHP é só um agente que está gerando o HTML para você, portanto a questão nada tem a ver com esta linguagem, a não ser que ela seja outra bem diferente do que está descrito.
A tag  é a que determina que haverá um link ali. Ela existe por si só, o que terá dentro pode ser vários elementos do HTML, pode ser um texto ou pode ser uma imagem. HTML são tags umas dentro das outras.

Se quiser mais legível:

No caso das outras é só reproduzir este código com o nome da imagem que quer que seja exibida e o devido link:
if ($formaCombate == "patk") {
    if($patk1 > $patk2) echo "";
    elseif ($patk1 < $patk2) echo "";
    else echo "";
}

Coloquei no GitHub para referência futura.
Documentações:

a href
img
Answer: Para criar um hiperlink usamos o comando formado pelo par de TAGS   com a seguinte sintaxe:
texto ou figura ou elemento

Hyperlink de texto é uma palavra ou frase, que foi atribuída a um URL de destino. Neste caso o visitante do site pode clicar em qualquer lugar da palavra ou frase para exibir seu destino.
exemplo: Texto
Hyperlink de figura é uma figura que foi atribuída a um URL de destino. Neste caso, o visitante do site pode clicar em qualquer parte da figura para exibir seu destino.
exemplo:
Na sua aplicação ficaria assim
if($formaCombate == "patk")
{
    if($patk1 > $patk2)
    {
        echo "Jogador 1 Ganhou!";
    }
    elseif ($patk1 < $patk2)
    {
         echo "Vitória do jogador 2";
    }
    else
    {
        echo "";
}


AccessDeniedHttpException on a route with _access: TRUE

Question: In my custom module I have a few "publication" routes that do not need any kind of authentication. Months ago I learnt that I could achieve this with the following requirements in routing.yml:
my_module.myroute:
  [...]
  requirements:
    _access: 'TRUE'

This works on my existing routes.
Now I'm trying to add a new one that parses the Authorization HTTP header only for identification purposes: the purpose is to show a custom view on public data, without any authentication or authorization need. So, I tried to reach my custom route adding an Authorization header (via a browser extension), and I get the following error:
Path: /CLS/it/pub/quadroxml. Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException:
The used authentication method is not allowed on this route.
in Drupal\Core\EventSubscriber\AuthenticationSubscriber->onExceptionAccessDenied()
(line 134 of [...]/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php).

So, sending an Authorization header apparently triggers some authentication method even on routes with _access: 'TRUE'.
Can I disable completely all authentication and authorization on some routes? Alternatively, can I enable the "used authentication method" on my route, and then accept any password? (I am only interested in the user id!)
Answer: I'm not sure about how to accept any password. But there is a difference between the default user authentication and basic_auth you are probably using for this route. The first one is defined as global:
core/modules/user/user.services.yml
user.authentication.cookie:
    class: Drupal\user\Authentication\Provider\Cookie
    arguments: ['@session_configuration', '@database', '@messenger']
    tags:
      - { name: authentication_provider, provider_id: 'cookie', priority: 0, global: TRUE }

while the second one is not:
core/modules/basic_auth/basic_auth.services.yml
services:
  basic_auth.authentication.basic_auth:
    class: Drupal\basic_auth\Authentication\Provider\BasicAuth
    arguments: ['@config.factory', '@user.auth', '@flood', '@entity_type.manager']
    tags:
      - { name: authentication_provider, provider_id: 'basic_auth', priority: 100 }

In this case the route needs to specify the _auth option. See
https://www.drupal.org/docs/drupal-apis/routing-system/structure-of-routes
Comment: Well, this is indeed not complete, but it put me on the right track. I understood that the authentication providers available were not suited to my needs, so I implemented a custom one. and then I added it to the `_auth` option, as I suggested. I think this may deserve a new answer, and a comment to the other question that put me on the right track...
Comment: I've hesitated to suggest a custom authentication provider, because the question topic was the route definition. But showing the two core definitions was pointing in that direction and then of course you need a priority of >100 to override both.
Comment: Yes, indeed it pointed in the right direction. I'm curious about your statement on the priority, is it possible that if I use a low priority the predefined authentication providers are still used? I ask because that's what seems to be happening...
Comment: If you have enabled HTTP Basic Authentication and you are sending an Authorization header, this module is used, unless you implement a custom authentication provider with a higher priority. The authentication happens before routing. After routing it's only checked whether the provider which won the authentication race before is appropriate for the route.
Comment: I see. That explains everything I saw. I didn't find this behaviour documented anywhere – but I may have not looked deep enough. Also, I guess that implementing a custom behaviour on an HTTP Basic Authentication is not really a common requirement, especially nowadays... Anyway, I think that _now_ this is documented, _here_ :)
Answer: You can do pretty much anything you want when it comes to access control, by either defining a custom access check via a controller class (1) that you set directly on the specific route, or by creating your own access check service (2).
1. Access check via controller class
Docs: Custom route access checking
example.routing.yml
example:
  [...]
  requirements:
    _custom_access: '\Drupal\example\Controller\ExampleController::access'

ExampleController.php
class ExampleController {

  public function access(AccountInterface $account) {
    // Return \Drupal\Core\Access\AccessResultInterface here
  }

}

2. Access check service
Docs: Advanced route access checking
Basically, you do the same thing that provides the _access parameter that you already use (which is implemented by DefaultAccessChecker. So you create a tagged service and set that service to be a requirement on your route. The example from the docs is very complete, so I don't copy that here.
Comment: Thank you, I already add a custom route access check in my module. I tried to add another one for this new path, but it made no difference: in the end I managed to solve my problem using a custom authentication provider, so I guess my problem was in the earlier phase of authentication rather than in the access check phase.
Answer: Inspired by @4k4 answer, I implemented a custom authentication provider, as detailed here: the sample implementation used on that page only checks for the presence of an header, I just had to replace X-Auth-Token with Authorization to get the code to do what I need.
With a minor, but important correction: if I left priority: 10 in the tags of the authentication service, I still keep on getting the same error when I send an Authorization header in the request. I struggled with this problem for a few hours, googling and searching; in the end my eye fell on the priority: -10 value of a path processor service I implemented months ago, where I had left the helpful comment "Low priority acts last", so I changed the value of the priority to 1000, and suddenly I managed to get my route to work!
I don't understand exactly why this happens, since I had only my custom authentication provider in the _auth vector under options, so I don't see how another provider can get a higher priority. I think this may be a bug, I'll try to find the time to reproduce it on a clean installation and file it.
Anyone needing help on this issue should also have a look at this question: it didn't help me much because the problem with priority is not mentioned, but since the problem is exactly the same, maybe other hints may be collected.


Geometric interpretation on an algebraic geometry problem

Question: Let $\mathcal{K}$ be an algebraically closed field and $n\geq 1$.
I've prooved that an ideal $\textbf{m}\subset \mathcal{K}[X_1,...,X_n]$ is maximal if and only if $\textbf{m}=(X_1-a_1,...,X_n-a_n)$, with $a_1,...,a_n\in \mathcal{K}$.
I need to interpret this result geometrically. Any suggestion is appreciatte.
Comment: Since $K$ is algebraically closed, you can take polynomials to be distinct functions $K^n\to K$. Then the elements of $m$ are those polynomial functions which vanish at the point $(a_1\dots,a_n)$. In fact the point is completely determine by $m$.
Answer: This means that the only closed points of the topological space $X = \textrm{Spec}(\mathcal{K}[X_1,...,X_n])$ are the points coming from $\mathcal{K}^n$. Note that this space is not only a topological space, but also an affine scheme.


Unable to access ssl certificate from octopus library as X509Certificate2 object using powershell

Question: I am trying to create a jwt token using a pfx which,I have stored in Octopus library. For this I have to create an object of X509Certificate2, which takes certificate path and password as input. Can someone please suggest a way to do this using powershell?
<code>$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certpath,'password')
</code>
I have been through some documents as per how to access certificate variables in octopus but how can I use them to create an object of X509Certificate2.
https://octopus.com/docs/deployment-process/variables/certificate-variables
Answer: After going through Microsoft and Octopus documentation I have managed to get it to work. Octopus store the certificate as a base64 encoded string in a variable named as Cert.Pfx and constructor of X509Certificate2 takes a byte array as a first parameter. So as a first step I just needed to convert the base64 encoded string to byte array.
<code>$certbytearray=[System.Convert]::FromBase64String($OctopusParameters["Cert.Pfx"])
$CertPassKey="password"
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certbytearray,$CertPassKey)
</code>
Answer: @Biplab Thanks for posting your solution; it saved me a lot of headache! I had a slightly different situation without a password and I found that the X509Certificate2 constructor interpreted the byte array as a file name when I tried to call without the password even though the documentation indicates it should accept just a byte array.
I got it to work without the password by doing an import instead.
<code>$certbytearray=[System.Convert]::FromBase64String($OctopusParameters["mycert.Pfx"])
$mycert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$mycert.import($certbytearray)
write-host $mycert.ThumbPrint
if ($mycert.HasPrivateKey)
{ write-host "has private key"}
</code>


How does "secondaryPreferred" work in this scenario?

Question: Suppose there is a replica set of three nodes: 1 primary P and 2 secondaries S1 and S2. Suppose also that P and S1 are located in one data center DC1 and S2 in another data center DC2.
Suppose a client is located in DC1 (i.e. in the same data center as P and S1) and S1 is down. Where will the client queries go ? P or S2 ?
Answer: secondaryPreferred will choose the secondary, even if it's further away (I'm assuming that S2 has a lower priority because it probably shouldn't be primary, so in your scenario S2 is the secondary and that it's further away in the latency sense).
You can instead use tag sets for data-center awareness / geographically distributed members or the nearest read-preference, which will select the server that is closer, irrespective of whether it's a primary or secondary.
Comment: And is covered directly in the paragraphs following the link: http://docs.mongodb.org/manual/reference/read-preference/#secondaryPreferred
Answer: From the MongoDB documentation:
secondaryPreferred

In most situations, operations read from secondary members, but in situations where the set consists of a single primary (and no other members), the read operation will use the set's primary.
When the read preference includes a tag set, the client attempts to find a secondary member that matches the specified tag set and directs reads to a random secondary from among the nearest group. If no secondaries have matching tags, the client ignores tags and reads from the primary.
Read operations using the secondaryPreferred mode may return stale data.

My guess is that you would get the data from S2, since that is what you have asked for with the preferred suffix. The secondary option excludes the primary entirely but while the secondaryPreferred allows for primary to be used in case of no secondaries.
Though by using tags for your servers in the same data center you can make the driver read from primary even though a secondary is present in the rest of the replica set.
Comment: It's not a matter of a guess. As the documentation you quote says, The  use of a tag set can resolve this so that the operations will use the nearest in preference to a remote secondary. This ensures the routing to the secondary rather than the primary. But you probably didn't see the other answer in time.
Comment: Bad phrasing. It is plain as you say.


"google.maps.MapTypeId is undefined" when using GMAP3 in FF 14

Question: Testing the sample code from gmap3:

on FF 14.0.1, it gives the alert:

TypeError: google.maps.MapTypeId is undefined

on Chrome 16.0.889.0, a div with image shows up.
Why is there such a difference?
Answer: You can try naming your function that initializes the map and then put it as callback in the link loading Google Maps api.
Something like this:

Original answer from here: Google Maps API v3 - TypeError... https://stackoverflow.com/a/8361021/1266136
Answer: might be a little late, but for me it helped adding this line:
var myLatlng = new google.maps.LatLng(0.0, 0.0);

before you call mapTypeId: google.maps.MapTypeId.TERRAIN
Like this:
 var myLatlng = new google.maps.LatLng(0.0, 0.0); // this will somehow initialize google.maps...
 $('#geoTestDiv').gmap3(
              { action: 'addMarker',
                latLng : [46.578498,2.457275],
                map:{
                  center: true,
                  zoom: 14,
                  mapTypeId: google.maps.MapTypeId.TERRAIN
                }
              }
              );


What is the benefit of the port portion of the "Host" header in HTTP/1.1?

Question: Can anyone explain what is the benefit of the port portion of the "Host" header in HTTP/1.1? Is it so that we can have two or more websites with the same names (but different ports)?
Answer: Most of the internet website traffic is done on standard port 80. For this case, a port number can (according to RFC should) be omitted. HTTPS traffic is usually done on port 443 in which case a browser will include it by default. Connection to any other port is a fairly special case (mostly for development or separation of services).
So yes, if you want to have two different sites with the same (sub)domain on a server, you would have to either distinguish them by port or some kind of cookie trickery.
But the most common examples of using ports in HTTP communication is a multi-application server, where port determines which applications API should be used.
Comment: But why is this header even necessary? Having received and accepted the TCP connection, the web server obviously *already knows* which port is being used...
Comment: The port number used as a target of TCP connection from browser and port number of destination server doesn't have to be same.
If you use any HTTP proxy for example, you are always connecting to some defined port (let's say 8080) no mather what kind of traffic is going through. The proxy needs to know to which destination port it should relay the request.
Answer: It is required by the RFCs, a point previously made here:
https://stackoverflow.com/questions/3364144/is-port-number-required-in-http-host-header-parameter
The question was why, and the RFC's requirement does seem a bit contrary to normal layering.  After all, the port is a property of the transport connection and not of the application (or session) layers.
However I would speculate that  carrying this property forward into the application layer may have been seen to be desirable to allow multiple sites to be handled on a single IP address, and including the port specifier here does allow the freedom to create website software that separates the TCP communications process from the web application whilst still being able to use the incoming port number if required.


What is the difference between a short fugue and a versette?

Question: What is the difference between a short fugue and a versette?
Short Fugue example:
https://imslp.org/wiki/Ariadne_Musica_(Fischer,_Johann_Caspar_Ferdinand)
Versette example:
https://imslp.org/wiki/44_Versetten_(Albrechtsberger%2C_Johann_Georg)
Answer: A versetto (Italian, mid-1500's) is a very short polyphonic composition, often using imitative entries much more closely spaced than would be found in a motet of that era (Palestrina gives each textual phrase its own block of imitative entries, spaced far enough apart to make at least the first few words comprehensible: "Agnus Dei, qui tol-[jabberwocky ensues]", oh, whatever, I know how the rest of those words go, let's just chill and enjoy the music).
(A long modern Italian list of musical terms equates versetto to nothing more or less precise than the English word verse.  Not too helpful.)
A short fugue would have more than one set of imitative entries.  Many of Fischer's examples even thin out the texture halfway through (look for the rests).  There's no time for that in a versetto.
But the boundaries are blurry.  A contemporary composer or listener, presented with one or the other out of context, might have trouble distinguishing a long versetto from an extremely short fugue.
Within context, however: hey, this comes after a prelude in the same key, ergo it's a fugue.
I doubt that short fugue is a well-distinguished musical form.  It's just a fugue that is short.


PHP echo produces a "Parse error: syntax error"

Question: I have started learning PHP and trying a simple echo statement on XAMP on my machine. This is my code  :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>Hello</title>
<link rel="stylesheet" type="text/css" href="common.css" />

 <?php echo "Hello, world !"; ?>

When I run this I am getting this error  :

Parse error: syntax error, unexpected '!', expecting ',' or ';' in C:\xampp\htdocs\PHP\hello.php on line 9

I have no clue as to what is going wrong.
Comment: You're using the wrong kind of quotes. Use `"` instead (`"` is wrong).
Comment: Those quotes seem tired. They can't stand up straight. Maybe use more robust ones.
Comment:    copy paste this and check
Answer: Try
<?php echo "hello, World!"; ?>

Answer: If you are using MS Word to write your code, don't. Use Notepad++ or Sublime Text - even plain ol' Notepad is better.
Also, you must run your program using localhost/PHP/hello.php - not c:\xampp\htdocs\PHP\hello.php
In the browser address bar, type localhost/PHP/hello.php
Comment: I am using notepad++ and running it using localhost/PHP/hello.php
Comment: Do you understand why we have identified the incorrect quotes as the reason for your problems? The quotes posted in your question are "smart quotes" inserted by word processors like MS Word. ASCI double quotes are not slanted: ` " `  How did you get the smart quotes in your question?
Comment: Yes , I got it now . Never knew there were different  type of  quotes . Thanks a lot .


What is the ordinary definition of a saddle-point?

Question: Suppose $f:\mathbb{R}^2 \to\mathbb{R}$ is a $\mathcal{C}^2$ function such that both first-order partial derivatives vanish at the origin. Under what circumstances would you say that $f$ has a saddle-point at the origin?
If the Hessian of $f$ is nonsingular, then this question is not interesting, so I suppose I am really asking when a function $f$ having a stationary point at the origin and whose Hessian is singular there has a saddle-point. Consider as examples the obvious saddle-point $f(x,y) = x^4 - y^4$, the slightly less obvious case of $f(x,y) = x^3-y^3$, and the very peculiar case of $f(x,y) = \sin(1/(x^2 + y^2))\exp(-1/(x^2+y^2))$ extended to $\mathbb{R}^2$ by setting $f(0,0)=0$.
Answer: A saddle point is a critical point that's not a local maximum or minimum; in other words, a point $p$ with $\nabla f(p)=0$ and the property that for all $\epsilon>0$, there exist two points $q_1$ and $q_2$ with $\|p-q_1\|<\epsilon$, $\|p-q_2\| < \epsilon$, and $f(q_1) < f(p) < f(q_2)$.
If $f$ is only $C^2$ there's no way to characterize such functions by looking only at $f$'s derivatives at $p$ (since like you point out all bets are off at points where both the gradient and Hessian vanish.) Perhaps more could be said if $f$ is smooth.
Comment: This is the definition that wikipedia, for instance, uses (inconsistently). I myself feel uncomfortable calling something that exhibits no saddle-like behaviour at all a saddle-point, but I don't know where I'd draw the line.
Comment: For what it's worth, the question of $\mathcal{C}^2$-ness is a red herring, there are pathological examples where the function is smooth, the third example in the original question is pretty dreadful, but smooth.
Comment: How do we know that if a point is a saddle point that maybe in some directions (not just in the direction of x and y) this point is minima or maxima?
Comment: I would expect a saddle point to have some sort of stable/unstable (positive/negative) *submanifolds*, whether linear or smooth, rather than simply *subsets*, as in this definition. Maybe with an additional requirement that the submanifolds intersect rather than touch. This would keep [Peano surface](https://en.wikipedia.org/wiki/Peano_surface) as a saddle surface, but exclude the second example $f(x,y)=x^3-y^3$ and also $f(x)=x^3$. @BenWilliams, is this something like what you had in mind?


Jasper server Active Directory conf erroe :Invalid content was found starting with element 'value'

Question: I'm authenticationg jasperserver 5.6.1 to microsoft active directy reference to this.
[https://community.jaspersoft.com/documentation/jasperreports-authentication-cookbook/v56/authentication-microsoft-active-directory]
but when I compile and run the server there's a log error.
cvc-complex-type.2.4.a: Invalid content was found starting with element 'value'. One of '{"http://www.springframework.org/schema/beans":meta, ' is expected.
The erroe occered userSearch bean in span class="Forceful".
<bean id="userSearch"
      class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
  <constructor-arg index="0"><value>cn=Users</value></constructor-arg>
  <constructor-arg index="1"><value>(sAMAccountName={0})</value></constructor-arg>
  <constructor-arg index="2"><ref local="ldapContextSource"/></constructor-arg>
  <property name="searchSubtree"><value>true</value></property>
</bean>

How to fix this error ?
Best Regards,
Chinthaka
Answer: You need to remove the  class from both constructor-arg's.
They should look like this..
<constructor-arg index="0"><value>cn=Users</value></constructor-arg>
<constructor-arg index="1"><value>(sAMAccountName={0})</value></constructor-arg>

Hope that helps..
Comment: I tried that one.But it couldn't work on new jasper server version 5.6.1.


Prove that three points are collinear (Menelaus theorem?)

Question: Given a point P inside the triangle ABC. Lines AP, BP, CP intersect the sides BC, CA, AB in points $A_1, B_1, C_1$. The lines $A_1B_1$ and AB intersect in the point  $A_2$. The points $B_2,C_2$ are defined in a similar way. How can I prove that $A_2, B_2, C_2$ are collinear?
I think it has to do someting with the Menelaus theorem. But how can I use it here?. Another hard thing in this task is that it is almost impossible to draw a good figure, the best thing I could get is that:
Answer: Hint: by Ceva's theorem for the cevians through $P\,$:
$$
\frac{BA_1}{A_1C}\cdot\frac{CB_1}{B_1A}\cdot\frac{AC_1}{C_1B} = 1
\tag{1}$$
By Menelaus' theorem for the transversal $A_1B_1\,$:
$$
\frac{BA_2}{A_2A}\cdot\frac{AB_1}{B_1C}\cdot\frac{CA_1}{A_1B} = -1
\tag{2}
$$
Multiplying the two $(1) \cdot (2)\,$:
$$
\require{cancel}
\cancel{\frac{BA_1}{A_1C}}\cdot\bcancel{\frac{CB_1}{B_1A}}\cdot\frac{AC_1}{C_1B} \;\cdot\; \frac{BA_2}{A_2A}\cdot\bcancel{\frac{AB_1}{B_1C}}\cdot\cancel{\frac{CA_1}{A_1B}} = -1 \;\;\iff\;\; \frac{BA_2}{A_2A} = -\,\frac{C_1B}{AC_1}
$$
Repeat for $B_2,C_2\,$, multiply together, and the RHS reduces to $-1$ using $(1)$ one more time.
(It should be noted that the problem is equivalent to half the Desargues' theorem in the plane.)
Comment: And what happens when we get all those -1s?
Comment: @idliketodothis It follows that $A_2,B_2,C_2$ are collinear by (the converse of) Menelaus' theorem.
Comment: But what I got for point B2 is B2C/B2B = -BA1/A1C; for point C1: AC2/CC2 = -B1A/CB1;
All in all, I have C1B/AC1 * BA1/A1C * B1A/CB1 = -1. What am I doing wrong?
Comment: @idliketodothis Don't know how you somehow reverted to $(1)\,$. What you get in fact is $BA_2/A_2A \cdot AC_2/C_2C \cdot CB_2 / B_2B = -1\,$, which proves that $A_2,B_2,C_2$ are collinear. As a side note, you did not choose the best notation to preserve the symmetry in $A,B,C\,$, and it would have been easier to follow had you defined $AB \cap A_1B_1=C'$ instead of $A_2\,$.
Answer: A proof using projective geometry: Triangles $ABC$ and $A_1B_1C_1$ are perspective from the point $P$, so by Desargues' Theorem they are perspective from a line too, i.e. their pairs of corresponding sides intersect at $3$ points which are collinear. This implies $A_2,B_2,C_2$ are collinear.


Verify connectivity to a server on a UDP port

Question: I want to know if a HP-UX machine can communicate to a remote machine (which I don't have control over) on a particular port using UDP.
I tried telnet, but it doesn't look like it supports UDP. I would use netcat, but I was unable to find any bundle. This machine is in production so I don't want to mess around compliling or installing things too much... (nmap, netcat from source...)
Any simple way to do this?
Answer: Pinging a UDP port is kind of tricky, since there are no connections, per se. If you don't have control over the remote host, then you might never really know whether your UDP datagrams are actually being received. I assume you already know whether the remote host is reachable, via ping, traceroute, mtr, etc. (If not, check that first!)
Next, since you don't have netcat, you'll need some way of generating UDP packets.
The bash shell sends UDP packets when you redirect data to the special device /dev/udp/host/port. For example:
#!/bin/bash
host="10.10.10.10"
port=12345
echo "PING" >/dev/udp/$host/$port

Python, of course, is also fully capable of UDP, e.g.
#!/bin/python
import socket
host="10.10.10.10"
port=12345
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_sock.sendto('PING', (host, port))

Regardless of how you contrive to generate your UDP "ping" packet, you'll want to know whether the target received it. If the target port is open (i.e. a service is listening at the given port), then what happens will be application-defined. Hopefully, you will notice some behaviour or indication from the remote system.
If the target port is closed (i.e. no service is listening at that port), then you should get an ICMP error packet back in response. Use your favourite wire-level network sniffer to watch for it. Or, perhaps your HP-UX system logs ICMP errors somewhere (sorry, I don't have any experience with HP-UX).
Unfortunately, if the target is firewalled, you may not get a response when the target port is closed. The only surefire way to know if the remote host is responsive is to run your UDP-data-dependent application and watch the network traffic.
Answer: You can use netcat. In OSX, this is my command:
$ nc -vnzu <IP> <PORT>
found 0 associations
found 1 connections:
1: flags=82<CONNECTED,PREFERRED>
outif (null)
src <SOURCE IP> port <SOURCE PORT>
dst <DEST IP> port <DEST PORT>
rank info not available

Comment: Perfect, nc works for everything!


product topology confusion

Question: Let $(X_i)_{i \in I}$ be a nonempty collection of nonempty
topological spaces.Then let $f: I \to I$ be a bijection. Of course, if $\alpha \in I$, then we can define the projection $\pi_\alpha : \prod_{i \in I} X_i \to X_\alpha$ by $\pi_\alpha((x_i)_{i \in I}) = x_\alpha$. However, how are we to define projections on $\prod_{i \in I} X_{f(i)}$?
Do we define $\rho_\alpha : \prod_{i \in I} X_{f(i)} \to X_\alpha$ by
$\rho_\alpha((x_{f(i)})_{i \in I}) = x_\alpha$?
This is important to me, since I want to be able to say something about the continuity of functions from $\prod_{i \in I} X_i$ to $\prod_{i \in I} X_{f(i)}$.
Thanks.
Comment: I would use $\rho_\alpha \colon \prod\limits_{i\in I} X_{f(i)} \to X_{f(\alpha)}$.
Answer: You can do it either way,
$$\rho_\alpha:\prod_{i\in I}X_{f(i)}\to X_\alpha:\langle x_{f(i)}:i\in I\rangle\mapsto x_\alpha$$
or
$$\rho_\alpha:\prod_{i\in I}X_{f(i)}\to X_{f(\alpha)}:\langle x_{f(i)}:i\in I\rangle\mapsto x_{f(\alpha)}\;,$$
whichever is more convenient; just be sure to use it consistently the way you've defined it.

product topology confusion


How to have different style files in multilingual website using Drupal?

Question: I have been developing a multilingual website using Drupal 6. The languages are English and Spanish. I want to have some different backgrounds and css for them. But both use just style.css.
How can I create different style.css file for them? For example style-sp.css for Spanish one and en-style.css for English one ?
Is it possible ?
Answer: you can do this in template.php:
you have to copt css file in themefolder/css.
<code>    function yourtheme_preprocess_page(&$vars) {
        global $language ;
        $lang_name = $language->language ;
        if ($lang_name=='en')
        drupal_add_css(path_to_theme(). '/css/en-style.css');
        elseif ($lang_name=='sp')
        drupal_add_css(path_to_theme(). '/css/style-sp.css');
        $vars['styles'] = drupal_get_css(); //  use drupal_get_css() to add new css
}
</code>
so you have one of css files related to current page language.
Comment: I copied and pasted your code and put my theme instead of 'yourtheme'. Cleared cache, but it doesn't work.
Comment: i 'm sorry. you are using drupal 6.i think you have to use  'yourtheme_preprocess_page'. let me know if it works.
Comment: I use preprocess_page function, it goes through it but doesn't add style file.
Comment: i edited code and tested by myself and it works.


Some confusions while applying Cauchy's Theorem (Local Form)

Question: I have a couple of confusions surrounding the correct use of Cauchy's Theorem to compute integrals using techniques in complex analysis. I'm using the following local version of the following theorem:
\begin{align}
\textbf{} \text{Suppose that} \; \Delta \; \text{is  an open disk in the complex plane and that} \; f \; \text{is a function which is analytic
in $\Delta$ (or, more generally, is continuous in} \; \Delta \; \text{and analytic in} \; \Delta \setminus\{z_0\}. \text{Then,} \int_{\gamma} f(z) dz = 0 \; \text{for every closed, piecewise smooth
path } \; \gamma \; \text{in} \; \Delta
\end{align}
I have the following confusions:

On the contour $\gamma(t) =  2 \cos t + i \sin t, \; t \in [0, 2\pi]$, I'm trying to evaluate the integral,

\begin{align}
\int_{\gamma} \frac{dz}{z}
\end{align}
Since the contour encloses a pole of this function, I expect the integral to be non-zero. But a direct computation using the given contour shows that the integral is zero! Here's a sketch of the computation:
Noting that $\dot{\gamma}(t) = -2 \sin t + i \cos t$, the integral is:
\begin{align}
\int_{0}^{2 \pi} dt \; \frac{-2 \sin t + i \cos t}{2 \cos t + i \sin t}.
\end{align}
Letting $a = 2 \cos t + i \sin t$, a change of variable shows that the new limits under the change of variable are $2$ and $2$!
For a circle of radius 1, a direct computation yields a non-zero answer. What's going on? I can compute the answer by considering a closed path formed by paths for the ellipse and the circle, where one closed path lies in the right-half plane, and the other lies in the left half-plane. Using the analyticity of the function in these domains, the answer, $2 \pi i$, is readily computed. What goes wrong with a direction computation though?

For $b > 0$, I wish to show that,

\begin{align}
\int_{- \infty}^{\infty} e^{-t^2} \cos(2 b \pi t) = \sqrt{\pi} e^{-b^2 \pi^2}
\end{align}
The textbook recommends using the function $e^{-z^2}$ over the a rectangular contour defined by vertices $-c, c, c + i b \pi, -c + i b \pi$.
I understand the motivation of choosing this contour from previous exercises, but I am not sure why is the function $e^{- z^2}$ chosen? Since the integral with the $\sin(2b\pi t)$ replaced with $\cos(2 b \pi t)$ is clearly zero, shouldn't we consider the function $e^{- z^2 + iz}$?
Comment: Plus, no residue theorem for point number 1. I haven't covered it yet.
Answer: You must have made a mistake in your direct computation.  The contour you mentioned is a simple Jordan curve containing the origin in its interior so the line integral should be the residue of the function at the point (namely, $1$) times $2\pi$.
Your change of variable is not legitimate because it does not enable you to replace all occurrences of $t$ by $a$, so it does not  help you to compute the integral.
Comment: That was a typo. I have edited the computation sketched above.


Use string as bash variable name in alternative value expansion

Question: How can I use the value of one variable as the name of another variable in an alternative value expansion (${var+alt}) in bash?
I would think that
#!/bin/bash
cat='dog'
varname='cat'
if [ -z ${`echo "${varname}"`+x} ]; then
    echo 'is null'
fi

should be roughly equivalent to
#!/bin/bash
if [ -z ${dog+x} ]; then
    echo 'is null'
fi

but when I try to do this, I get
${`echo "${cat}"`+x}: bad substitution

I guess part of the problem is that the subshell doing the command substitution doesn't know about $varname anymore? Do I need to export that variable?
My reason for doing this is that I learned from this answer how to check if a variable is null, and I'm trying to encapsulate that check in a function called is_null, like this:
function is_null {
    if [ $# != 1 ]; then
        echo "Error: is_null takes one argument"
        exit
    fi
    # note: ${1+x} will be null if $1 is null, but "x" if $1 is not null
    if [ -z ${`echo "${1}"`+x} ]; then
        return 0
    else
        return 1
    fi
}

if is_null 'some_flag'; then
    echo 'Missing some_flag'
    echo $usage
    exit
fi

Comment: I think you need this http://stackoverflow.com/questions/26337826/in-linux-shell-script-how-can-i-recall-value-of-variable/26337979#26337979
Comment: @Ashwani Thank you, that's just what I needed. I changed my if statement to `if [ -z ${!1+x} ]; then ...`
Answer: I'm not sure if I understand your problem.
If I got, what you need is eval command.
$ cat='dog'

$ varname='cat'

$ echo ${varname}

cat

$ eval echo \$${varname}

dog

Comment: What he was looking for was **indirection**, while that can be accomplished with `eval`, the use of `eval` is frowned upon in such circumstances.
Comment: @Davison I appreciate your answer - `eval` can do the job, but as David said, I was trying to avoid the use of that sledgehammer in favor of a more precise tool. I forgot to mark my question as duplicate to the link posted above.


Como usar If Else corretamente

Question: Tenho os seguintes checkboxes:
<input type="checkbox" class="check"  id="livros" value="livros"/>
<input type="checkbox" class="check" id="folhas" value="folhas"/>
<input type="checkbox" class="check" id="porta" value="porta"/>

 Avaliar

e preciso compará-los de acordo com o que o usuário escolher:
function Avaliar_checkbox() {

    // Variáveis
     var livros = document.getElementById("livros");
     var folhas = document.getElementById("folhas");
     var porta = document.getElementById("porta");

// Variáveis
if (livros.checked) {
        alert('livros');
     }
if (folhas.checked) {
        alert('folhas');
     }
if (porta.checked) {
        alert('porta');
     }
if (livros.checked && porta.checked) {
        alert('Livros e Porta');
     }
if (livros.checked && folhas.checked && porta.checked) {
        alert('Livros, folhas e porta');
     }
}

O problema é que quando executo a função, as condições entram em conflito, me retornam dois resultados ou não retornam nada. Qual seria a maneira correta de fazer isso?
Comment: Eu daria uma olhada em switch-case, que apesar de ser um pouco mais lento ajuda muito na legibilidade do código.
Answer: Você está fazendo a comparação de maneira incorreta, para o seu caso eu aconselho utilizar if-else assim:
if (livros.checked && folhas.checked && porta.checked) {
    alert('Livros, folhas e porta');
} else if (livros.checked && porta.checked) {
    alert('Livros e Porta');
} else if (livros.checked) {
    alert('livros');
} else if (folhas.checked) {
    alert('folhas');
} else if (porta.checked) {
    alert('porta');
}

Primeiro você verifica livros, folhas e porta, se ambos estiverem checados, ele dá o alert("Livros, folhas e porta"), senão e se livros e porta estiverem checados ele manda o alert, e assim por diante, repare no uso do else antes do if, é ele que vai fazer com que a próxima verificação seja chamada, mas somente se a anterior falhar, dessa forma você não executa o alert mais do que o necessário.
Answer: Acho que é isto que deseja. Se cada opção é mutualmente exclusive precisa elas precisam ser avaliadas como uma estrutura só, executando uma delas, não executa as outras seguintes. Isto de fato é obtido com o else.
Mas também precisa colocar as opções mais restritivas na frente. Ou seja, a opção que precisa ter mais condições verdadeiras deve vir antes que as outras mais simples. Se não fizer isto a que tem apenas uma opção executa e se outras opções foram ligadas não serão executadas.
Não sei se era a intenção ou esqueceu que existem outras possibilidades de combinações de ter dois checkboxes ligados.

function Avaliar_checkbox() {
    var livros = document.getElementById("livros");
    var folhas = document.getElementById("folhas");
    var porta = document.getElementById("porta");
    if (livros.checked && folhas.checked && porta.checked) alert('Livros, folhas e porta');
    else if (livros.checked && porta.checked) alert('Livros e Porta');
    else if (livros.checked) alert('livros');
    else if (folhas.checked) alert('folhas');
    else if (porta.checked) alert('porta');
}
<input type="checkbox" class="check"  id="livros" value="livros"/>
<input type="checkbox" class="check" id="folhas" value="folhas"/>
<input type="checkbox" class="check" id="porta" value="porta"/>

Avaliar

Coloquei no GitHub para referência futura.

Como usar If Else corretamente


Javascript : How to scroll horizontally to given position within an overflowed div?

Question: I have following situation
<code>WRAPPER (100% width of page)
----------------------------------------------
|                                            |
|                                            |
|     CONTENT (8000px width)                 |
|                                            |
|                                            |
----------------------------------------------
|     HORIZONTAL SLIDER FOR CONTENT          |
----------------------------------------------
</code>
Dragging the slider is moving thought the content.
I would like to ask how can i programatically trigger horizontal slider click to move for give position. Or how move to the given position on axis X.
I tried scrollTo but without the luck (it works only for document object.
Maybe use the anchors, but i would like the simplest solution.
Many thanks for any advice.
Answer: Did you try with scrollLeft(value)?
For more information on this please see the link https://api.jquery.com/scrollleft/
Comment: Thank You very much, i did not know about this method.
Answer: You can use jquery scrollLeft() method (or scrollLeft DOM property) on the container


Server Density or Scout-like Services for Windows?

Question: I've been very impressed with agent-based / SaaS-like monitoring services such as Scout and Server Density.  They both provide very nice trending, alerting, and reporting capabilities for my *nix boxes, and I need to find something similar for Windows.
Can anyone out there recommend such a tool?
It is important that this tool is a centralized service in line with the aforementioned products, as the deployment environment is owned by a lean team with limited resources.
Thanks!
Answer: Server Density has a Windows monitoring agent now, so I'd still recommend it.
Answer: Don't know what the size of your Windows install-base is, but if you want to go "whole hog" the Microsoft monitoring system is System Center Operations Manager 2007 R2.  It's not exactly cheap compared to other solutions out there, but it basically has every conceivable monitoring and alerting option covered.
They almost have it completely scriptable via PowerShell.
However, it can be a real pain to get configured.  You are probably better off sticking with the product you already understand/use in a "lean" team.
Comment: Thank you very much for the recommendation - I should have been more specific about the size of the environment, as it will be somewhere around a dozen machines to begin with.  I'm trying to keep support infrastructure as lean as possible for this project, so something like Server Density will probably work better.

Thanks again, though.  I'll keep this in mind for our larger environments.
Comment: Ssystem Center Essentials. Cheaper, handles that well, still. One machine separate is not a problem - even fo r a dozen machines. Virtualize it.
Answer: My company, Panopta, has a Windows agent that can be installed locally on a server that feeds metrics to our central monitoring system for combined alerting and reporting with results from our Linux agent and remote network service checks.


Display two block elements on same line using CSS

Question: So I'm trying to print this out on one line, But when it executes it prints the statement out on two separate lines. Any ideas why?
Example:
Welcome
12/14/2012
<?php
 print("
Welcome
" .
    "
" . Date('n \/ j \/ Y') . "
");
 ?>
If this make any difference I'm trying to print a welcome one the left side of the page, and the date on the right Example:
Welcome             12/14/2012
Answer: that's an html issue. As h1 and h2 are block level elements the browser puts a line break at the end. You can use css to change that or use more appropriate html
<?php print("
Welcome
" . "
" . Date('n \/ j \/ Y') . "
"); ?>

Comment: Thats what I figured, but I wasn't sure. Thanks for the help.
Answer: <?php print("
Welcome  " . Date('n \/ j \/ Y') )."
"; ?>

Comment: Why was it downvoted? Perfectly valid answer for the question, +1
Comment: Perfectly good answer, only thing I would change is to wrap the date in a span so further styles can be applied.
Comment: @zerkms Yes, but technically they'd still be on the same *side* of the page.
Comment: @zerkms you didn't see it before the edit. I have reversed my down vote
Comment: Thanks for the attempt. But unfortunately I would like to use a h1 and and h2.
Comment: @mvmrocks: "But unfortunately I would like to use a h1 and and h2" --- that's why it really matters **how** you ask a question :)
Comment: The question was to have the `` on the left and `` on the right; this has both on the left.
Comment: @Jack: with the code from answer you would have the `Welcome` from the left of the date. And there is nothing about keeping `h1` and `h2`. So it's not ideal, but it fits requirements :-)
Comment: @mvmrocks -- Did u tried with this..? previously its an hmtl cause.
Answer: Also a tip:
Think in boxes and find out which elements are blockelements.
If they are block-elements you have to float them OR change them into Inline-Objects.


Random variables

Question: I've just come across a few questions on the net which I have no idea how to answer, can anyone point me towards the right direction?

Random variables $X$ and $Y$ are such that $X$ has mean 1 and variance 4, $Y$ has mean 2
and variance 9, and $\text{Corr}(X, Y ) = 1/3$ What is the variance of $3X − 2Y + 1$?
In question 1 above, what is the covariance between $X + 2Y$ and $X − Y$ ?
In question 1 above, if $Z$ is another random variable satisfying $E[3X −2Y +Z] = 0$,
what does the mean of the random variable $Z$ equal?
Comment: The variance is defined as $\mathrm{Var}(X)=\mathrm{E}[(X-\mu)^2]$. And the covariance of $X$ and $X$ is by definition $\mathrm{Cov}(X,X)=\mathrm{E}[(X-\mathrm{E}(X))\cdot (X-\mathrm{E}(X))]=\mathrm{E}[(X-\mathrm{E}(X))^2]=\mathrm{E}[(X-\mu)^2]$ (the same as the variance of $X$). For question 2, look at the [answer of Macro](http://stats.stackexchange.com/a/38722/21054) and just plug in the numbers (the result is $-12$). For question 3, look at the Wikipedia page about the linearity of [expected values](http://en.wikipedia.org/wiki/Expected_value#Linearity). The answer for question 3 is $1$.
Comment: Regarding your question about how to format equations w/ $\LaTeX$ on CV, it may help you to read my answer [here on meta](http://meta.stats.stackexchange.com/questions/1604/reviewing-questions-and-applying-latex-format/1605#1605).
Comment: Concerning the first question, have a look at the Wikipedia page about the variance and especially about the [Sum of correlated variables](http://en.wikipedia.org/wiki/Variance#Sum_of_correlated_variables). Also, look at the definition of the [correlation coefficient](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#For_a_population). That should get you started. For question 2, have a look at [this post](http://stats.stackexchange.com/questions/38721/covariance-of-a-variable-and-a-linear-combination-of-other-variables).
Comment: You'll have to search the web for examples. Maybe you could explain where exactly you're stuck? The Wikipedia page on the variance of [Weighted sum of variables](http://en.wikipedia.org/wiki/Variance#Weighted_sum_of_variables) almost provides the final solution to your first question (you have to calculate the covariance though, use the definition of the correlation for this).
Comment: The covariance is 2, that's exactly right! $a$ and $b$ are just numbers. In your case, you search the variance $\mathrm{Var}(3X-2Y+1)$, so $a=3$ and $b=-2$. You can drop the $+1$, because adding 1  doesn't affect the variance. **48 is the correct solution.**
Comment: Thanks for the post but the wiki page isn't helping at all, are there any examples I can look at instead?
Comment: Yeah, the covariance is 2 right? But I'm not sure about what a/b are.
Edit = is it 48 for q.1?
Comment: thanks a lot, any extra guidance with 2 and 3? I don't understand how cov(X,X) = var(X), Is that what I should be using?
Answer: The definition of variance and a few basic properties should be enough to answer the questions. For the third one, you may need to remember that the expected value operator is linear.
You can work out ${\rm Cov}(X, Y)$ from ${\rm Corr(X, Y)}$ given how the definition of ${\rm Corr}$.
Answer: Given
E(X) = 1,  σ2x = 4, E(Y) = 2, σ2y =  9, and Rxy = 1/3
Cov(X, Y) = Correlation (X,Y))*(SD (X)*SD(Y)
Cov(X, Y) = (1/3)*(2)(3) = 2
Random variables X and Y are such that X has mean 1 and variance 4, Y has mean 2 and variance 9, and Corr(X,Y)=1/3 What is the variance of 3X−2Y+1?
Variance of linear combination of random variable is given by
Var (aX+bY+c)=a2 Var(X) + b2 Var(Y) + 2ab Cov(X,Y)
Hence,
Var (3X−2Y+1) = 3^2 Var(X) + (-2)^2 Var(Y) + 2 (3)(-2) Cov (X, Y)
= (9*4) + (4*9) – 12* 2
= 72 – 24 = 48
In question 1 above, what is the covariance between X+2Y and X−Y ?

Cov(X+2y, X - Y) = Cov(X, X) – Cov(X, Y) + 2 Cov(Y, X)  - 2 Cov (Y, Y)
As, Cov(aX+bY,cW+dZ) = acCov(X,W)+adCov(X,Z)+bcCov(Y,W)+bdCov(Y,Z)
Cov(X+2y, X - Y) = 4 + 2 - 2*9 = -10
As, Cov(X,X)=Var(X) = 4, Cov(Y,Y)=Var(Y) = 9 and Cov(X, Y) = Cov(Y, X) = 2
In question 1 above, if Z is another random variable satisfying E[3X−2Y+Z]=0, what does the mean of the random variable Z equal?

Given E[3X−2Y+Z]=0
Hence,
3E(X) – 2E(Y) + E(Z) = 0
Or (3*1) – (2*2) + E(Z) = 0
Or E(Z) = 1
Mean/expectation of random variable Z is one.
Comment: Early on you seem to confuse correlation and covariance.  That creates an erroneous result that appears to be propagated into subsequent answers.

Random variables


Windows 2003 DNS subdomains

Question: We have a purely internal DNS setup to resolve multiple nics for eash host, i.e. -

mailserver01-sm 126.96.36.199 remote access and AD connectivity (service management)
mailserver01-data 184.108.40.206 mail routing
mailserver01-bk 126.96.36.199 backup connectivity

My question is this can I frig DNS by having sub domains of -sm, -data, & -bk under the FQDN ?
so that the following each appear under the relevant subdomains:-

mailserver01-sm.datacenter.int
mailserver01-data.datacenter.int
mailserver01-bk.datacenter.int

instead of:-

mailserver01.-sm.datacenter.int
mailserver01.-data.datacenter.int
mailserver01.-bk.datacenter.int
Answer: Having any part of an FQDN starting or ending with a hypen is not a supported configuration. You can create a zone starting or ending in -, but it's really not recommended.
Also, records within that zone (i.e. A or CNAME) that start with a - will not work with most DNS resolvers, as - is usually reserved for flags.
You can use _ however.
Refer to RFC 1035, section 2.3.1 (although it's been revised by RFC 1123 to permit starting with a digit rather than an alpha)

Windows 2003 DNS subdomains


How do I change the automatically generated migration page in Laravel?

Question: When I genarate a migration in Laravel, it automatically looks like this:
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
    });
}

But I want to work more convenient, I want to let the database handle when I create and update a row instead of doing it myself everytime.
I found a way to make this possible like this:
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamp('created_at')->useCurrent();
        $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
    });
}

But now everytime I make a migration, I manually have to change this and I don't think that's very convenient. Does anybody know how I can change the automatically generated migration in Laravel?
Comment: Eloquent manages these fields by default unless you're doing something weird with your models. What do you mean you have to do it yourself every time?
Comment: @Bytewave I want to be able to have those two lines of the created_at and the updated_at in a migration by default, but the defaul currently is $time->timestamps()
Answer: If you dig around in the source code you will find that:

There's a file called create.stub in the framework.
This file is used by the MigrationCreator to make migrations.

In principle you can do the following:

Grab the built-in migration file and move it in another folder in your project (e.g. resouces/stubs probably) Note that you should copy the other stubs in that folder too even if you won't modify them.
Then, override the default migration creator to use this file instead, this should work:
class MyMigrationCreator extends MigrationCreator {
      protected function stubPath() {
             return base_path("resources"); //Or something valid
      }
}

Then in your application service provider you can do:
$this->app->instance(MigrationCreator::class, resolve(MyMigrationCreator::class));

This will (hopefully) "trick" laravel into using your migration creator than the default one. However, creating tables is not something that happens so often to justify all this trouble.
Update: It should extend the migration creator.
Comment: This will not work on Laravel 5.6 and maybe in couple of earlier minor versions. The reason os that MigrationServiceProvider is deferred and it creates instance of MigrationCreator class directly: $this->app->singleton('migration.creator', function ($app) {
            return new MigrationCreator($app['files']);
        }); The worst thing is that even if you redeclare $this->app->singleton('migration.creator', function ($app) {}) even in boot() - it will be overwritten because MigrationServiceProvider is deferred. I'm stil searching for the solution. =(
Comment: @Swayok try using `$this->app->instance` instead of `singleton` and pre-resolve it yourself. Hopefully that will be flagged as resolved in the framework.
Comment: then it will be reloved every time service provider is called and this is not a way it should work because you do not need this class every time your app loads
Comment: Well you can limit it to when you are running it in the CLI at least since that's when you need the migration creator. I know it's not a good solution but there doesn't seem to be an official way to change the stubs.
Answer: Testet with Laravel 10.
Custom MigrationCreator:
<?php

namespace App\Services;

use Illuminate\Database\Migrations\MigrationCreator as Creator;

class MigrationCreator extends Creator
{
    // Custom Changes
}

Custom MigrateMakeCommand:
use Illuminate\Database\Console\Migrations\MigrateMakeCommand as Command;
use App\Services\MigrationCreator; # <- Custom Creator!
use Illuminate\Support\Composer;

class MigrateMakeCommand extends Command
{
    /**
     * Create a new migration install command instance.
     *
     * @param \App\Services\MigrationCreator $creator
     * @param \Illuminate\Support\Composer   $composer
     */
    public function __construct(MigrationCreator $creator, Composer $composer)
    {
        parent::__construct($creator, $composer);
    }

    // Custom Changes
}

ServiceProvider:
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Foundation\Application;
use App\Console\Commands\Migrations\MigrateMakeCommand; # <- Custom Command!
use App\Services\MigrationCreator; # <- Custom Creator!

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->registerMigrateMakeCommand();
    }

    /**
     * Register a custom make:migration command.
     *
     * @return void
     */
    protected function registerMigrateMakeCommand(): void
    {
        $this->app->singleton(MigrateMakeCommand::class, function (Application $app) {
            $creator = new MigrationCreator($app['files'], $app->basePath('stubs'));

            $composer = $app['composer'];

            return new MigrateMakeCommand($creator, $composer);
        });
    }
}

Answer: In Laravel 5.6 there seems to be no possibility to override MigrationCreator class because it is used directly in MigrationServiceProvider:
protected function registerCreator() {
    $this->app->singleton('migration.creator', function ($app) {
        return new MigrationCreator($app['files']);
    });
}

But you can hack MigrationServiceProvider next way:

Create directory in your project root: overrides/Illuminate/Database
Copy file vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php into overrides/Illuminate/Database folder (note that class namespace will remain same)
Modify overrides/Illuminate/Database/MigrationServiceProvider.php:
protected function registerCreator() {
    $this->app->singleton('migration.creator', function ($app) {
         return new MyMigrationCreator($app['files']);
    });
}

Modify your composer.json ("Illuminate\\"):
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/",
        "Illuminate\\": "overrides/Illuminate"
    }
},

Run composer dump-autoload. Composer will say
`Warning: Ambiguous class resolution, "Illuminate\Database\MigrationServiceProvider" was found in both "$baseDir . '/overrides/Illuminate/Database/MigrationServiceProvider.php" and "/vendor/laravel/framework/src/Illuminate\Database\MigrationServiceProvider.php", the first will be used.`

Now your fake MigrationServiceProvider will be used instead of Laravel's but you won't be able to use original one. That's why we copied whole file.
Actually this way you can override MigrationCreator class but amount of code there is high and you actually will need to extend it with your MyMigrationCreator class and override several methods like stubPath() and maybe create(). But MigrationServiceProvider can be quite safely overriden because it contains several small methods that are unlikely will be changed until Laravel 6


360 image in cardboard app

Question: I have just purchased a 360 camera. I have seen on the cardboard demo app that you can view images in VR mode within the app. How do I go about doing this? I already know how to view a virtual environment from unity in VR mode but cant find a solution for doing it with 360 images.
Answer: There is no out of the box support for this.
What you can do is the following:

create a sphere
place the 2 GC cameras inside the sphere
use your image as the texture for the sphere

A few notes about this:

the default sphere that comes with Unity is a UV sphere, you'll need an icosphere to reduce the distortion near the pols.
a sphere has the normals oriented outwards so you'll need to invert them so the rendering happens on the interior of the sphere instead of the outside

360 image in cardboard app


Como usar um if dentro do outro?

Question: O problema é o seguinte 2 times de futebol, queria criar um decisão onde mostraria "Brasil ganhou" ou "Argentina Ganhou" ou "Houve empate".
Porém não consigo criar três decisões, segue abaixo meu código.
#include<iostream>
using namespace std;

int main(){
    int a, b;

    cout<<"Digite quantos Gol(s) o Brasil fez: ";
    cin>>b;
    cout<<"Digite quantos Gol(s) a Argentina fez: ";
    cin>>a;

    if (b>a){
        cout<<"\nBrasil ganhou com "<<b<<"Gol(s)\n";
        /*if (b==a){
            cout<<"Brasil e Argentina empatou, ambos com "<<a<<"Gol(s)";
        }*/

    }
    else (a==b)
        cout<<"Houve empate. "<<a<<"Gol(s)";

    else
        cout<<"\nArgetina ganhou com "<<a<<"Gol(s)\n";

    return 0;

}

Comment: Alguma das respostas resolveu o seu problema? Acha que pode aceitar uma delas? Se ainda não o fez, veja o [tour] como proceder. Você ajudaria a comunidade identificando a melhor solução para você. Pode aceitar apenas uma delas, mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Você não quer fazer um dentro do outro, embora isso até funcionaria, mas não é o ideal, o melhor é fazê-los em sequência:
int main() {
    int a, b;
    cout << "Digite quantos Gol(s) o Brasil fez: ";
    cin >> b;
    cout << "Digite quantos Gol(s) a Argentina fez: ";
    cin >> a;
    if (b > a) cout << "\nBrasil ganhou com "<< b << "Gol(s)\n";
    else if (a == b) cout << "Houve empate. " << a << "Gol(s)";
    else cout << "\nArgetina ganhou com " << a << "Gol(s)\n";
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: No final um  else if não seria um if aninhado no else?
Comment: @Guto, na verdade sim, o `if` reside dentro do `else`, mas se costuma não usar as chaves no `else`, nesse caso, por questão de semântica, dando a impressão do `else if` ser uma estrutura única.
Um jeito interessante de se usar o `else if` é com macros `#define elif else if` assim cria uma estrutura unica. `if(true){...}elif(!false){...}elif(a==b){...}`
Answer: Você deve usar o else if(statement)que significa: "SE NÃO PASSAR NO IF DE CIMA, TENTE ESTE".
No seu caso vai ficar:
cout<<"Digite quantos Gol(s) o Brasil fez: ";
cin>>b;
cout<<"Digite quantos Gol(s) a Argentina fez: ";
cin>>a;

if (b>a){
    cout<<"\nBrasil ganhou com "<<b<<"Gol(s)\n";
    /*if (b==a){
        cout<<"Brasil e Argentina empatou, ambos com "<<a<<"Gol(s)";
    }*/

}
else if(a==b){
    cout<<"Houve empate. "<<a<<"Gol(s)";

} else {
    cout<<"\nArgetina ganhou com "<<a<<"Gol(s)\n";
}

return 0;

Answer: cout<<"Digite quantos Gol(s) o Brasil fez: ";
cin>>b;
cout<<"Digite quantos Gol(s) a Argentina fez: ";
cin>>a;

if (b>a){
    cout<<"\nBrasil ganhou com "<<b<<"Gol(s)\n";
}else{
    if (b==a){
        cout<<"Brasil e Argentina empatou, ambos com "<<a<<"Gol(s)";
    }else{
       cout<<"\nArgetina ganhou com "<<a<<"Gol(s)\n";
   }
}

return 0;

Como usar um if dentro do outro?


Angular MFE - WebPack5 - Module Federation - Image Path Issue

Question: We are creating an MFE angular app using Module Federation WebPack 5 and ended up in an issue with the image source path. When we run the MFE alone, the image is loading(localhost:5000/assets/../angular.png) but when we run the host/shell app, the image is not loading for MFE since MFE is running in a different port(5000) and Shell is running in a different port(4200) and the app is trying to access the image from Shell's asset folder(localhost:4200/assets/../angular.png) when we run the shell app.
We have two options in hand:

Move those images to a common folder, outside the MFE and refer
set the image path dynamically using the basepath from a configuration file

We have used the below sample for my testing but in the below sample the angular.png file is available in both MFE1 and Shell but if we remove it from Shell, it won't work when we load the shell app.
Source Reference Code Sample (thanks to @manfredsteyer)
Any other solution in MFE to resolve this?
Comment: just adding a github issue of someone having the same question: https://github.com/module-federation/module-federation-examples/issues/697
Comment: I am a same problem. Do you have a solution
Answer: The problem is that the images are imported using relative paths. Because the micro frontends are always loaded inside the shell, these paths will reference the shell's assets. To fix the issue you would need to add the complete URL to the image to load it from the correct micro frontend.
If you want to load an image in the micro frontend it should look like this:

To adjust the base url for production or development, you could write a method in a service that you can inject into your componentes. It could look something like this:
public getImageBaseUrl(): string {
  if (environment.production) {
    return "http://someurl.com/assets/";
  } else {
    return "http://localhost:5000/assets/";
  }
}

Then you can call the method inside your HTML-template:

Comment: Just updated my answer, hope it will help :)
Comment: Because of Angular's change detection, you should not set an HTML attribute with a function. The function will run every time change detection runs to determine if the value has changed.
Is it your suggestion that the URL to the deployed micro-frontend should have an entry in the environment file?
Comment: you are right but this base URL will differ based on environment(QA, UAT, PROD), right? how that can be resolved?
Comment: The best possible solution which I am currently thinking is UrlRewrite (at the server) our assets folder should be unique specific to child apps, and matching the asset folder we can redirect the request to the actual child app URL (may be different url). In case of IIS there is a separate module and for nginix .htaccess file would help in getting UrlRewrite in place... Will update my results soon.
Answer: I found a few solutions for this problem. First we need to understand the main issue: let's say the shell app is running on localhost:3000, and the remote app is running on localhost:3001. In the remote app you can use images in two ways:

in html code:
in CSS stylesheet: .img { background-image: url(/assets/image.png) }

When you deploy the remote app and run it directly (on localhost:3001) it will correctly resolve both links to image to url localhost:3001/assets/image.png, and image will show.
But when you load the remote app in the shell app (on localhost:3000), the shell app will inject the remote html and css code inside the host DOM, and all links will be resolved relatively to the shell app url, which means on localhost:3000/assets/image.png (where the image does not exist.
The solution is we have to modify the remote app code to output absolute url to images:

in html code:
in CSS stylesheet: .img { background-image: url(http://localhost:3001/assets/image.png) }

If you know URL where the remote app will be deployed in advance, the easiest solution is to set deployUrl option in angular.json file (if remote app is Angular):
"build": {
  "options": {
    "deployUrl": "http://localhost:3001"
    ...
   },
   "configurations": {
     "production": {
       "deployUrl": "https://production.server.com"
       ...
    }
}

With this option angular compiler will automatically convert all relative links to absolute (=all links to images in compiled HTML and CSS code will start with http://localhost:3001). When the remote app is loaded inside the shell app the images will be loaded from the correct locations.
This is not a good solution when we need to build a project that can be deployable on any server, because this compiled code has absolute URLs hard coded and can only be deployed on the particular server. Another dissadvantage is if our remote app uses a lot of images, because hard-coded absolute links will make html/css files larger. Maybe in that case we can optimize the deployment process and deploy all the remote app assets to the shell server, so relative links will still work.
I think currently the most elegant solution to make the remote app deployable anywhere (not having to set the deployment url in advance) is to use dynamic link resolvement in our HTML and CSS code. For that a special global javascript variable __webpack_public_path__ comes handy. This variable is automatically defined by webpack in the project compilation process, and contains absolute URL to deployed server (that we can configure statically in advance or can be resolved dynamically at run-time based on browser URL address from where we loaded the remote app (=I think it gets resolved in the remote app remoteEntry.js, where the client-side JS code is aware of the absolute URL where it got downloaded from).
So, we can dynamically resolve absolute links to images in our remote app like this:
Angular component TS file:
@Component({
  templateUrl: './page1.component.html',
})
export class Page1Component {
  assetUrl = __webpack_public_path__;
}

Angular component HTML template:

If we have images inside our CSS files the solution is quite more tricky. Angular is possible to dynamically inject variables in CSS at run-time using @HostBinding decorator, but is not very convenient solution especially for injecting URL's for images:
Angular component TS file that will dynamicall handle it's CSS file:
@Component({
  styleUrls: ['./page1.component.scss'],
})
export class Page1Component {

  // CSS variable --imageUrl will be passed to CSS style declared in page1.component.scss.
  @HostBinding("style.--imageUrl") imageUrl = `url('${__webpack_public_path__}image.png')`;

}

CSS file:
.img {
  background-image: var(--imageUrl);
}

Disadvantage of this solution is that we must declare CSS variable for every different image we want to inject in the CSS. It would be much easier if we could just declare a base url path variable in TS file, and in CSS to append it to our image filename, like: background-image: url(var(--imageBaseUrl)/image.png);. This would throw compilation error because angular compiler (or mroe specifically css-loader in webpack, used by angular compiler) wants to resolve every url() function it finds in CSS files, and it won't understand how to resolve url(var(--imageBaseUrl)/image.png) (it will throw syntax error). I could not find a way we could tell the compiler to ignore this cases, css-loader is always used and we cannot configure it properly.
If you use many images in CSS files there is also a more elegant solution: put all styles that use images in your "global-remote" CSS file, where you can use relative links to images. When you deploy your remote app, browser will load the globa-remote CSS from http://localhost:3001/global-remote.css, and browser will automatically resolve all relative links relatively to localhost:3001. But for this to work you cannot use "scoped" CSS files from angular (=CSS files that are attached to angular component), because scoped CSS styles are compiled in JS code together with the component and are dynamically injected at-runtime to html DOM, so relative links to image will be resolved relatively to the shell app localhost:3000, not to the remote app). You have to compile this kind of CSS file separately, and include in your remote app separately:
To compile "remote-global" CSS separately, configure it in angular.json:
"build": {
  "options": {
    "styles": [
      {
        "input": "src/app/remote-global.scss",
        "bundleName": "remote-global" // Tell compiler to compile our style to remote-global.css
      }
    ],
...

Include this CSS in our remote app main App component (app.component.html):
<link [rel]="'stylesheet'" [href]="{{assetUrl}}remote-global.css">
Make sure also [rel] attribute is in brackets otherwise angular compiler will try to resolve href in compile-time and will throw syntax error. Compiler must ignore this <link> tag that must be resolved at run-time.
In app.component.ts define assetUrl variable that will resolve to absolute url of deployed remote app, like mentioned before:
@Component({
 templateUrl: './app.component.html',
})
export class AppComponent {
 assetUrl = __webpack_public_path__;
}

Comment: wow, the level of detail is high. good job


Stack column chart in PowerBI with date on x-asix and count on y-axis

Question: I have a data in below format and looking to get a stacked column chart as below. I am not sure how to club the dates and count together which are in multiple columns.
My data

I want to represent the above data in a clustered column chart where data on X-axis is clubbed in month and on Y-axis is clubbed with count of Yes per month like below based on different project types.
Answer: You will need to transform your data, add a Date table, add a relationship, and possibly a measure to do this.
1. Transform your data
You should unpivot your columns in PowerQuery to give you a table structure similar to this:

Project
Test
Date
Result

A
Test A
01/05/2023
Yes

Here is an example query to do this:
let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUTIw1Dcw1TcyMDIGciJTi4GkiT5QAMEFoVidaCUnKBuGDI31DcwQCkFKnEHC+hbIug2N9A0NUAQwdLkA2UbG+oaG6LYChVFEY2MB", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Project = _t, #"Test A Date Approved" = _t, #"Test A Result" = _t, #"Test B Date Approved" = _t, #"Test B Result" = _t, #"Test C Date Approved" = _t, #"Test C Result" = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Project", type text}, {"Test A Date Approved", type date}, {"Test A Result", type text}, {"Test B Date Approved", type date}, {"Test B Result", type text}, {"Test C Date Approved", type date}, {"Test C Result", type text}}),
    #"Unpivoted Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Project"}, "Attribute", "Value"),
    #"Date Filtered Rows" = Table.SelectRows(#"Unpivoted Columns", each Text.Contains([Attribute], "Approved")),
    #"Date Renamed Columns" = Table.RenameColumns(#"Date Filtered Rows",{{"Value", "Date"}, {"Attribute", "Test"}}),
    #"Date Replaced Value" = Table.ReplaceValue(#"Date Renamed Columns"," Date Approved","",Replacer.ReplaceText,{"Test"}),
    #"Result Filtered Rows" = Table.SelectRows(#"Unpivoted Columns", each Text.Contains([Attribute], "Result")),
    #"Result Renamed Columns" = Table.RenameColumns(#"Result Filtered Rows",{{"Attribute", "Test"}, {"Value", "Result"}}),
    #"Result Replaced Value" = Table.ReplaceValue(#"Result Renamed Columns"," Result","",Replacer.ReplaceText,{"Test"}),
    Merge = Table.NestedJoin(#"Date Replaced Value", {"Project", "Test"}, #"Result Replaced Value", {"Project", "Test"}, "ResultMerge", JoinKind.LeftOuter),
    #"Expanded ResultMerge" = Table.ExpandTableColumn(Merge, "ResultMerge", {"Result"}, {"Result"}),
    #"Changed Type1" = Table.TransformColumnTypes(#"Expanded ResultMerge",{{"Date", type date}, {"Result", type text}})
in
    #"Changed Type1"

2. Create a Date table
There are multiple ways to do this. For example, you can create a Calculated Table with the following DAX:
Dim Date = ADDCOLUMNS(
    CALENDARAUTO(),
    "Month", FORMAT([Date], "mmmm"),
    "Month#", MONTH([Date])
  )

Then right-click on this new Dim Date table and Mark as date table, select Date as the Date column. Next, select Month column and in the ribbon select Sort by column and select the Month# column.
3. Create a relationship
Now create a relationship between your Dim Date table to your test results table on the Date columns in each. It should look like:

4. Create your chart
Now you will be able to create your chart as show below. Select Show items with no data to see consecutive months.
Comment: Alternate powerquery would be  #"Unpivoted Columns" = Table.UnpivotOtherColumns(Source, {"Project"}, "Attribute", "Value"),
    #"Replaced Value" = Table.ReplaceValue(#"Unpivoted Columns","Date Approved","Date",Replacer.ReplaceText,{"Attribute"}),
    #"Split Column by Delimiter" = Table.SplitColumn(#"Replaced Value", "Attribute", Splitter.SplitTextByEachDelimiter({" "}, QuoteStyle.Csv, true), {"Test", "Attribute.2"})
    in  Table.Pivot(#"Split Column by Delimiter", List.Distinct(#"Split Column by Delimiter"[Attribute.2]), "Attribute.2", "Value")
Comment: Many thanks Sam, this is exactly what I wanted. Thanks again for your detailed explanation and clear steps.
Comment: Very nice @horseyride


Comandos do WEBPACK não funcionam

Question: instalei o webpack com o comando npm install webpack -g , porem quando tento usar o comando o webpack -h ou outro qualquer da esse problema
> PS C:\Users\renan\Desktop\Wchat> webpack -h The CLI moved into a
> separate package: webpack-cli Would you like to install webpack-cli?
> (That will run npm install -D webpack-cli) (yes/NO)

Apos da yes , aparece o seguinte erro
PS C:\Users\renan\Desktop\Wchat> webpack -h
The CLI moved into a separate package: webpack-cli
Would you like to install webpack-cli? (That will run npm install -D webpack-cli) (yes/NO)yes
npm WARN deprecated email@example.com:   Thanks for using Babel: we recommend using babel-prese
t-env now: please read babeljs.io/env to update!
npm WARN deprecated firstname.lastname@example.com: Package no longer supported. Contact email@example.com for more info.
npm WARN email@example.com No description
npm WARN email@example.com No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: email@example.com (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for email@example.com: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ firstname.lastname@example.com
updated 1 package in 45.313s
{ Error: Cannot find module 'webpack-cli'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at runCommand.then.result (C:\Users\renan\AppData\Roaming\npm\node_modules\webpack\bin\webpack.js:62:14)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7) code: 'MODULE_NOT_FOUND' }

Com esse erro fico inutilizado de usar os comando webpack , Alguem poderia me ajudar a resolver  ?
Aqui esta o package.json
{
  "name": "trabalhofinal",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.5.9",
    "express": "^4.16.3",
    "simple-peer": "^9.1.1"
  },
  "devDependencies": {
    "webpack": "^4.6.0",
    "webpack-cli": "^2.1.2",
    "webpack-dev-server": "^2.7.1"
  },
  "description": ""
}

Apos ajeitar o comando webpack apareceu o seguinte erro ao tentar fazer um bundle.js
webpack ./src/app.js ./public/bundle.js
Hash: 0ad17ada6fbd759751dd
Version: webpack 4.6.0
Time: 629ms
Built at: 2018-05-01 01:45:09
 1 asset
Entrypoint main = main.js
[0] ./src/app.js 23 bytes {0} [built]
[1] multi ./src/app.js ./public/bundle.js 40 bytes {0} [built]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

ERROR in multi ./src/app.js ./public/bundle.js
Module not found: Error: Can't resolve './public/bundle.js' in 'C:\Users\renan\Desktop\TrabalhoFinal'
 @ multi ./src/app.js ./public/bundle.js
PS C:\Users\renan\Desktop\TrabalhoFinal>

Comment: Bom, até aonde consta, ele foi instalado. [**Edite**](https://pt.stackoverflow.com/posts/295330/edit) sua pergunta e coloque o conteúdo do arquivo **package.json** .. Se não me engano, para instalar um pacote global, usa-se o comando `npm install -g pacote` e não `npm install pacote -g` pode ser ai aonde esta o problema
Comment: Tente remover ele: `npm uninstall -g webpack-cli` e instalar novamente: `npm install -g webpack-cli`
Comment: Editei e botei o packge.json amigo !
Comment: Amigo funcionou , porem apareceu outro problema ja editei a pergunta e botei ele, vc poderia dar uma olhada ?
Comment: Você deve abrir outra pergunta, pois trata-se de outro projeto, pois percebesse pelo diretório **C:\Users\renan\Desktop\TrabalhoFinal**
Comment: Obrigado pela ajuda NoobSaibot , muito obrigado mesmo , esta tudo funcionando !
Answer: Erro pode ter sido causado devido a ordem do argumento -g no comando, que segundo a documentação é:
npm install -g webpack-cli

diferente do Yarn que é:
yarn add webpack-cli -g

Referência

How to Install Global Packages

Comandos do WEBPACK não funcionam


Cannot read property 'join' of undefined

Question: Estou querendo consultar o array de um elemento que está dentro de um array através de um for..of e quero unir os elementos do array com a função join, mas estou recebendo o erro abaixo e não sei o porquê.
Erro:

Cannot read property 'join' of undefined

Código:

var usuarios = [{
    nome: "Lucas",
    habilidaes: ["JavaScript", "NodeJS", "MongoDB", "HTML", "CSS"]
  },
  {
    nome: "Rafael",
    habilidades: ["JavaScript", "Java", "MySQL", "HTML", "CSS"]
  }
];

function leitorHabilidades(usuarios) {
  for (usuario of usuarios) {
    console.log(
      'O ' +
      usuario.name +
      ' possui habilidade em: ' +
      usuario.habilidades.join()
    );
  }
}

leitorHabilidades(usuarios);
Comment: Você escreveu `habilidaes` em vez de `habilidades`
Answer: Isso é devido a um erro de digitação, você escreveu "habilidaes" em vez de "habilidades" no primeiro item do array
Na função também tem outro problema, você está buscando o "name" de cada usuário mas definiu como "nome"


Is the square root of a hyperbolic map hyperbolic?

Question: Suppose that we have an area preserving diffeomorphism of the $n$-dimensional torus,
$$f:\mathbb T^n \to \mathbb T^n,$$
such that the two-fold composition $f^2 := f \circ f$ is uniformly hyperbolic. That is, one has a splitting of the tangent bundle of $\mathbb T$
$$ T(\mathbb T^n) =  E_s \oplus E_u$$
and $\lambda \in (0,1)$ which satisfies the following, for all $x \in \mathbb T$,

invariance under $f^2$: $\qquad T_xf^2(E_s(x)) = E_s(f^2(x))$  and  $T_xf^2(E_u(x)) = E_u(f^2(x))$.
contraction on $E_s$: $\qquad\|D_xf^2|_{E_s(x)}\|_{op}<\lambda$.
expansion on $E_u$: $\qquad \|D_xf^{-2}|_{E_u(x)}\|_{op}< \lambda.$

($\|\cdot\|_{op}$ denotes the operator norm, $T_xf^2$ is the tangent map of $f^2$ at $x$ and $E_s(x)$ denotes the fibre $T_x(\mathbb T^n)\cap E_s$, for example).
Question: Must $f$ be uniformly hyperbolic too?
Answer: The answer is yes.

Let $M$ be  a compact $C^\infty$ manifold, $g:M\to M$ be a $C^1$ Anosov diffeomorphism. Thus there is a $(g,Tg)$-invariant topological splitting $TM=S(g)\oplus U(g)$ and for any $C^0$ fiberwise norm $|\bullet|$ on $M$ there are numbers $(C,\lambda)\in\mathbb{R}_{>0}\times ]0,1[$ such that for any $x\in M$ and any $n\in\mathbb{Z}_{\geq0}$ we have
\begin{align*}
S_x(g)=&\{\quad v\in T_xM\quad|\quad |T_xg^n v|\leq C\lambda^n|v|\quad\},\\
U_x(g)=S_x(g^{-1})=&\{\quad v\in T_xM\quad|\quad |T_xg^{-n}v|\leq C \lambda^{n}|v|\quad\}.
\end{align*}
Call $(C,\lambda)$ an Anosov pair for $g$ (with respect to $|\bullet|$) (see also What is the constant of hyperbolicity?). Note that $(C,\lambda)$ is an Anosov pair for $g^{-1}$ also.
For any $x\in M$ denote by $\mathcal{S}_x(g)$ and $\mathcal{U}_x(g)$ the global stable and unstable manifolds of $g$ at $x$, respectively. We have that $\mathcal{S}_x(g)$ and $\mathcal{U}_x(g)$ are injectively immersed $C^1$ submanifolds of $M$, $T_x\mathcal{S}_x(g)=S_x(g)$ and $T_x\mathcal{U}_x(g)=U_x(g)$, and they are uniquely defined by these properties. Further, if $d$ is the intrinsic distance function on $M$ defined by the fiberwise norm, then
\begin{align*}
\mathcal{S}_x(g)&=\left\{\quad y\in M\quad\left|\quad \lim_{n\to \infty} d(g^n(y),g^n(x))=0\quad\right\}\right.,\\
\mathcal{U}_x(g)=\mathcal{S}_x(g^{-1})&=\left\{\quad y\in M\quad \left|\quad \lim_{n\to \infty} d(g^{-n}(y),g^{-n}(x))=0\quad\right\}\right..
\end{align*}

Obs.: Let $f:M\to M$ be a $C^1$ diffeomorphism that commutes with a $C^1$ Anosov diffeomorphism $g:M\to M$, i.e. $f\circ g=g\circ f$. Then $f$ permutes the leaves of the stable foliation of $g$, that is,
$$\forall x\in M: f: \mathcal{S}_x(g)\to \mathcal{S}_{f(x)}(g).$$
Pf.: Let $x\in M, y\in\mathcal{S}_x(g)$. Then since $f$ is uniformly continuous
\begin{align*}
d(g^n(f(y)),g^n(f(x)))
=d(f(g^n(y)),f(g^n(x)))\xrightarrow{n\to\infty}0,
\end{align*}
that is, $f(y)\in \mathcal{S}_{f(x)}(g)$.
Applying the same argument to $g^{-1}$ we have that $f$ permutes the leaves of the unstable foliation of $g$ as well. Note that in this case we also have $T_xf : S_x(g)\to S_{f(x)}(g)$ and $T_xf: U_x(g)\to U_{f(x)}(g)$ by taking derivatives.
(For a general $g$ one can still define the global stable and unstable sets $\mathcal{S}_x(g)$ and $\mathcal{U}_x(g)$ as above, but they may fail to be injectively immersed submanifolds. In any event, if $f\circ g=g\circ f$, then again $f$ would permute the global stable sets of $g$ as well as the global unstable sets of $g$ (and vice versa).)

Claim: Let $p\in\mathbb{Z}_{\geq1}$ and  $f,g:M\to M$ be $C^1$ diffeomorphisms such that $f^p=g$. Then $f$ is Anosov iff $g$ is Anosov.
Pf.: First note that $f$ and $g$ (as well as any powers of them) commute. It's clear that if ($f$ is Anosov and) $(C,\lambda)$ is an Anosov pair for $f$, then $(C,\lambda^p)$ is an Anosov pair for $g=f^p$.
Conversely, suppose ($g$ is Anosov and) $(C,\lambda)$ is an Anosov pair for $g$. Let $x\in M,n\in\mathbb{Z}_{\geq0}, v\in S_x(g)$. There are unique numbers $Q\in\mathbb{Z}_{\geq0}$ and $R\in\{0,1,...,p-1\}$ such that $n=pQ+R$, so that $f^n=g^Q\circ f^R$. By the above observation $T_x f^R:S_x(g)\to S_{f^R(x)}(g)$. We have $Q=\frac{n-R}{p}$, so that
$$\lambda^Q\leq (\lambda^{1/p})^n \lambda^{-\frac{p-1}{p}},$$
and also
$$\left\Vert T_xf^R\right\Vert\leq \max_{R\in\{0,1,...,p-1\}}\max_{x\in M}\left\Vert T_xf^R\right\Vert \leq \max_{R\in\mathbb{Z}_{|\bullet|<p}}\max_{x\in M}\left\Vert T_xf^R\right\Vert\in\mathbb{R}_{>0},$$
which does not depend on $R,n$ nor $x$.
(Here $\mathbb{Z}_{|\bullet|<p}=\{-p+1,-p+2,...,0,...,p-2,p-1\}$.)
Then we have
\begin{align*}
|T_xf^n v|
&=\left|T_x\left(g^Q\circ f^R\right)v\right|
=\left|T_{f^R(x)}g^Q\left( T_x f^Rv\right)\right|\\
&\leq C\lambda^Q \left|\left( T_x f^Rv\right)\right|
\leq C\lambda^Q \left\Vert T_x f^R\right\Vert |v|\\
&\leq \left(C\lambda^{-\frac{p-1}{p}} \max_{R\in\mathbb{Z}_{|\bullet|<p}}\max_{x\in M}\left\Vert T_xf^R\right\Vert\right) \,\, (\lambda^{1/p})^n |v|.
\end{align*}
Since $f^{-n}=g^{-Q}\circ f^{-R}$, for $v\in U_x(g)$ the appropriate estimate holds and we get that $\left(C\lambda^{-\frac{p-1}{p}} \max_{R\in\mathbb{Z}_{|\bullet|<p}}\max_{x\in M}\left\Vert T_xf^R\right\Vert,\lambda^{1/p}\right)$ is an Anosov pair for $f$, whence $f$ is Anosov (and $S_x(f)=S_x(g)$ and $U_x(f)=U_x(g)$ for any $x\in M$).
(An alternative argument is to use a uniform modulus of continuity for $\{f^R\,|\, R\in \{0,1,...,p-1\}\}$) to show that the global stable sets $\mathcal{S}_x(f)$ and $\mathcal{S}_x(g)$ coincide.)
Corollary: Let $M$ be a compact $C^\infty$ manifold, $f\in\operatorname{Diff}^1(M)$ be a $C^1$ diffeomorphism. Denote by $f^\mathbb{Z}=\{f^p\,|\, p\in\mathbb{Z}\}$ the subgroup of $\operatorname{Diff}^1(M)$ consisting of all iterates of $f$. Then $f^\mathbb{Z}$ contains an Anosov diffeomorphism iff $\forall p\in\mathbb{Z}\setminus0: f^p$ is an Anosov diffeomorphism.


Angular material multiple items drag drop

Question: I'm using angular material for dragging an item from one list to other.
Attaching the code: https://stackblitz.com/angular/mdgkpprxjej?file=src%2Fapp%2Fcdk-drag-drop-connected-sorting-group-example.ts.
My issue is that I'm able to move only a single item across the lists. Is there some way to select and drag multiple items?
Answer: I think this is achievable. However, it requires too much work. You can take a look at  this issue on GitHub. KevynTD explained well to achieve this using Angular cdk.
Comment: Yes, That's quite complex. I'm looking for something simple. But, I can still give a try.
Comment: Unfortunately, I don't think there is an easy way...


Nginx Reverse Proxy Will Not Load HTTPS Sites

Question: Today has been the first time I've used Nginx. I got it set up as a dedicated reverse proxy by following a few guides. This is what I'm trying to recreate - http://www.integratedwebsystems.com/wp-content/uploads/2010/06/reverse_proxy.jpg
I have it working fine with port 80 but anything loaded over HTTPS gives me errors about HTTP content being insecure. Trying to load any HTTPS site over the reverse proxy via the internet looks very wrong. Loading it internally works just fine.
Example - https://i.stack.imgur.com/90Mfc.png - That is supposed to be the Wordpress admin console, it looks like something out of the 90s.
Below is the nginx config I'm using -
server {
   listen 80;
   server_name domain1.com;
   location / {
      proxy_pass http://192.168.1.149/;
      proxy_set_header Host $host;
   }
}

# HTTPS server

server {
    listen 443 ssl;
    server_name domain1.com;

    error_log /tmp/error.log;

        ssl on;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    ssl_certificate /etc/nginx/ssl/server.crt;

    location / {
        proxy_pass http://192.168.1.149/;
        proxy_set_header Host $host;
    }
}

Can anyone advise me on what I'm missing to get HTTPS working correctly over the reverse proxy?
Comment: FWIW, the raw look of the page is caused by the browser refusing to load the CSS via plain HTTP when the HTML was retrieved via HTTPS.
Answer: You're not missing anything; you configured nginx correctly.
The problem here is that WordPress thinks it should be generating HTTP links. When you try to access it via HTTPS, it still generates all of its links with http:// and thus they can't be loaded (without explicitly loading insecure content in the browser).
There are WordPress plugins that will convert your admin console to https, if that is what you are trying to do. You could also edit your blog's General Settings and convert the entire site to https quickly and easily, without a plugin.
Comment: Thanks for the quick response. It feels like something is still a little off. Loading the Wordpress site directly from the server I can access the whole site off of https without a problem.

Earlier I installed this HTTPS plugin to wordpress and told it to force https on the admin console but it didn't make a difference - http://wordpress.org/plugins/wordpress-https/
Comment: There probably is something still a little off. But you didn't describe the other server. So it's hard to say.
Comment: The Nginx error logs give this for 443 connections -

2014/06/18 17:22:38 [error] 1639#0: *15 upstream prematurely closed connection while reading response header from upstream, client: 50.83.1X6.1X3, server: domain1.com, request: "GET /favicon.ico HTTP/1.1", upstream: "https://192.168.1.149:443/favicon.ico", host: "domain1.com"
Comment: The other internal webservers are all running Apache2 on Ubuntu server.
Answer: If you can afford it, you can try re-encrypting the traffic:
location / {
    proxy_pass https://192.168.1.149/;
    proxy_set_header Host $host;
}

The appserver will then be aware of the SSL, obviously.
Another way is to configure an alternate Apache port, e.g.
location / {
    proxy_pass http://192.168.1.149:444/;
    proxy_set_header Host $host;
}

with a vhost that sets appropriate flags to make Wordpress/PHP believe that the request had actually been encrypted, e.g.
SetEnv SSL=on

It can be tricky to catch all necessary/sufficient settings.


Show that a set of all limit points of subsequences is closed

Question: Assume $(x_n)_{n\in\mathbb{N}}\in\mathbb{R}^\mathbb{N}$ and consider the set:
    $$E:=\{x\in\mathbb{R}, \text{there exists a subsequence of $(a_n)_{n\in\mathbb{N}}$ converging to $x$.}\}$$
Show that $E$ is closed.
I can think about three situations, two of which are easy to prove.
The first, $E$ is empty. The second, $E$ has one element. The third, $E$ has more than one element. I'm struggling to prove the third.
I think that I might be misunderstanding what the set E is.
Answer: Assuming $x\not\in E$, there must be an open set $U$ with no element of $(x_n)$ contained in $U$.  That is, $U\cap (x_n)=\emptyset$.  Hence $U\cap E=\emptyset$.  Hence $\Bbb R\setminus E$ is open.
Comment: Well, if not then for every $U_n=(x-\frac1n,x+\frac1n)$, we have an element $a_n$ of $(x_n)$ with $a_n\in U_n$.  So $(a_n)$ is a subsequence of $(x_n)$ with $a_n\to x$.  So $x\in E\,\Rightarrow \Leftarrow $.
Comment: Thanks. Why does $U$ must exist?
Comment: And I'm not entirely clear on why $U$ is open..
Comment: There has to be at least one such open $U$,  or else we arrive at the contradiction outlined above.


why in can't activate SCAYT functonnality

Question: *Hi everybody i have a probleme with scayt plugin for ckeditor 4 when i enable the scayt check speller the button appaer but i can active the functonality for check spelling i am on IE 11.0.9600.19080.
that my conf in config.js :
config.allowedContent = true; //Allow all content
   config.disableNativeSpellChecker = false; //Enable native spell checking      (browser)
    config.scayt_autoStartup = true; // Enable SCAYT on editor startup
    config.scayt_sLang = 'fr_FR';
    config.extraPlugins = 'scayt';
    config.toolbar =
        [
            [ 'Find','Replace','-','SelectAll','-','Scayt' ]]

Thanks for reply*
Answer: You can start from simple demo and add all additional options step by step if you need.
CKEDITOR.config.toolbar = [{
    name: 'editing',
    items: ['Scayt', 'Cut', 'Copy', 'Paste', 'Bold', 'Italic', 'Underline']
}];

CKEDITOR.replace('container', {
    scayt_autoStartup: true,
    grayt_autoStartup: true
});

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