Avoid overlapping between a Dijit Menu and its target div

Question: I have the following code example in fiddle.net here of a Dijit.Menu and a div.
The Menu appears with a left click, my problem is that the Menu overlaps (or covers, hides) the content of the target div and users cannot read its content when making comparisons with the alternatives presented in the Menu, see the figure below.

So is there a way to make the Menu appear without overlapping the div content, so that the div content could be seen while browsing the menu items, maybe positioning the menu below or above the div, as in the following figure.
Comment: What do you mean overlap, the menu nature is to appear on top of anything? can you explain more I can't see what do you want or where is the issue ??
Comment: I add more details, hope this helps, thanks.
Answer: You can use TooltipDialog, here is a jsfiddle based on the one you provided.
Answer: This can be achieved with some javascript attached to the onOpen event that is triggered when the popupMenu is shown.
The code should get the position and the height of the clicked element and calculate the position where the menu should be placed:

x: is the x position of trigger element
y: is the y position summed up with the height of the trigger element

Use these coordinates to set the left and top style attributes of the popup menu holder element:
pMenu.connect(pMenu, 'onOpen', function () {
    var position = dojo.position(this.currentTarget, true);
    domStyle.set(this.domNode.parentNode, {
       left: position.x + "px",
       top: (position.y + position.h) + "px"
    });
});

Here is a jsfiddle with the popup menu positioned as in your image


Any way to filter IP's when logging queries? (BIND 9.3)

Question: I would like to record queries to my DNS from a particular ip. Is this possible?
Right now I have this:
channel query_log {
                file "/var/named/data/queries.log" versions 2 size 1G;
                severity debug 3;
                print-category yes;
                print-severity yes;
                print-time yes;
        };

category queries { query_log;};

As you may imagine, the file "queries.log" grows at an extremely fast rate on our busy network.  I just would like to log the queries from a particular ip.  Is there a way to do this using any channel option?  I thought about creating a separate view (to match the host I want to record) but you can oly have one "logging" option in named.conf (not inside the views) :(
Thanks.
Answer: I do not think there is any way that you can configure bind to do the filtering you want.
I can think of two ways you could achieve the result I believe you want.
Setup bind query logging, keep only 1 versions, and reduce the size of the logs you are keeping.
Leave a command like below running to constantly monitor changes to the query log and store the information you want to save to a separate file.
tail --follow --retry /var/named/data/queries.log \
      | grep 'ip.ad.dd.res' > /var/named/data/queries_ip.ad.dd.res.log

The second method would be to just use tcpdump to capture all incoming requests from that host.  You would use a command like this.
tcpdump -n dst port 53 and src host ip.ad.dd.res > /var/log/dns_ip.ad.dd.res.log

Comment: Thanks again Zoredache.  The tail idea sounds good and that's what I'm going to do then.  I thought about tcpdump but I wanted to see if it was possible using BIND (I like the format of the query log that BIND produces) and thought that maybe there was some switch I was missing but indeed it seems there's no way to perform the filtering natively.  Thanks again!


Calculate $\int\int_S\vec F\cdot\vec ndS$, where $\vec F(x,y,z)=-z\vec k$ and $S$ is the part of $x^2+y^2+z^2=4$ outside of the cylinder $x^2+y^2=1$

Question: Calculate $\int\int_S\vec F\cdot\vec ndS$, where $\vec F(x,y,z)=-z\vec k$ and $S$ is the part of the sphere $x^2+y^2+z^2=4$ outside of the cylinder $x^2+y^2=1$, with $\vec n$ pointing out of the sphere.
Answer: $-4\pi\sqrt3$
My attempt:
$x^2+y^2+z^2=4$
$x^2+y^2=1$
$1+z^2=4$
$z^2=3$
$z=\pm\sqrt3$
$2\cos\phi=\pm\sqrt3$
$\phi=\pm\cos^{-1}\frac{\sqrt3}{2}=\pm\frac{\pi}{6}$
$\vec r(\phi,\theta)=(2\sin\phi\cos\theta,2\sin\phi\sin\theta,2\cos\phi)$
$\frac{\pi}{6}\leq\phi\leq\frac{5\pi}{6},0\leq\theta\leq2\pi$
$\vec r_{\phi}\times\vec r_{\theta}=4\sin^2\phi\cos\theta\vec i+4\sin^2\phi\sin\theta\vec j+4\sin\phi\cos\phi\vec k$
$\int\int_S\vec F\cdot\vec n dS=\int_{\pi/6}^{5\pi/6}\int_0^{2\pi}(0,0,-1)\cdot(4\sin^2\phi\cos\theta,4\sin^2\phi\sin\theta,4\sin\phi\cos\phi)4\sin\phi d\theta d\phi$
$=\int_{\pi/6}^{5\pi/6}\int_0^{2\pi}-16sin^2\phi\cos\theta d\theta d\phi$
$=0$
I'm not sure if the bounds of $\phi$ are correct or if even I should be using spherical coordinates, but beyond that everything else seems right to me, help me understand what is going wrong here.
Comment: Where did the $(0,0,-1)$ come from? P.S. Your limits seem fine.
Comment: It's the coordinates from the vector field, but now I realize that's in cartesian coordinates, I forgot to change to spherical coordinates, but I think changing wouldn't change the result since the inside integral still 0.
Comment: It's $-z\vec k$, isn't it?
Comment: Yes, that's right.
Answer: Let $R=2$ (sphere) and $r=1$ (cylinder).
$$\vec{F}=(0,0,-z)$$
$$\vec{n}=\frac{(x,y,z)}{R}$$
$$\vec{F} \cdot\vec{n}=-\frac{z^2}{R}$$
$$dS=R \ d\phi dz \text{ (cylindrical coordinates)}$$
$$\int\int_S\vec F\cdot\vec ndS=\int _{-\sqrt{R^2-r^2}}^{\sqrt{R^2-r^2}}\int _0^{2 \pi }\vec{F}\cdot\vec{n}\ R d\phi dz=\int _{-\sqrt{R^2-r^2}}^{\sqrt{R^2-r^2}}\int _0^{2 \pi }-z^2\ d\phi dz=-\frac{4}{3} \pi  \left(R^2-r^2\right)^{3/2}$$
$$-\frac{4}{3} \pi  \left(R^2-r^2\right)^{3/2}|_{R=2,r=1}=-4 \sqrt{3} \pi$$


For what $x>0$ series $\sum_{n=1}^{\infty} x^{1+\frac{1}{\sqrt2}+\frac{1}{\sqrt3}...+\frac{1}{\sqrt n}}$ is convergent?

Question: For what $x>0$ series $\sum_{n=1}^{\infty} x^{1+\frac{1}{\sqrt2}+\frac{1}{\sqrt3}...+\frac{1}{\sqrt n}}$ is convergent?
By logarithmic test,
$$ \lim_{n\rightarrow \infty}\left(n \log\frac{u_n}{u_{n+1}}\right)$$ is infinite for $0<x<1$. So for $x\in (0,1)$, series is convergent. Am I correct? Thanks.
Answer: Since the sum $\displaystyle\sum_{k=1}^n\,\frac{1}{\sqrt{k}}$ is well approximated by $2\sqrt{n}$, the required series is convergent iff the series $$\sum_{n=1}^\infty\,x^{2\sqrt{n}}$$ is convergent.  Since $$\int_0^\infty\,\exp\big(-\alpha\sqrt{t})\,\text{d}t=\frac{2}{\alpha^2}<\infty$$ for all $\alpha>0$, the required series is convergent for all $x\in(0,1)$ by the Integral Test.  Surely, if $x\geq 1$, the required series is divergent.  Ergo, you are correct.
Comment: Let $\alpha:=-2\,\ln(x)>0$ if $0<x<1$, so that $x=\exp\left(-\frac{\alpha}{2}\right)$.  Then, the series $\sum\limits_{n=1}^\infty\,x^{2\sqrt{n}}$ is convergent if and only if the said intgral is convergent.
Comment: Why do you compute $\int_0^\infty\, e^{\big(-\alpha\sqrt{t})}\,\text{d}t$ ?
Comment: oh i got it. Tnx
Answer: By comparing with an integral, you can see that the exponent
$$\sum_{k=1}^n \frac 1 {\sqrt k} \approx 2\sqrt{n}$$
so the series converges iff $|x|<1$.
Answer: Yes you are true.$$$$
First if $x\ge1$ then $x^{1+\cdots+\frac{1}{\sqrt n}}\ge x\ge1=>$ sum divergent.$$$$
Second if $0<x<1$.
$$
\\1+\frac{1}{\sqrt2}+\cdots+\frac{1}{\sqrt{n}}\ge \frac{1}{\sqrt{n}}+\cdots+\frac{1}{\sqrt{n}}=\frac{n}{\sqrt{n}}=\sqrt n=>
\\x^{1+\cdots+\frac{1}{\sqrt{n}}}\le x^{\sqrt{n}}
\\\lim_{n\to\infty}\frac{\ln\frac{1}{x^\sqrt n}}{\ln n}=\lim_{n\to\infty}\frac{\sqrt{n}}{\ln n}\cdot \ln (\frac{1}{x})>1=>
$$
sum convergent.
https://ru.wikipedia.org/wiki/Логарифмический_признак_сходимости


What happens after eleven kicks from the penalty mark?

Question: On April, 20 2017) Besiktas and Lyon took eight (8) kicks from the penalty mark each.
What would have happened if the balance had kept up to the eleventh (11th) kicks?
Which player would have taken the twelvth (12th) kick?
Answer: In penalty shootouts in association football, a format of sudden death is followed if after 5 penalty shots each, the scores are still tied. If the number exceeds 11* penalty kicks each without a winner, all players become eligible to take a second penalty kick. The order of penalty kick takers can be changed, but all 11* players must take a second kick before any player can take a third kick, if required.
From the IFAB Laws of the Game, Section 3. Kicks From The Penalty Mark

If, after both teams have taken five kicks, the scores are level kicks continue until one team has scored a goal more than the other from the same number of kicks.
Each kick is taken by a different player and all eligible players must take a kick before any player can take a second kick.
The above principle continues for any subsequent sequence of kicks but a team may change the order of kickers.

Such an incident took place in the quarter finals of the 2006 Africa Cup of Nations between Cameroon and Ivory Coast. Each of the first 11 penalty kicks were converted by both teams. Samuel Eto'o, who took the first penalty kick for Cameroon, took the twelfth spot kick and missed. Didier Drogba, who took the first penalty kick for Ivory Coast, took the twelfth spot kick and scored, thus winning the match.
This article lists the interesting records pertaining to penalty shootouts. Some interesting ones:

In domestic high level competition, the record for most penalty kicks taken was set by KK Palace and Civics in the first round of the 2004/05 Namibian Cup, with KK Palace winning 17-16 after 48 penalty kicks (24 kicks per team).
The highest score in a penalty shootout was 20-19 set in the 1988/89 Argentine Championship match between Argentinos Juniors and Racing Club, with Argentinos Juniors winning after 44 penalty kicks (22 kicks per team).
The record in domestic amateur football is 52 kicks.  It happened in the 5th tier of Czech football in 2016; Batov beat Frystak 21-20.  See the video.

* Note: In case one of the teams has less than 11 players on the pitch at the time of the penalty shootouts, either due to red cards or injuries, the other team must exclude as many players as required to equate the number of penalty kick takers. This is done to ensure that the team's 11th spot kick is not taken by the best player of the team with the sent off player, giving them an advantage against the weakest player of the team with a fuller squad. In such a scenario, the 11th penalty kick will be taken a player who has already taken one spot kick earlier.
Comment: Also, it would be stronger if the number 11 was disregarded when reciting the general principle, as in [Yosef's answer](https://sports.stackexchange.com/a/16003/3526). 11 is only applicable here because both teams had 11 players left on the field at the end of the match. The general principle is that no eligible player takes a second kick until all kickers have had their first kick.
Comment: This answer is strong, but could be even stronger with a reference to the [Laws of the Game](http://theifab.com/laws).
Answer: From the Laws of the game:

 - Each kick is taken by a different player and all eligible players must take a kick before any player can take a second kick.
- The above principle continues for any subsequent sequence of kicks but a team may change the order of kickers.

So if it had gone past 11 they have to repeat kickers but the team is allowed to change the order of their 11 kickers.


relationship between function and Function

Question: I`m really wondering about the relationship between function and Function..
i read that article "function inherit the methods of Function", so can function use the methods like apply, bind, call, etc
so i checked in the console, using the code below.
function test(){} // statement
test.__proto__ // function(){[native code]}

ah.. if "function inherit the methods of Function" is true,
why is the outcome function(){[native code]}, not the function Function(){[native code]}?
also i`ve checked that the constructor of function test is function Function,
even makes me confusing..
its so weird.. need some help..
Comment: `test.__proto__ === Function.prototype`. The article you read was slightly wrong. It should have said `Function.prototype`.
Comment: thanks a lot. i was wondering about that point if the article is wrong.
Answer: a.__proto__ is the prototype.
a.__proto__.constructor is Function

function a() { }
console.log(a.__proto__);
console.log(a.__proto__ === Function);

console.log(a.__proto__.constructor);
console.log(a.__proto__.constructor === Function);

a.__proto__ is pretty much an anonymous function for initializing.
Comment: but both the outcome of Function.prototype and Function.__proto__ are same, both the outcome function(){[native code]}.
so does the user_defined function actually inherit the methods of function(){[native code]}, not the Function?? is that the article what i`ve read wrong?
Comment: @jwkoo This is a bit tricky to understand, but `Function` is a function itself, meaning that it, too, inherits from `Function.prototype`. It's a bit special in that way.
Comment: @4castle aha ! i understand.. thanks a lot. so please let me check..
both the Function.__proto__ and user-defined function.__proto__ have same outcome, so Function includes the many user-defined function, anyway all of them inherit the property of function(){[native code]}?
Comment: @jwkoo You got it!
Comment: @jwkoo Any of the fundamental, built-in components generally kind of play by different rules (namely Function and Object), since they are themselves as well. It's weird. =p
Answer: test is created using the constructor Function, what test__proto__.constructor will return
the prototype of test is function () { [native code] } from where is is inheriting (what test.__proto__), and that is why you are able to access
test.<some property name> whose are actually property of function () { [native code] }
Answer: Both function test() {} and new Function(), output function ... and not Function ... in the console, so it is still consistent. That they do it this way is a historical reason, it reflects more what you normally see in the source code.

console.log(new Function() );
console.log(function test(){} );


Possible to ssh into a server without using -i flag for key?

Question: I have 3 EC2 instances and they all use the same private key. I'm setting up a hadoop cluster between these nodes and they require passwordless entry for this to work.
How can I use this private key to easily ssh into the servers with keyless entry?
The only thing I have is a .pem file. I've scp'ed the file into the master server.
Answer: You want to create a ~/.ssh/config file with the necessary entries. The equivalent of the -i command line option is the IdentityFile command in the configuration file.
Host my.domain.com
  HostName other-name
  User me
  PreferredAuthentications publickey
  Port 2222
  IdentityFile /home/me/.ssh/other_keys/other_id_rsa

More info about the configuration file can be found in man ssh_config.
IMPORTANT NOTE: If you are to use many such keys, place them in a sub-directory otherwise you will get failures because ssh tries to login with all the keys found directly under ~/.ssh. However, most servers will accept 3 to 5 attempts. More keys in the .ssh folder and it is likely to fail many login attempts unless you use the -i option or the configuration file.
Comment: @coderkid, if that's your solution then you may want to click on the big checkmark on the side of the answer to mark it as the one that made it work for you.


Merge video files with their original audio in iOS

Question: I need to merge two video files along with their corresponding audio.
I tried using :
http://www.raywenderlich.com/13418/how-to-play-record-edit-videos-in-ios
The videos gets merged, but their audio is missing. It's like a muted video. I need the audio also to be merged. I also googled on this, couldn't find anything useful. Can someone help me on this please...
Answer: Live-editing audio is exactly like live-editing video. Go back to each movie and fetch the audio track and stick it into your mutable composition.
In this example, I grab the first five seconds of video and the last five seconds of video from a movie and put them one after the other in a new video:
NSString* type = AVMediaTypeVideo;
NSArray* arr = [oldAsset tracksWithMediaType:type];
AVAssetTrack* track = [arr lastObject];
CMTime duration = track.timeRange.duration;
AVMutableComposition* comp = [AVMutableComposition composition];
AVMutableCompositionTrack* comptrack = [comp addMutableTrackWithMediaType:type preferredTrackID:kCMPersistentTrackID_Invalid];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeMakeWithSeconds(0,600), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(0,600) error:nil];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeSubtract(duration, CMTimeMakeWithSeconds(5,600)), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(5,600) error:nil];

But the resulting video would be silent. So I also go back and fetch the corresponding audio:
type = AVMediaTypeAudio;
arr = [oldAsset tracksWithMediaType:type];
track = [arr lastObject];
comptrack = [comp addMutableTrackWithMediaType:type preferredTrackID:kCMPersistentTrackID_Invalid];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeMakeWithSeconds(0,600), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(0,600) error:nil];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeSubtract(duration, CMTimeMakeWithSeconds(5,600)), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(5,600) error:nil];

Comment: 'AVMutableCompositionTrack *AudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];'
'[AudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, firstAsset.duration) ofTrack:[[firstAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];'

'AVMutableCompositionTrack *secondTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
// do same thing for another track , like this : **[secondTrack insertTimeRange:....**


querySelector returns 'Failed to execute div is not a valid selector' when it exists in the DOM

Question: I'm running into an issue where the 'div ID' isn't valid when I run it from the code.
However, when I document.querySelector('#div-gpt-ad\\/1594654184865-0>div') it returns the correct div ID.
Screenshot of error: https://gyazo.com/a7f1898f246bd84f28e85c2052ac60eb
The div id exists on page before executing the code, the console.log in the renderDiv function returns
Here is the code I'm trying to execute:
var slots = window.top.googletag.pubads().getSlots();

init(slots);
function init(slots) {
    for (let i = 0; i < slots.length; i++) {
        renderDiv(slots[i]);
    }
}
function getSelectors(slot) {
    var escapeCheck = slot.getSlotElementId();
    if(escapeCheck.includes('/')){
       let placeHold = escapeCheck.replace(/\//g, '\\\\/');

        return  "#" + placeHold + ">div" ;
    } else{
    return "#" + escapeCheck + ">div";
}
}
function renderDiv(slot) {
        let selector = getSelectors(slot);

        console.log("Selector:" + selector)
       document.querySelector(selector)

}

Comment: Try `console.log('#div-gpt-ad\\/1594654184865-0>div')` and spot the differences with what `console.log("Selector:" + selector)` is logging. Looks like your escaping is going wrong.
Comment: I see, this returns 'undefined' I think this is 1 step closer to where I need to be!
Comment: Nvm, this gives no difference. They're both the same
Answer: Fixed!
Changed let placeHold = escapeCheck.replace(/\//g, '\\\\/');  to
let placeHold =escapeCheck.replace(/\//g, "\\/").replace(/\./g, "\\.");

Something I quite don't understand yet is why the first one did not work as the string was correct that was passing through
Comment: "_as the string was correct that was passing through_" No it wasn't. In the selector that was working, you passed `\\/`. In your replacement you replaced it with `\\\\/`. That's not the same amount of backslashes.


Open sets and intersections

Question: Suppose $G$ is an open subset of the real number that is not upper bounded. Is there a real number $x > 0$ such that the set of all integer multiples of $x$ intersects $G$ at infinitely many points?
That is, is it true that $\exists x \in \mathbb{R}$ such that $\{mx\mid m\in \mathbb{Z}\}\bigcap G$ is infinite?
My intuition tells me yes, since the fact that $G$ is not upper bounded seems to be a major factor here, but I can't seem to prove it.
Comment: $G$ is open means $G$ is a countable union of open intervals. If $(a,\infty ) \subset G$ or $G$ admits a subsequence of open interval with bounded below diameter, things are easy.
Comment: Is $G$ a subset of $\mathbb R$?
Comment: Could you explain more?
Comment: Yes, I made an edit to the question I asked. It should be slightly clearer now.
Comment: i think its, $G \subset \mathbb{R}$ does $\exists~ (x \in \mathbb{R}) > 0 ~s.t~ A = \{ax | a \in \mathbb{Z}\}$ with $A \cap G$ being infinitely large.
Comment: What is your proof
Comment: If x was rational in the question, answer was no.
Comment: just spitballing here, but if such an x exists, and since the Reals are a well ordered chain, couldnt you just use open balls around x to make a countable ordering?
Comment: Where is $G$ being open used here?
Comment: It's false if $G$ isn't open. Let $G=\{c^k, k\in \mathbb{N}\}$ with $c > 1$ and $c$ transcendental.

Let $x \in \mathbb{R}, p>q, m>n \in \mathbb{N}$ such that $px = c^m$ and $qx = c^n$. Then $\frac{p}{q} = c^{n-m}$ which is a contradiction.
Answer: Yes. Suppose $\nexists x$ such that $\{nx:n\in\mathbb{Z}\}\cap G$ is infinite, then for any $\epsilon>0$, $\{n\epsilon:n\in\mathbb{Z}\}\cap G$ is finite.
Let $n_0 = \max \{n \in\mathbb{Z}:n\epsilon \in G\}$.
Take $a\in G$ such that $a > n_0\epsilon$. $[\because G$ is unbounded above$]$.
Let $S = \{x \in G: (a,x) \subset G\}.$ $S\ne \phi$ as $G$ is open.
Let $b=\sup S$.
So $(a, b) \subset G$. Then $|b-a|<\epsilon$ also implies $b=a$. We have arrived at a contradiction.
Comment: Would you mind to suggest how does $|b-a|<\epsilon$ imply $b=a$?
Comment: As $\epsilon$ is arbitrarily small.
Comment: As you choose $n_0$ you implicitly fix an $\epsilon$ already, thus your $a$ and things else too depends on $\epsilon$.
Comment: I understood the problem with $\epsilon$. There is a glitch in the proof. I'll try to mend it.

Open sets and intersections


C# HttpWebRequest response error (401)

Question: Please excuse me if I look as though I'm doing something stupid here.  I've tried browsing other stack overflow questions for the answer to my issue, yet do not seem to be getting anywhere.
I'm working on a dotnet core MVC application and wanting to return some data from a remote server.  I am using the HttpWebRequest class.
In Fiddler I executed the following using the composer.

As you can see its a simple GET request with two cookies passed in the header.
This works great and returns me exactly what I need.
I then compose my request in the dotnet world as follows:
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

 request.CookieContainer = new CookieContainer();

 request.CookieContainer.Add(new Cookie("name", "value", "/", "localhost"));

(did not include second cookie for purpose of question)
I then call:
var httpResponse = (HttpWebResponse)request.GetResponse();

Yet receive 'The remote server returned an error: (401) Unauthorized'
Any ideas what I'm doing wrong here? I tried to add the following line of code for testing purposes, but still no luck.
request.ServerCertificateValidationCallback = delegate { return true; };

All answers appreciated.  Plus as I mentioned, I'm no expert so I could just be doing something daft!
James
Comment: Can you use fiddler to look at the request that is being produced from the C# code? How is it different from the working request you produced in fiddler?
Comment: Is your request url going to localhost? You've set the cookie to only be delivered to the localhost domain.
Comment: Hi @Ed T thanks for your comment.  I did what you said and changed this to the correct domain and...bingo! it worked.  Should have spotted that one!  Turn this into an answer and i'll up vote and mark this as the answer.  James
Comment: Can you post the rest of the controller action?
Comment: @JamesSherburn, glad to help. Answer posted.
Answer: I think your request is defaulting to POST, but your Fiddler example is doing a GET.
Try adding:
            request.Method = "GET";
            request.ContentType = "text/xml; encoding='utf-8'";

Comment: Hi @Scrappydog just out of interest I also tried this, yet it didn't make a difference.  The request still processed as a GET.  I guess there is no harm in making this explicit though, so I'm up voting.
Answer: In the Cookie constructor, you are setting the cookie's domain as "localhost" which means it will only be delivered to requests to the localhost domain. It should be set to the domain you are actually sending the request to.

C# HttpWebRequest response error (401)


2 Heads on one Cab?

Question: I have two Half stacks, one Marshall and one Kustom. My question is can I plug the two heads into each cab?
What I want to end up doing is have an ABY switch from my guitar straight to the Marshall head, and then the other goes to an effects processor, and have sound coming from both cabinets at the same time.
Are there any problems that I could/will face having 2 heads into a single cab? And should I just go with the ABY switch to each half stack as it is
I want to be able to use one head at a time. When I'm playing some nice classic rock, have my switch to the Marshall head, and then if I come up on a song that needs effects switch over to the kustom head that has an effects processor on it. So one Head driving  both cabs at the same time, only one head at a time.
The stacks I have are:
Marshall 1987xl 1960bx
Kustom 100HD kustom 4x12 cab
anything else that you need to know just ask and I'll try and provide the info.
Thanks
Answer: WARNING: Do NOT plug both heads into the same cabinet as it can do serious damage to the heads.
The trick of re-wring the cab so that you have two independent sets of two speakers will work fine. However I would recommend doing the left column and right column and not the bottom or top row. The bottom row sits very low so as a player you will not get any high frequencies. It will sound very dull to your ears (but it's screaming at your ankles), while your audience is probably already writhing in pain. Even the top row is actually not high enough unless you get at least 6' away from your cab.
If you chose to do this, you need to analyze the wiring for impedance. If your cab is rated 4 Ohms than you either have 4x16 Ohm drivers in parallel or 4x4 Ohm drivers in a serial/parallel configuration. If it's the first: wire the two speakers in parallel. If it's the second, wire the two speakers in series. In either case you will get 8 Ohm impedance (which is fine). If you get this wrong, you'll either end up with 32 Ohms (very low sensitivity) or 2 Ohms (likely to damage the head), so some care is advised.
There is a device that will actually do all the required switching for you (including multiple heads and/or cabs). See http://www.soundsculpture.com/products/headtrip.htm
Answer: This can be straightforward, the one caveat its that you can't wire both heads to the same speakers in a cab.
So what you could do is wire one head to 2 speakers in a cab, and have the other head wired to the other two speakers.
It isn't ideal though- it's usually better to keep them apart. Is there a reason you want to do this?
Comment: I was curious being there are 2 inputs on both cabs.. I like the sound I get from 2 cabs vs 1, but I only want one head operating at a time Thats why I would have the ABY switch on there.. So one head for 8 speakers, and then use the switch and it would be the other head driving them.
Comment: Oh, I see- that would be really easy then. I thought you meant both at the same time.
Answer: I use sort of the same set up live. I use an ABY box, 1 output goes to my marshall JCM900 head into a 1960 JCM800 - 4x12 cabinet, wired for 16ohms, most marshall heads are able to switch between 4,8, & 16 ohms. The other output goes to a marshall MA100 head into a peavy 4x12 cabinet at 8 ohms. The JCM900 is my lead or overdrive channel, the MA100 is my clean channel. I prefer to use 1 cabinet per head, but that's my preference. The main thing I always make sure happens is that the cabinets match the heads ohms. Ive tried two 4x12 cabs @ 8ohms each setting the jcm900 @ 4ohms. wasn't much louder or didn't seem louder. I'd go with one cab for each head but that's just me. Good luck.

2 Heads on one Cab?


Reactive ggplot with Shiny-

Question: Hi community
Im try to make a reactive Shiny app.
When I select the name "Lugar" appear the plot. Im have the code of the each plot that in need but dont run well in shiny.
library(readxl)
library(tidyverse)
library(shiny)

server <- function(input, output, session) {

  precip = read_excel("meses2.xlsx", sheet="F")
  #Summarize Data and then Plot
  data <- reactive({
    req(input$sel_Lugar)
    df <- precip %>% filter(Lugar %in% input$sel_Lugar) %>%  group_by(Mes) %>% summarise(precip = sum(Medicion))
  })

  #Update SelectInput Dynamically
  observe({
    updateSelectInput(session, "sel_Lugar", choices = precip$Lugar)
  })

  #Plot
  output$plot <- renderPlot({
    ggplot(data(),aes(x=sel_Lugar, y=Medicion, fill=Mes,na.rm = TRUE)) +
      geom_col() +
      scale_fill_manual(values=c("#E23D2C","#BAA512","#512B9A","#21AB3F")) +
      labs(title = "Distribución general de la precipitación",
           caption= "Fuente: propia")+
      ylab("Precipitación (mm)") +
      theme_light()

  })
}

ui <- basicPage(
  h1("R Shiny Dynamically create Drop Down List"),
  selectInput(inputId = "sel_Lugar",
              label = "Choose Sales Rep",
              "Names"),
  plotOutput("plot")
)

shinyApp(ui = ui, server = server)

-
Im need that in one sheet appear this not reactive plot
In other sheet/tabs Im need put the reactive plot. This is the code. Im want that when select the "lugar" appear the plot. Are 4 "Lugar"
d_New<-read_excel("meses2.xlsx", sheet="F")

ggplot(d_New, aes(x=Lugar, y=Medicion, fill=Mes,na.rm = TRUE)) +
  geom_col() +
  scale_fill_manual(values=c("#E23D2C","#BAA512","#512B9A","#21AB3F")) +
  labs(title = "Distribución general de la precipitación",
       caption= "Fuente: propia")+
  ylab("Precipitación (mm)") +
  theme_light()

The app run and show this.

Example data
structure(list(Mes = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L), .Label = c("Marzo", "Abril", "Mayo"), class = "factor"),
    Dia = c(17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
    17, 18, 19, 29, 30, 31, 1, 2, 3, 4, 5, 6, 7, 8, 17, 18, 19,
    20, 21, 22, 23, 24, 25, 26, 27, 16, 17, 18, 19, 20, 21, 22,
    23, 24, 25, 26, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), Medicion = c(50,
    17, 13, 12, 3, 6, 0.3, NA, 13, 1, 4, 20, 3, NA, 0, 0, 0,
    0, 20, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, 0, 0, 5, 9,
    0, 1, 0, 0, 0, 0, 2, 17, 58, 32, 0, 9, 0.5, 1, 25, 1, 0.5,
    4, 10, 3, 3, 8, 36, 13, 1, 0.5, 0.5), Lugar = c("UNIAGRARIA",
    "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA",
    "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA",
    "UNIAGRARIA", "UNIAGRARIA", "GRANADA NORTE", "GRANADA NORTE",
    "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE",
    "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO",
    "RIO FRIO", "RIO FRIO", "RIO FRIO", "CHICU", "CHICU", "CHICU",
    "CHICU", "CHICU", "CHICU", "CHICU", "CHICU", "CHICU", "CHICU",
    "CHICU", "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO",
    "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO",
    "RIO FRIO", "RIO FRIO", "GRANADA NORTE", "GRANADA NORTE",
    "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE",
    "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE",
    "GRANADA NORTE")), row.names = c(NA, -60L), class = c("tbl_df",
"tbl", "data.frame"))

Thanks
Answer: Since you want to have 2 tabs (1 for the fixed plot and 1 for the reactive plot) you need to use navbarPage.
"sel_Lugar" was not found and it couldn't be used for the plot because data() doesn't have this column. The way that you tried to get data it was giving you a column with "Mes" and another column with "precip".

I don't know why you were trying to summarise, but if you want to draw the plots, you need to remove this part.

Therefore, you will be able to use the columns "Lugar", "Medicion" and "Mes" in the plot.
On the other hand, the code that you were using to draw the reactive plot is wrong.
ggplot(precip, aes(x=Lugar, y=Medicion, fill=Mes,na.rm = TRUE)) +
  geom_col() +
  scale_fill_manual(values=c("#E23D2C","#BAA512","#512B9A","#21AB3F")) +
  labs(title = "Distribución general de la precipitación",
       caption= "Fuente: propia")+
  ylab("Precipitación (mm)") +
  theme_light()

If you want to get the same output that you attached in the photos (for the reactive plot), you need to change the x (instead of "Lugar", it has to be "Dia"). Besides, if you want a scale that contains "Dias" I recommend you to use scale_x_continuous.
In my case, I have used scale_x_continuous(breaks=seq(from=0, to = max(precip$Dia), by=1))

seq(from=0, to = max(precip$Dia), by=1)
1  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 3

I have changed the way that you show the places (selectInput), since I have saved the choices into a function.
However, if for any case you have a huge list of options, I recommend you to use selectizeInput. Here you have one example.
After all the changes that I made, this is how your app looks.

Here I attach you the entire code.
Note that I added a table where you can see how you are subsetting your data according to the selectInput.
library(shinythemes)
library(shiny)
library(readxl)
library(shiny)
library(dplyr)
library(DT)
library(ggplot2)

# Since you want to have 1 tab for the "not reactive plot" and another tab for the "reactive plot", you will need to use navbarPage
ui <-  fluidPage(
  theme = shinytheme("flatly"), # this is to put some colors/themes
  navbarPage(
    title = "R Shiny Dynamically create Drop Down List",
    collapsible = TRUE,
    fluid = TRUE,

    tabPanel(
      title = "Not reactive plot",

      sidebarLayout(
        sidebarPanel = sidebarPanel(

        ),

        mainPanel = mainPanel(
          plotOutput("plot1")
        )
      )
    ),
    tabPanel(
      title = "Reactive plot",

      sidebarLayout(
        sidebarPanel = sidebarPanel(
          uiOutput('selectUI'), # this is to have the list of places
        ),

        mainPanel = mainPanel(
          plotOutput("plot2"),
          dataTableOutput("table")
        )
      )
    ),
  )
)

server <- function(input, output, session) {

  # this is your data without filtering
  data <- reactive({
    return(precip)
  })

  # this gives you the a vector of the choices of your original data
  lugar_choices <- reactive({
    choices <- levels(data()$Lugar)
    return(choices)
  })

  # this will give you your choices.
  output$selectUI <- renderUI({
    selectInput(inputId = 'sel_Lugar', "Choose Sales Rep", choices = lugar_choices())
  })

  # this your new data according to your select Input.
  data_filtered <- reactive({
    req(input$sel_Lugar)
    df <-  data() %>%
      filter(Lugar %in% input$sel_Lugar) %>%
      group_by(Mes)
    return(df)
  })

  # first plot (not reactive)
  output$plot1 <- renderPlot({
    ggplot(data(), aes(x=Lugar, y=Medicion, fill=Mes,na.rm = TRUE)) +

      geom_col() +
      scale_fill_manual(values=c("#E23D2C","#BAA512","#512B9A","#21AB3F")) +
      labs(title = "Distribución general de la precipitación",
           caption= "Fuente: propia")+
      ylab("Precipitación (mm)") +
      theme_light()
  })

  # second plot (reactive)
  output$plot2 <- renderPlot({
    ggplot(data_filtered(), aes(x=Dia, y=Medicion, fill=Mes,na.rm = TRUE)) +
      geom_col() +
      scale_fill_manual(values=c("#E23D2C","#BAA512","#512B9A","#21AB3F")) +
      labs(title = "Distribución general de la precipitación",
           caption= "Fuente: propia")+
      ylab("Precipitación (mm)") +
      scale_x_continuous(breaks=seq(from=0, to = max(data_filtered()$Dia), by=1))+
      theme_light()
  })

  # this is the info that you are plotting
  output$table <- renderDataTable(data_filtered())

}

shinyApp(ui, server)

Data:
precip = structure(list(Mes = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                          2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
                                          2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
                                          3L, 3L, 3L, 3L, 3L), .Label = c("Marzo", "Abril", "Mayo"), class = "factor"),
                        Dia = c(17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
                                17, 18, 19, 29, 30, 31, 1, 2, 3, 4, 5, 6, 7, 8, 17, 18, 19,
                                20, 21, 22, 23, 24, 25, 26, 27, 16, 17, 18, 19, 20, 21, 22,
                                23, 24, 25, 26, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), Medicion = c(50,
                                                                                17, 13, 12, 3, 6, 0.3, NA, 13, 1, 4, 20, 3, NA, 0, 0, 0,
                                                                                0, 20, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, 0, 0, 5, 9,
                                                                                0, 1, 0, 0, 0, 0, 2, 17, 58, 32, 0, 9, 0.5, 1, 25, 1, 0.5,
                                                                                4, 10, 3, 3, 8, 36, 13, 1, 0.5, 0.5), Lugar = c("UNIAGRARIA",
                                                                                "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA",
                                                                                "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA", "UNIAGRARIA",
                                                                                "UNIAGRARIA", "UNIAGRARIA", "GRANADA NORTE", "GRANADA NORTE",
                                                                                "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE",
                                                                                "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO",
                                                                                "RIO FRIO", "RIO FRIO", "RIO FRIO", "CHICU", "CHICU", "CHICU",
                                                                                "CHICU", "CHICU", "CHICU", "CHICU", "CHICU", "CHICU", "CHICU",
                                                                                "CHICU", "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO",
                                                                                "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO", "RIO FRIO",
                                                                                "RIO FRIO", "RIO FRIO", "GRANADA NORTE", "GRANADA NORTE",
                                                                                "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE",
                                                                                "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE", "GRANADA NORTE",
                                                                                "GRANADA NORTE")), row.names = c(NA, -60L), class = c("tbl_df",
                                                                                "tbl", "data.frame"))

# we transform the column into factors because we will need it for the choices (I will need the different levels)
precip$Lugar <- as.factor(precip$Lugar)

Comment: Ok, yes, the code run well. Tnks!
Comment: Tkns! @emr2, when Im run this code show this msm "Error in navbarPage(title = "R Shiny Dynamically create Drop Down List",  :
  argumento ausente, sin argumento por omisión".

Im check but dont see the error.
Comment: Have you checked if you have all the packages in your system? Because I added some new. I have loaded the code and the data again and I don't receive that error, so I don't know why you have it.. Which version do you have of R? (Mine is 4.1.3). Have you tried to restart R too? Sometimes it works... (And finally, did you change the column "Lugar" to factor?) We need to figure it out if you have done all the changes to know what it is going on

Reactive ggplot with Shiny-


The free group II$_{\infty}$ factor isomorphism problem

Question: Let $\Gamma$ be an infinite discrete group, and $H = l^{2}(\Gamma)$ the separable infinite dimensional Hilbert space.
Let $\rho$ be the left regular representation of $\Gamma$ on $H$.
Definition : Let $L(\Gamma) := \rho (\Gamma)''$ the von Neumann algebra generated by $\Gamma$.
Proposition :  $L(\Gamma)$ is a $II_{1}$ factor iff $\Gamma$ is ICC (infinite conjugacy class).
Let $\Gamma = \mathbb{F}_{n} = \langle a_{1}, a_{2},..., a_{n} \vert   \rangle$  the free group with $n$ generator. It's ICC iff $n \geq 2$.
Free group factor isomorphism problem : $L(\mathbb{F}_{n}) ≃ L(\mathbb{F}_{m})$, $∀n,m≥2$ ?
Voiculescu's formula (see here p 3) :  $L(\mathbb{F}_{n}) \simeq L(\mathbb{F}_{(n-1)k^{2}+1}) \otimes M_{k}(\mathbb{C})$
Example:  $L(\mathbb{F}_{2}) \simeq L(\mathbb{F}_{5}) \otimes M_{2}(\mathbb{C})$
Corollary: $\bigotimes_{i} L(\mathbb{F}_{n_{i}})   \simeq \bigotimes_{i} L(\mathbb{F}_{m_{i}})$ if $\prod_{i}(n_{i}-1) = \prod_{i}(m_{i}-1)$
Observation : $L(\mathbb{F}_{n}) \otimes B(H) \simeq L(\mathbb{F}_{(n-1)k^{2}+1}) \otimes M_{k}(\mathbb{C}) \otimes B(H) \simeq L(\mathbb{F}_{(n-1)k^{2}+1})  \otimes B(H)$
However, "$\exists k_{1}, k_{2} $ : $(n-1)k_{1}^{2}+1 = (m-1)k_{2}^{2}+1$" $\Leftrightarrow$  "$(n-1)(m-1)$ is a square".
Corollary: $L(\mathbb{F}_{n}) \otimes B(H) \simeq  L(\mathbb{F}_{m}) \otimes B(H)$   if $(n-1)(m-1)$ is a square.

Question :  Is it known to be true in general : $L(\mathbb{F}_{n}) \otimes B(H) \simeq  L(\mathbb{F}_{m}) \otimes
 B(H)$ $\forall n, m \ge 2$ ?
  (if "no", is it equivalent to the free group factor isomorphism problem ?)

In general:  $L(\mathbb{F}_{n}) \simeq L(\mathbb{F}_{m})^{\alpha} $ with  $\alpha = (\frac{m-1}{n-1})^{1/2}$.
Definition: Let $\mathcal{M}$ be a $II_{1}$ factor, then $\mathcal{M}^{t} \simeq p(M_{k}(\mathbb{C}) \otimes  \mathcal{M})p \simeq q(B(H) \otimes  \mathcal{M})q$,
 with $q \in B(H) \otimes  \mathcal{M}$ and $p \in M_{k}(\mathbb{C}) \otimes  \mathcal{M}$ projections, $Tr(q) = t$,  $k=\lceil t \rceil$ and $\tau(p) = \frac{t}{k}$.
Remark : Let $n, m \ge 2$ such that $(n-1)(m-1)$ is a square.
Let the $II_{\infty}$ factor $\mathcal{N} \simeq  L(\mathbb{F}_{n}) \otimes B(H) \simeq  L(\mathbb{F}_{m}) \otimes B(H)$.
Let $Tr$ (resp. $Tr'$) be the trace on $\mathcal{N}_{+}$ coming from the unique trace of $L(\mathbb{F}_{n})$ (resp. $L(\mathbb{F}_{m})$).
Let the projection $p, q \in \mathcal{N}$ such that $Tr(p) = Tr'(q) = 1$.
Then  $p \mathcal{N} p \simeq L(\mathbb{F}_{n})$ and $q \mathcal{N} q \simeq L(\mathbb{F}_{m})$. So, $Tr' = \alpha Tr$ with  $\alpha = (\frac{n-1}{m-1})^{1/2}$.
Answer: Yes, this is true.
Radulescu introduced the interpolated free group factors $L(\mathbb{F}_r)$ for all $1<r<\infty$. They obey the rule that if $r\in\mathbb{N}$ then we get the proper free group factor and they also obey,
$L(\mathbb{F}_r)^s=L(\mathbb{F}_{r'})$ where $r'={1+\frac{r-1}{s^2}}$. This gives that all free group factors are amplifications of each other. Which implies that they all generate the same $II_\infty$ factors. (ie $L(\mathbb{F}_n)\overline\otimes\mathcal{B(H)}\simeq L(\mathbb{F}_m)\overline\otimes\mathcal{B(H)} $.
Further, this reduces the free group factor isomorphism problem to the calculation of the fundamental groups one of the finite free group factors.
It is known that it is either
I.) All of $\mathbb{R}^+$ in which case they are all isomorphic.
II.) Or $\{1\}$, in which case they are all non-isomorphic.
Here is part of Dykema's thesis where this is proved.
http://arxiv.org/pdf/funct-an/9211012v1.pdf
Comment: Yes: but you need the fact about interpolated free group factors to get the result about fundamental groups.
Comment: Yes, the key is that if you have a $II_1$-factor $M$ acting on $\mathcal{K}$ then the isomorphism type of $M'$ is uniquely determined by dim$_M\mathcal{K}$. So for example if dim$_M\mathcal{K}=\infty$ then $M'\simeq M^{op}\otimes B(H)$. Now if we cut everything down by $p$ then we get $p\mathcal{K}$ is an infinite dimensional $pMp$ module so the commutant is $pMp\otimes B(H)$, however you can also get this by cutting $M'$ by $p$, but since $p$ commutes with $M'$ it doesn't change the isomorphism type. Hopefully this clarifies.
Comment: A sort heuristic argument is that you should think of a $II_1$ factor as a "square" because it's a diffuse version of a finite matrix. Then a $II_\infty$ factor is like an "infinite square" pieced together from many copies of the same finite square. In this analogy, I always like to say that "a $II_\infty$ factor is a $II_1$ quilt". and the isomorphism I describe is just saying that what matters is the quilt, not where we do the stitching. Hopefully, this makes some sense.
Comment: Yes, you're right !
Comment: The details runs exactly as your comment [here](http://mathoverflow.net/questions/136411/whats-the-natural-equivalence-of-subfactors-in-general/136424#comment351943_136424). I'm thoughless, I should have remembered it... : we restrict to $s  \in \mathbb{N}^{*}$, $L(\mathbb{F}_{r})^{s} = p ( L(\mathbb{F}_{r} \otimes B(H) )p$. Then, $L(\mathbb{F}_{r})^{s} \otimes B(H) \simeq L(\mathbb{F}_{r}) \otimes B(H) \otimes  (qB(H)q) $ $ \simeq L(\mathbb{F}_{r}) \otimes B(H)$, because $qB(H)q \simeq M_{n}(\mathbb{C})$.
Comment: **There is a point I don't understand** : take $s \in \mathbb{N}^{*}$ is not sufficient, because even with free interpolated group factors, we just prove that $L(\mathbb{F}_{r}) \otimes B(H)  \simeq L(\mathbb{F}_{s}) \otimes B(H)$ if $(s-1)/(r-1)$ or $(r-1)/(s-1)$ is a square interger. The problem is that we can't take $s  \not\in \mathbb{N}$ because $B(H)$ is a $I_{\infty}$ factor, and so, it can't absorb a projection with a non-integer trace, as $\mathcal{R}$ [here](http://mathoverflow.net/questions/136411/whats-the-natural-equivalence-of-subfactors-in-general/136424#comment351943_136424)
Comment: So "$L(\mathbb{F}_{r}) \otimes \mathcal{R}  \simeq L(\mathbb{F}_{s}) \otimes \mathcal{R}, r,s>1$" it's ok for me, but "$L(\mathbb{F}_{r}) \otimes B(H)  \simeq L(\mathbb{F}_{s}) \otimes B(H)$", still not... and for you ?
Comment: Ok, thank you Owen for these technical and heuristical arguments ! So in general, if $\mathcal{M}$ is a $II_{1}$ factor, then $\mathcal{M}^{t} \otimes B(H) \simeq \mathcal{M} \otimes B(H)$. It's good to have this in mind.
Comment: Yes!, exactly right.


Using Twig to declare template and pass in additional content between the parent template's block

Question: I have the following code that I repeat multiple times in my layout:

How can I put in the above html into a single Twig template, and then use that template and put in my additional specific html in the  section?
Answer: You could just define blocks and embed the template where ever you want
partial.twig.html

             {% block content %}
             {% endblock %}

template.twig.html
{% embed "partial.html.twig" with { 'id' : 'foo' } %}
    {% block content %}
         Lorem Ipsum
    {% endblock %}
{% endembed %}

You could also use an embed in a for-loop. Variables known inside the loop, are also know in the embedded file, e.g.
item.html.twig

             {% block title %}
                 {% if item.title is defined %}

{{ item.title }}

                 {% endif %}
             {% endblock %}
             {% block content %}
                 {% if item.content is defined %}

{{ item.content }}

                 {% endif %}
             {% endblock %}

template.html.twig
{% for item in items %}
    {% embed "item.twig" %}
    {% endembed %}
{% endfor %}

demo


mysql query to select everything except

Question: i have two mysql tables.
the first is called "chosen" and consists of id, user_id, and widget_id fields.
the other is called "widgets" and includes several things including widget_id.
i created a filter so that the user can either display widgets that he/she has chosen, or widgets that he/she hasn't chosen. for the ones he has chosen, i use this:
SELECT *
  FROM widgets, chosen
 WHERE chosen.user_id = $user_id
   AND chosen.widget_id = widgets.widget_id

however, i can't figure out how to display the ones that he/she hasn't chosen. this doesn't work (displays everything):
SELECT *
  FROM widgets, chosen
 WHERE !(    chosen.user_id = $user_id
         AND chosen.widget_id = widgets.widget_id)

how do i do this?
Answer: Using NOT IN:
SELECT w.*
  FROM WIDGET w
 WHERE w.widget_id NOT IN (SELECT c.widget
                             FROM CHOSEN c
                            WHERE c.user_id = $user_id)

Using NOT EXISTS:
SELECT w.*
  FROM WIDGET w
 WHERE NOT EXISTS (SELECT NULL
                     FROM CHOSEN c
                    WHERE c.widget_id = w.widget_id
                      AND c.user_id = $user_id)

LEFT JOIN/IS NULL:
   SELECT w.*
     FROM WIDGET w
LEFT JOIN CHOSEN c ON c.widget_id = w.widget
                  AND c.user_id = $user_id
    WHERE w.widget IS NULL

Performance:
If the columns compared (widget_id in either table) are not nullable, LEFT JOIN/IS NULL performs the best on MySQL.  If the columns are nullable (the value could be NULL), NOT IN or NOT EXISTS perform better.
Comment: thanks! i ended up using "SELECT * from widgets w WHERE w.widget_id NOT IN (SELECT w.widget_id FROM widgets w, chosen c WHERE c.widget_id = w.widget_id AND c.user_id = $user_id)"
Answer: Boolean logic: (ab)' is the same as a' + b'
SELECT *
  FROM widgets, chosen
 WHERE chosen.user_id <> $user_id
         OR chosen.widget_id <> widgets.widget_id

Answer: Basically, you want to select all rows from widgets that have no associated row in chosen for the given $user_id. You can accomplish this with a LEFT OUTER JOIN looking for the rows that didn't match in the chosen table. Something like this:
SELECT w.* FROM widgets as w
LEFT OUTER JOIN chosen as c on c.widget_id=w.widget_id AND c.user_id=$user_id
WHERE c.id IS NULL;

BTW: I recommend using the newer join syntax over the comma delimited tables join syntax. It's easier to read and understand, especially when it comes to outer joins.

mysql query to select everything except


Scala Write the adjacency list of each node of a graph to a text file

Question: I am trying to reverse a directed graph and to write the adjacency list of each vertex to a text file in the format
NodeId \t NeighbourId1,NeighbourId2,...,NeighbourIdn

So far I've only tried printing my output which is as follows:
(4,[J@13ad83aa)
(0,[J@338ff780)
(1,[J@6737f62b)
(3,[J@1250d788)
(2,[J@6d1fa6bb)

Whereas it should be of the format:
4   2
0   4
1   0,2
3   1,2,3
2   0,1

The current code I've been using is
object Problem2{
def main(args: Array[String]){
val inputFile:String = args(0)
val outputFolder = args(1)
val conf = new SparkConf().setAppName("Problem2").setMaster("local")
val sc = new SparkContext(conf)

val graph = GraphLoader.edgeListFile(sc,inputFile)
val edges = graph.reverse.edges
val vertices = graph.vertices
val newGraph = Graph(vertices,edges)

val verticesWithSuccessors: VertexRDD[Array[VertexId]] =
newGraph.ops.collectNeighborIds(EdgeDirection.Out)

val successorGraph = Graph(verticesWithSuccessors, edges)
val res = successorGraph.vertices.collect()

val adjList = successorGraph.vertices.foreach(println)

I don't think mkString() can be used with a graph object. Is there a similar method for graph objects to get the string?
Answer: Let's take again this example:
val vertices: RDD[(VertexId, String)] =
    sc.parallelize(Array((1L,""), (2L,""), (4L,""), (6L,"")))

val edges: RDD[Edge[String]] =
    sc.parallelize(Array(
        Edge(1L, 2L, ""),
        Edge(1L, 4L, ""),
        Edge(1L, 6L, "")))
val inputGraph = Graph(vertices, edges)

val verticesWithSuccessors: VertexRDD[Array[VertexId]] =
    inputGraph.ops.collectNeighborIds(EdgeDirection.Out)
val successorGraph = Graph(verticesWithSuccessors, edges)

Once you have this:
val adjList = successorGraph.vertices

You can translate into a DataFrame easily:
val df = adjList.toDF(Seq("node", "adjacents"): _*)
df.show()
+----+---------+
|node|adjacents|
+----+---------+
|   1|[2, 4, 6]|
|   2|       []|
|   4|       []|
|   6|       []|
+----+---------+

Now it's easy to transform with columns. Here a not so pretty example:
val result = df.rdd.collect().map(l=> l(0).asInstanceOf[Long] + "\t"  + l(1).asInstanceOf[Seq[Long]].mkString(" "))
result.foreach(println(_))

1   2 4 6
2
4
6

Or also  you can try with UDFs or handle the columns as you want.
Hope this helps!
Comment: For completeness, before translating to data frame, sql context was created
`val sqlContext = new org.apache.spark.sql.SQLContext(sc)`
`import sqlContext.implicits._`


How can I set a variable with twig?

Question: I want to set the variable key before using it
  "columns": [
      {% for key, value in columns %}
        {"data": "{{ key }}"},
        {% endfor %}
      { "data": "id" }
    ]

My approach:
  "columns": [
      {% for key, value in columns %}
      {% set result = '{{ key }}' %}
        {"data": "{{ result }}"},
        {% endfor %}
      { "data": "id" }
    ]

But it is not working. I get the error message:

Requested unknown parameter '{{ key }}'
Comment: just an aside ... why is it needed? You've added 1 new line, and attempted to set key to a name with 3 more chars... and then echo it straight away .. why not just stick with key? - also just do `{% set result = key %}`
Comment: you can still use key in an if statement, there's no point setting a var inside a loop to use for a conditional outside of the loop - it will be set to the last iteration of the loop ... so it won't ever be an accurate conditional. And if you are wanting the last iteration, then just call the last iteration and do the if on that
Comment: @treyBake Because I want to use an if statement later
Answer: {% set result = key %}

From what I see, you want to set the value of result variable, result of key is already set, you just didn't access it correctly.
Comment: From your code, `key` is just an integer or a string (not an object like you're suggesting) that represents each key from indexed `columns` array. Perhaps you're looking for `value` ? Try `{% set result = value %}` . Because I have no clue what `key.name` should be, I'm afraid I cannot help you more than this. Perhaps after you set `{% set result = value %}`, you can get to `value.name`.
Comment: Thank you very much
Comment: One question, what if I want the variable to be `{{ key }}.name`, because I tested `{% set result = key.name %}` and this did not work out

How can I set a variable with twig?


Batch file not calling other batch files

Question: I have a set of three automatically generated batch files, summed up below
arbitrary.bat
@ECHO OFF
set APPDATA=C:\Users\%USERNAME%\AppData\Minecrafts\1.9p5\
set T1=ÚÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
set T2=³ÍÍÍ 1.9p5 ÍÍͳ
set T3=ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
masterControl

masterControl.bat
varInit
[main program logic...]

varInit.bat
set U=valueOfU
set P=valueOfP
set S=valueOfS
pause

The idea is that arbitrary.bat is run and the other two are called, as well. However, the program stops right after masterControl runs its first line (all lines in varInit are run successfully). **Why doesn't this program run past the first line of masterControl?
Comment: I don't use windows, but I'd bet `pause` waits for user input. Did you hit `enter` after it got there?
Comment: yes -_- I put `pause` there for debugging
Answer: You have to use the command CALL to call each batch file from another i.e. CALL masterControl.bat
Comment: then why does `masterControl.bat` run its first line?
Comment: Every subsequent batch file execution (without using the call command) will abort the execution of the caller. Calling varInit from masterControl aborts the execution of masterControl so masterControl won't continue after varInit completes.
Comment: If a Batch file execute another one with no `call` command, the result is equivalent to a "goto to another file": when the second Batch file ends the whole execution ends. I call _Overlay_ a Batch file executed this way (instead of _Subroutine_ that returns when end).


How do I compare a new method of statistical sampling with an established one?

Question: Lets say that:
There exist 10 countries.
I travel to each country and take a random subset of the population of that country and count how many of my subset are woman.
I make a table of country to percentage female for the 10 countries.
I then repeat this study, but instead of traveling to the countries, I use some other method of getting a supposedly random sample of people to check for femaleness.
In the end my data looks like this.
<code>country, random-sampling, new-technique
a,       0.6,             0.55
b,       0.4,             0.38
c,       0.9,             0.85
.
.
.
</code>
If I assume that the first time around I actually found a representative sample of people for each country, and thus we trust that there really are 90% woman in country 'c' then:
How do I validate whether the new technique is a valid way of testing for percentage woman in countries? I want to know how well the second set of data agrees with the assumed-to-be-correct first set.
Comment: You'll want to assess whether your estimates are biased and have less variance over repeated sampling.  But a question I have is do you consider the first method the "gold standard" that you'd like to compare to?
Comment: Yes, assuming that the first method is the 'gold standard'.
Comment: To elaborate, I don't want to use the second-technique to add certainty some overall estimate, I want to validate whether the second-technique is a valid method, assuming that the first was 'perfect'.
Answer: If you really want to take the first sample as the truth, then we can use the estimated probabilities from that sample as known probabilities, and use those to formulate a null hypothesis for the new-technique sample. The null hypothesis can be that the second sample is as if sampled with/without replacement (you didn't specify), lets assume without, so a hypergeometric model (with the given probability parameters $p_a=0.6, p_b=0.4, \dotsc$.) The sample sizes must also be given (you didn't) as $n_a, n_b, \dotsc$ and known. Then the data from the second sample is $X_a \sim \mathcal{Hypergeo}(n_a p_a,n_a(1-p_a), X_b \sim \dots$ (independently.)   Just lets hope those products are integers ...
Then you can construct a hypergeometric test for each population, and somehow combine those to get an overall test.


Delegate vazio ( delegate { } )

Question: O que retorna a instrução delegate { }? Seria um delegado vazio?
Em que situações seria necessário criar um delegado vazio?
Answer: O que é um delegate?
Grosso modo é um ponteiro para um método, certo? Então o que terá nele é um endereço para algo que pode ser executado. Isso pode ser guardado em variáveis. E esta é a grande vantagem do delegate, você pode variar o que será executado, já que aquela variável pode apontar em um momento para uma função, em outro momento para outra função.
Quando você precisa inicializar o delegate e

não quer ainda dar uma função útil para ele e deixar isto para mais tarde,
ou quer que a função seja "fazer nada",

então podemos atribuir ao delegado uma função vazia, ou seja, que executa nada.
Então a função é vazia, o delegado não, porque ele é o ponteiro. Um delegado vazio na verdade seria um nulo.
Referências adicionais:

Delegates e métodos
Qual a diferença entre uma expressão lambda, um closure e um delegate?
Qual a diferença entre event e delegate?
Quando e onde usar um delegate no C#?

Coloquei no GitHub para referência futura.
Answer: Só para complementar a resposta do @Maniero, aonde é usado...  eu particularmente uso para iniciar eventos para não me preocupar se o evento é null
Por exemplo:
public class Teste{

  public event EventHandler MeuEvento;
  public event EventHandler MeuEvento2 = delegate { };

  public void MetodoExemplo(){

      //se quiser disparar o evento deve-se antes checar se alguem se registrou,
     if (MeuEvento != null)
         MeuEvento(null,null);

     //agora como iniciamos o event não precisamos se "preocupar"
     MeuEvento2 (null,null);
  }
}

Comment: Com C# 6 pode-se também escrever algo do tipo `MeuEvento?.Invoke(null,null)`

Delegate vazio ( delegate { } )


Chrome Sources Displaying Javascript in Chinese

Question: My javascript was working properly and then all of the sudden it wasn't. Chrome give me the Uncaught SyntaxError: Unexpected token ILLEGAL error on line 1 of my JS file called para2.js. I removed script from the file except for the following and I still get the error:
$( window ).ready(function() {
});

My jQuery file is included in the head of my document:

When I look at my js file in Chrome developer tools on the Sources tab, it displays the script in Chinese:
兪敵祲搨捯浵湥⥴爮慥祤昨湵瑣潩⡮笩⥽

When I view the source of the js file, it looks fine. I have read similar posts that say copy and pasting from JSFiddle can include some hidden characters that may cause it, but I have started from scratch writing this file from a blank text file and copy and pasting nothing. It is strange that it was working and now it is not. Did my server get hacked or something? And help is appreciated.
Comment: Probably because the encoding of your para2.js file is not correct. Try use another text editor and type in again. You can start with a very simple javascript file.
Comment: And it does not seem to be related to jQuery itself. Any javascript code I insert responds the same way. I tried a simple alert and console.log and both give me the same error and strange Chinese.
Comment: I am using Coda 2.5.7. I created a new file and added an alert script with TextEdit, uploaded with Coda and still get the same issue.
Comment: It's possible that the invalid character is actually in your HTML file, near where the
Comment: I pulled the code from off my server, rewrote it and ran it in MAMP. It seems to be working now, but I am not sure why. Thanks for reading.
Answer: You should use the charset attribute to indicate which charset you are using.


Microsoft Outlook asks password whenever user changes passwords

Question: I have 10000 users with different OUs, groups. We have a Windows 2008 AD server and a Exchange 2010 mail server. Clients are using Windows 7 64-bit OS and Outlook 32 bit. Whenever users change their password, Outlook and Lyncs keep on prompting passwords from the user even after the users enter the correct credentials. This causes an account lockout issue. Due to this, we are facing large number of tickets. What we are doing right now is restart the machine and remove the saved password from the vault.
Does anyone have an alternate solution for this?
Answer: You've got Basic or NTLM authentication enable for Outlook Anywhere (on your Exchange Client Access server(s)). This has the negative side effects that your clients store the password in the Windows Vault, and that your Exchange server(s) are susceptible to the recently released NTLM security bug (which makes your Exchange server trivial to hack).


Can $G^2$ statistic in log-linear model for contingency tables be negative?

Question: Can $G^2$ statistic of log-linear (unsaturated) model in contingency tables be negative? Since saturated model with perfect fit has $G^2=0$ I don't think the unsaturated models can get negative $G^2$. In need of insight, since I might have run into some miscalculations.
Comment: Depending on the order I've entered models in some R functions, I've run issues like this.
Answer: Note from Wikipedia that the $G^2$-statistic has the form of (twice) a Kullback-Leibler divergence, see Why is Kullback Leibler Divergence always positive?. More precisely
$$ \DeclareMathOperator{\KL}{KL}
   G^2 = 2\sum_i O_i \log\frac{O_i}{E_i}=2N\KL\left(\frac{O_i}{N}   || \frac{E_i}{N}  \right)
$$ where $N$ is the total count.  It is also related to the deviance in generalized linear models, and is in fact the Deviance (in R terminology, Null deviance - Residual deviance) in a logistic regression model for the contingency table.


Find all solutions of $y^2 dx + (e^x - y)dy = 0$

Question: I need to find all solutions of:
$y^2 dx + (e^x - y)dy = 0$
So I take:
$M = y^2$
$N = e^x - y$
And I see that:
$\frac{M}{dy} = 2y$
$\frac{N}{dx} = e^x$
I'm therefore looking for an integrating factor:
$$ \displaystyle e^{\int \frac{1}{y^2}(e^x - 2y) dy} = e^{\int \frac{e^x - 2y}{y^2}dy} = e^{-2ln(y) - \frac{e^x}{y}}$$
And at this point I think it might be too complicated and I probably do something wrong.
Comment: Try taking the substitution $y=e^x(1+z)$.
Comment: Seeing that the terms are polynomial up to $e^x$, one might try $u=e^x$. With $dx=e^{-x}du=du/u$ this gives a rational polynomial expression, but increases the degree. So one might try to go in the other direction with $u=e^{-x}$, so that now $dx=-e^xdu$. This gives a simpler version of the expression, you should be able to see the next steps.
Answer: Hint
Consider the equation as
$$y^2\,x'+e^x -y=0$$
Let $x(y)=\log \left(\frac{y}{u(y)}\right)$ to make it more than simple
Comment: I don't know how to find the antiderivative of $log(\frac{y}{u(y)})$ with respect to y
Comment: @mathman12. $x=\log(y/u)=\log(y)-\log(u) \implies x'=1/y - u'/u$
Comment: Ok, then I get in te end that: $u' = \frac{1}{y}$, but how to undo the substitution?
Comment: $x = log(\frac{y}{u}) \iff e^x = \frac{y}{u} \iff u = \frac{y}{e^x} \iff u' = \frac{1}{e^x}$?
Comment: is that something like this?
Answer: Divide equation by $y$.
Then easy get that integrating factor of $y^2 dx + (e^x - y)dy = 0$ is
$$\mu=\frac{e^{-x}}{y}$$
and all solutions
$$\ln y-e^{-x}y=C$$
Comment: I get $ye^{-x}dx+(1/y-e^{-x})dy=0$. Then $M'_y=e^{-x}$, $N'_x=e^{-x}$. Derivatives are equal.
Comment: I don't think it works. When I divide by $y$ I get $y dx + ((\frac{e^x}{y} - 1) dy) = 0$. Taking the integrating factor as you metioned gives me $\frac{1}{e^x} dx + \frac{1}{y^2} - \frac{1}{e^x \cdot y} dy = 0$. Now, derivatives are not equal: one is $0$ and the other is not. The differential equation is not exact.


Understanding log messages from iptables

Question: I have enabled logging with iptables. Now, I need to understand some of the abbreviations.

Feb 23 20:43:08 spiderman kernel [ 2905.992450]: IN=wlan0 OUT=
  MAC=ff:ff:ff:ff:ff:ff:00:06:25:09:6a:b5:08:00 SRC=192.168.1.100
  DST=192.168.1.255 LEN=241 TOS=0x00 PREC=0x00 TTL=64 ID=64564 DF PROTO=UDP
  SPT=138 DPT=138

What does each of the following mean:

[ 2905.992450]
TOS=0x00
PREC=0x00
ID=64564
DF

Any help is appreciated. Thanks.
Answer: [ 2905.992450] - kernel timestamp
TOS=0x00 - The Type of Service of the IP packet.
PREC=0x00 - The Precedence of the IP packet.
ID=64564 - The id of the IP packet.
DF - Fragment Flags. Can have "CE" (congestion), "DF" (don't fragment), or "MF" (more fragments are coming).


Selecionar várias tabelas ao mesmo tempo em SQL

Question: Tenho 5 tabelas no meu sistema:
pacientes - Primary key idPacientes
anamnese - foreggin key idPacientes
avaliacoes - foreggin key idPacientes
intervencao - foreggin key idPacientes
contrato - foreggin key idPacientes

A tabela pacientes tem a chave primária chamada idPacientes, as demais têm as chaves estrangeiras conectadas ao paciente.
Estou fazendo um relatório para quando eu terminar de cadastrar, fazer anamnese, avaliar, intervenir com o paciente e dar o seu contrato, eu puxar todas as informações que estão na anamnese, avaliacoes, intervencao e contrato do paciente.
Mas não sei como fazer um select disso. Meu professor me ajudou dando um exemplo, mas que só pega as informações do pacientes e da anamnese:
SELECT PAC., FIC.
FROM PACIENTES AS PAC INNER JOIN anamnese AS FIC ON PAC.idPacientes=FIC.idPacientes
where pac.idPacientes = '$id'

Aonde está escrito PAC e FIC são os apelidos das tabelas pacientes e anamnese. Quero ter a mesma coisa desse SELECT, mas incluindo o restante das tabelas.
Comment: Você quer criar uma consulta que retorne dados das 5 tabelas ao mesmo tempo, é isso? Eu não entendi o parágrafo final, pode reformular, por favor, para ficar mais claro? Informe também o banco de dados que está usando, na pergunta e nas tags.
Comment: Pedro, faça o teste usando a minha resposta e me diga se era isso que você desejava ok?
Comment: É realmente isso André, mas testei aqui e não foi deu esse error mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
Answer: Pode ler a documentacao sobre INNER JOIN e LEFT JOIN.
Uma Ideia simples para juntar as tabelas sera algo como
Select * from Pacientes INNER JOIN anamnese ON anamnese.idPacientes == Pacientes.idPacientes

Nesse caso você retorna todos os pacientes que tiverem na tabela anamnese.
Para juntar mais tabelas seria o caso de adicionar outro inner join
Select * from Pacientes
INNER JOIN anamnese ON anamnese.idPacientes == Pacientes.idPacientes
INNER JOIN avaliação ON avaliação.idPacientes == Pacientes.idPacientes

Sempre deixando a tabela que tiver mais registros a esquerda do ON.
Na documentação existe muitas outras dicas que você deve levar em consideração.
Comment: Tem algum DBMS que usa `==` como operador de comparação? Seria legal colocar um link para a documentação que você menciona!
Answer: SELECT * FROM Pacientes pac
LEFT JOIN anamnese as ana ON ana.idPacientes = pac.idPacientes
LEFT JOIN avaliacao as ava ON ava.idPacientes = pac.idPacientes
LEFT JOIN intervenção as int ON int.idPacientes = pac.idPacientes
LEFT JOIN Contratos as cont ON cont.idPacientes = pac.idPacientes

Lembrando que onde está o * você deve pôr os campos das tabelas, ex: pac.Nome, pac.Idade, int.AlgumaCoisa, cont.OutraCoisa.
Comment: No padrão ISO `int` é uma palavra reservada, no SQL Server não ([doc SQL Server](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql)), então, dependendo de qual [DBMS](https://en.m.wikipedia.org/wiki/Database#Database_management_system) estiver sendo usado, esse `int` como alias pode dar errado.
Comment: Verdade Pedro Gaspar, não percebi na hora. Lembrando que o nome da tabele á você quem define Pedro Lukas (bom se atentar a nomenclatura como citado pelo Pedro)..
Comment: Desculpem se eu não fui muito claro, mas eu respondi essa minha pergunta olhem lá em baixo, pfv
Answer: Se você deseja exibir todos os registros de cada tabela, você pode usar ( .* ) para extrair todos os dados de cada tabela relacionada do seguinte modo:
SELECT
 Pacientes.*,
 Anamnese.*,
 Avaliação.*,
 Intervenção.*,
 Contratos.*
FROM Pacientes
 JOIN Anamnese ON Pacientes.idPacientes = Anamnese.idPacientes
 JOIN Avaliacao ON Anamnese.idPacientes = Avaliacao.idPacientes
 JOIN Intervenção ON Anamnese.idPacientes = Intervenção.idPacientes
 JOIN Contratos ON Contratos.idPacientes = Intervenção.idPacientes
WHERE Pacientes.idPacientes = [Id do paciente que você deseja]

Nota: o .* trás todos os campos da tabela, porém, você pode adicionar as colunas desejadas caso você não queira trazer todos em algum momento posterior.
Dica: A dica que te dou é de criar tanto as tabelas quanto as colunas sem acentuação gráfica para melhor manutenção de seu projeto.
Comment: Eaí brother, é isso mesmo que eu quero, mas testei aqui aí apareceu isso Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\TCC3001\TCC V3.0\relatorios\infopaciente.php on line 14
Comment: Esse erro deu na aplicação php ou direto no banco?
Comment: na aplicação php msm
Comment: Se eu passar o sistema pra você, tu da uma olhada?
Comment: Claro, estou aqui para ajudá-lo. Mas só me tira uma dúvida... Você já tentou executar este select no banco?
Comment: Sim, já consegui brother kk vlw ae
Comment: @PedroLukas o que era o problema?
Comment: Erro era de aspas kk
Comment: Ah, então o que mandei ajudou não é?


How do you reference a attribute field and output results onto a different attribute field?

Question:
Here is what i am trying to do....
STATUS     STATU_DESC
1          Occupied
2          Not Occupied
3          Busy
4          No Information
Answer: I think that something like this should work:
def calc_status_desc(status):
    if status == 1:
        return 'Occupied'
    elif status == 2:
        return 'Not Occupied'
    elif status == 3:
        return 'Busy'
    elif status == 4:
        return 'No information'
    else:
        return None

In the field calculator select python and invoke it like this,
calc_status_desc(!STATUS_DESC!)
calculate field example
Comment: the picture below is the correct code, thanks for your help cabesuon!


Which hook occurs last before rendering the exposed filter widgets?

Question: I'm trying to edit the variables that go from Views into the form array editted by hook_form_alter() and the tpl file views-exposed-form.tpl.php. Specifically, I'm trying to use the contents of $view->exposed_input for form theming, without resorting to using $view = views_get_current_view();
I've tried working my way up the order of execution defined here:

hook_views_pre_view
hook_views_pre_build
hook_views_post_build
hook_views_pre_execute
hook_views_post_execute
hook_views_pre_render
hook_views_post_render

...but I'm stuck. At hook_views_pre_render(), $view->exposed_widgets gives me already-rendered HTML, so it's clearly too late, but the earlier ones don't give me anything at all.
Based on How to choose between all the views hooks?, I've tried using a preprocess hook based on the tpl file name, like hook_preprocess_views_exposed_form(), but the view isn't in scope here, I'm looking for the last views hook before this where I can find data from the view to these variables.
What I want to do, is take the contents of $view->exposed_input, and pass it through to the exposed form tpl file so that I can add a facet-like summary of current filters to my view. Which is the Views hook where I can do this?
I'm using Better Exposed Filters module, so if there are any hooks or tricks specific to that,they'd be welcome.
Answer: You can do what you need by adding a custom property to your form array via form alter:
function yourmodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // get the related view
  $view = $form_state['view'];

  // get the exposed_input and store it into a custom property
  $form['#exposed_input'] = $view->exposed_input;

}

The form array is directly available as a variable in your views-exposed-form.tpl.php, try adding the following to the end of that tpl file:

<?php print_r($form['#exposed_input']); ?>

Hope this helps!


Declared const variable not visible in useEffect

Question: I am working through the following code:
index.js
import React, {useRef, useState, useEffect} from "react";
import ReactDOM from "react-dom";
import AddAPhotoTwoTone from '@material-ui/icons/AddAPhotoTwoTone'
import backImg from "./background.png";

const Canvas = (props) => {
  const canvas = useRef(null);
  const image = useRef(null);
  const xLoc = useState(props.backImg.width/2)
  const yLocTop = useState(props.backImg.height/2)
  const yLocBottom = useState(props.backImg.height/2)

  useEffect(() => {
    const ctx = canvas.current.getContext("2d");
    image.current.onload = () => {
      ctx.drawImage(image.current, 0, 0);
      ctx.font = "20px Courier";
      ctx.textAlign = "center";
      console.log(xLoc)
      ctx.fillText(props.textTop, xLoc, yLocTop);
      ctx.textAlign = "center";
      ctx.fillText(props.textBottom, xLoc, yLocBottom);
    };
  });

  useEffect(() => {
    const ctx = canvas.current.getContext("2d");
    ctx.drawImage(image.current, 0, 0);
    // const xLoc = canvas.current.width/2
    // const yLocTop = canvas.current.height*.95
    // const yLocBottom = canvas.current.height*0.05
    ctx.font = "20px Courier";
      ctx.textAlign = "center";
      ctx.fillText(props.textTop, xLoc, yLocTop);
      ctx.textAlign = "center";
      ctx.fillText(props.textBottom, xLoc, yLocBottom);
  });

  return (

      <canvas ref={canvas} width={props.backImg.width} height={props.backImg.height} />

  );
};

function App() {
  return (

      <Canvas textTop="TEST 123" textBottom="TEST 456" backImg={backImg} />

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Why is the console.log(xLoc) within first useEffect printing NaN?
  useEffect(() => {
    const ctx = canvas.current.getContext("2d");
    image.current.onload = () => {
      ctx.drawImage(image.current, 0, 0);
      ctx.font = "20px Courier";
      ctx.textAlign = "center";
      console.log(xLoc)
      ctx.fillText(props.textTop, xLoc, yLocTop);
      ctx.textAlign = "center";
      ctx.fillText(props.textBottom, xLoc, yLocBottom);
    };
  });

Sandbox code is here
Edit:
Even with properly configured useState, it returns NaN on console.
Comment: I dont think you are using `useState()` properly. Should be declaring 2 const's by destructuring the array that useState returns... `const [pieceOfState, setterFuncToUpdatePieceOfState] = useState(defaultValueForPieceOfState);`
Answer: useState() returns an array. The first element is the state-value and the second is its state-updating function. You need to destructure the output like so.
Needs to be
const [xLoc, setxLoc] = useState(props.backImg.width/2)
const [yLocTop, setyLocTop] = useState(props.backImg.height/2)
const [yLocBottom, setyLocBottom] = useState(props.backImg.height/2)

Thus whatever you pass in to useState() will be the initial value.
Additionally. The problem is that the props.backImg is simply a string. It does not have any object properties like .width, and .height. To actually have access to those values, you need to first use that image as a src inside an img tag.
Then the img tag has access to the onLoad event-listener. With an event-handler, we can access the object properties mentioned.
In sense, we first need to render the image on the screen, but that doesn't happen until we render the Canvas component, so there is no need to pass in those props from App. See sandbox for more details.
See sandbox: https://codesandbox.io/s/hardcore-night-djzmr
Comment: It still prints Nan
Comment: You get NaN when you try to divide a non-num type by a number. Possibly check if (props.backImg.height) is a number before dividing it? @Zanam
Comment: Can you please see in the sandbox link why I am not able to get the dimensions? Or should I start a new thread?
Comment: @Zanam yeah I took some time to look at it. The problem is that the props.backImg is simply a string. It does not have any object properties like .width, and .height. To actually have access to those values, you need to first use that image as a src inside an img tag. Then the img tag has access to the onLoaded event-listener. Where we now can you the object properties mentioned. See sandbox for more details. In sense, there is no point passing the properties as props when we first need to render the image on the screen :)


LDAP integration with Spring

Question: I am trying to integrate Spring with LDAP, after succesfull login authentication I am able to hit my controller but not able to see view page.
This is my security.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/security"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:beans="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
        <http  auto-config="true">
                <intercept-url pattern="/abc/**"
                access="ROLE_USER" />

            <form-login login-page="/login" authentication-success-handler-ref="authenticationSuccessHandler" authentication-failure-url="/login?error=true" default-target-url="/home/page"
                login-processing-url="/j_security_check" />

        </http>

    <beans:bean id="authenticationSuccessHandler" class="com.abc.webapp.security.AuthenticationSuccessHandler">
        </beans:bean>

        <beans:bean id="tdrUserDetailsContextMapper" class="com.XXXX.util.LDAPGrantedAuthoritiesMapper">
        </beans:bean>

        <authentication-manager>

<authentication-provider  ref="activeDirectoryAuthenticationProvider">

</authentication-provider>

  </authentication-manager>

  <beans:bean id="activeDirectoryAuthenticationProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider" >
<beans:constructor-arg value="XXXXXXX.XXX" />
<beans:constructor-arg value="ldaps://XXXXXX:636/" />
<beans:property name="convertSubErrorCodesToExceptions" value="true"/>
<beans:property name="userDetailsContextMapper" ref="tdrUserDetailsContextMapper"/>

</beans:bean>

</beans:beans>

My LDAPMapper class:
package com.abc.util;

import java.util.ArrayList;
import java.util.Collection;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
public class LDAPGrantedAuthoritiesMapper  implements UserDetailsContextMapper   {

    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx,
            String username, Collection<? extends GrantedAuthority> authorities) {
        // TODO Auto-generated method stub
        Collection<GrantedAuthority> mappedAuthorities = new ArrayList<GrantedAuthority>();

        ctx.setAttributeValue("referral", "follow");

        SimpleGrantedAuthority roleUser = new SimpleGrantedAuthority("ROLE_USER");
         for (GrantedAuthority granted : authorities) {

                if (granted.getAuthority().equalsIgnoreCase("Vendor-TaisTech-CreditPaymentApp-R")) {

                    mappedAuthorities.add(roleUser);
                }
         }

            UserDetails userDetails= new TaisUserDetails(username, "", true, true, true, true, mappedAuthorities);

        return  taisUserDetails;
    }
    @Override
    public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
        // TODO Auto-generated method stub

    }

}

my urlrewrite.xml:
<urlrewrite default-match-type="wildcard">

    <rule>
        <from>/</from>
        <to type="redirect" last="true">/home/page</to>
    </rule>
    <rule>
        <from>/abc/**</from>
        <to last="true" type="redirect">%{context-path}/$1</to>
    </rule>

    <rule>
        <from>/login*</from>
        <to>/pages/login.jsp</to>
    </rule>
    <rule>
        <from>/logout*</from>
        <to>/pages/logout.jsp</to>
    </rule>

    <rule>
        <from>/**</from>
        <to>/abc/$1</to>
    </rule>
</urlrewrite>

In my Authentication Success hanlder I get a authorised user with ROLE_USER.
But when I hit my controller class it returns me to:
http://localhost:8080/login with 404 error.
In my logs I am able to see that user has been successfully authenticated but I am not able view any of my application page.
Answer: Everything looks correct, i think there is an issue of urlRewrite or check requestInterceptor class if you have created.
Comment: Please check above i have added my urlrewrite.xml(which is working with simple db integration with mysql)
Comment: Have you checked your requestInterceptor class, i think there should be redirection
Comment: I found the problem there was a wrong redirect in one of my custom interceptor. Thanks for your help
Answer: There was a wrong redirect on my request interceptor, after removing the unnecessary redirect it started working.

LDAP integration with Spring


how to override material UI .Mui-selected on ListItemButton component

Question: I have a list item button with a selected prop. That I would like to style in my createTheme() I'm trying to override the selected properties, but I can't get it to work.
//Navbar.js
<ListItemButton
   component={Link}
   to='/'
   selected={value === 0}
>

//primaryTheme.js
export default createTheme({
components: {
    MuiListItemButton: {
      root: {
        '&$selected': {
          color: '#5FBB7D',
          backgroundColor: '#F0F3F3',
        },
      },
    },
  },
})

Answer: If you just make a overwrite in one behavior in your component, like a 'selected', you can use attribute 'sx' in your tag component. Looks like this:
<ListItemButton sx={{
        '&.Mui-selected': {
          backgroundColor: 'rgba(220, 0, 50, 0.1)'
        }
      }} selected={0}>
     <ListItemText primary={'label in item selected'} />
</ListItemButton>

i hope this helped you
Comment: this is good but I had to mark the other answer as I was looking for how to customize my `createTheme()`. Good to know though for future reference.
Answer: In MUI v5 they switched JSS to emotion so selecting with the dollar sign won't work anymore. You can target the component state using the className instead.
export default createTheme({
  components: {
    MuiListItemButton: {
      root: {
        '&.Mui-selected': {
          color: '#5FBB7D',
          backgroundColor: '#F0F3F3',
        },
      },
    },
  },
});

Answer: styleoverrides is missing in previous sample:
MuiListItemButton: {
   styleOverrides: {
      root: {
        '&.Mui-selected': {
          color: '#5FBB7D',
          backgroundColor: '#F0F3F3',
        },
      },
    },
  },


Codeigniter a simple way to get config-like array from cache folder

Question: I have some data in array format which I wrote to a file in application/cache folder.
Format is:
$extra_data['some_key'] = 'some_data';

It is not directly about site config so I don't want to put it in application/config. Yet, in some cases, I need to reach this $extra_data inside the controller or model.
What I do is,
1) define variable in controller
class pages_model extends CI_Model
{
  var $extra_data;

2) inclulde the cache file and associate it with above variable,
  function __construct()
  {
     parent::__construct();
     @include_once APPPATH . "cache/extra_data.php";
     $this->extra_data = $extra_data;
  }

3) get the class variable as variable then use it:
function func_name()
{
  $extra_data = $this->extra_data;

This is the way I am using, but I am not sure that it is the correct or efficient way.
Thanks for any idea and suggesstion.
Answer: How about extending the Loader library with a cache()?
Then you can call it like:
$this->load->cache('extra_data');

libraries/MY_Loader.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Loader extends CI_Loader {

    /* Load custom cache values */
    function cache($str = '') {

        $CI =& get_instance();

        $data = array();
        $path = APPATH . "cache/{$str}.php";
        if (file_exists($path)) {

            include $path;
            $data = $extra_data;

        }

        $CI->$str = $data;

    }

}
Comment: Out of curiosity why call `file_get_contents($path)` rather than `file_exists($path)`?
Answer: Why dont you create a file in config folder that is called cache.php
in the file just put the data like this
$config['some_key'] = 'some_data';

then you can use this code in your construct
    $this->load->config('cache', TRUE);
    $extra_data = $this->config->item('cache')

I know its not config thing,  but since you are placing them on separate file it will be better way to use them
Comment: if no more answers follow i will have to eventually use this  way.


chown on items in nfs mount get wrong user

Question: I have an nfs share mounted on my linux box.  If users create files or directories, everything works fine and the newly created item is owned by that user.  However if root goes in and does a chown on an item, it ends up being owned by 32547.  Something similar happens with groups, it ends up as 1310644168. [Edit: I just noticed the number changes based on every time I restart nfs on the server.  So if I restart nfs and remount it on the client and then I do a chgrp test1 dir2, it ends up with group 28772371144]
On the server hosting the share, idmapd uses Method = static.  The options in /etc/exports are rw,insecure,sync,no_all_squash,no_root_squash.
On the box that has it mounted, fstab has the following options: bg,intr,soft,timeo=5,retrans=5,actimeo=10,retry=5
What do I need to do to allow root to change the owner or group of items in the share?
Thanks in advance.
Answer: I finally found this item: https://www.novell.com/support/kb/doc.php?id=7014266
Basically to make it work on the RHEL server I had to do:
<code> echo 1 > /sys/module/nfsd/parameters/nfs4_disable_idmapping
</code>
Now everything just works.


jQuery client-side and Java server-side - Alternatives to JSON?

Question: I have a project in Flex (client) and Java red5 that I would like to move to jquery for the client. I would like to reuse some parts of the Java server-side code, and use Java's jQuery support.
Are there other solutions that I could use for the communication with the server?
Comment: [JSON](http://json.org/), as well, is only a way of marking up data in a format that a browser can easily interpret into a native JS object/array. See [JSON in Java](http://json.org/java/) and [JSON in Javascript](http://www.json.org/js.html). It's typically used to send data between the client/server, instead of GET/POST or XML.
Answer: JSON is probably your best bet, very simple and well supported in both Java and JQuery.
Answer: Yes, I've read that http://www.playframework.org is an excellent framework for building Java-based RESTful web services.  This way, you can easily integrate jQuery and JSON requests with your Java web service.
This site, http://coffeebean.loicdescotte.com/2011/01/how-to-export-objects-to-json-with-play.html, has a great example of how to export content as JSON.
As for the jQuery itself, check the doc's or start with something like this:
<code>$.ajax({
  url: "your-web-service.php",
  context: document.body,
  dataType: "json",
  success: function(data){
    // do something with data
    $(this).addClass("done");
  }
});
</code>
Answer: JSON keeps things simple but you could also use XML as your data interchange format. jQuery plays well with both JSON and XML. If you were hoping to do something like SOAP I suppose it could be done but I'm pretty sure jQuery doesn't exactly do SOAP out of the box.
As far as moving to PHP goes, in your situation I wouldn't bother. If your app server is running securely, solidly, and fast enough then why even consider a change?


Bash Script : Execute unix commands inside a remote server

Question: I am trying to login to Server B from Server A and perform simple UNIX commands on Server B using a shell script. The code is as follows. But ls -al is displaying the result of Server A and not the one that is logged on to i.e Server B. Any inputs are highly appreciated. Thanks
#!/bin/bash

clear
sshpass -p password ssh hostname
ls -al
exit

Answer: When the shell interprets a script file, it creates a child process to
execute each command line.  So, the command lines after sshpass -p password ssh hostname are not actually executed inside the ssh
session to hostname, but in the host where the bash instance is
running.
To achieve what you want, you can check ssh(1) usage line and note that there is a [command] argument, that says:

If command is specified, it is executed on the remote host instead
  of a login shell.

So, one way to do it is sshpass -p password ssh hostname ls -la. Another way which can provide some more flexibility is:
#!/bin/bash

clear
cat | sshpass -p password ssh hostname <<EOF
ls -la
EOF

Which would make ssh start a login shell in the remote host and pass
to its stdin the lines provided in the Here Document.  The remote
shell would then interpret those strings as commands and execute them.
Answer: If you just want to run ls -al on the remote server, put it on the same line as the ssh command like
sshpass -p password ssh hostname ls -al

it will automatically exit when it gets to the end of the command so you don't need to put exit
Also, if you're going to be doing this and don't want to interactively enter the password, you might want to look at sharing public/private keys and using that so it won't ever ask for a password (unless you password protect your private key)