Query about formula for independent events

Question: According to my lecture notes (beginner probability & stats student here!), I am told that if events X and Y are independent, then P (X ∩ Y) = P(X)P(Y). I am further told that, in general however, P(X ∩ Y) is usually not equal to P(X)P(Y).
I am given a very simple example problem: a bag contains 8 green marbles and 3 blue marbles. Two marbles are drawn from the bag one after another, with the second marble being drawn only after the first marble is replaced. Find the probability of drawing a green marble in the first draw and then a blue marble in the second draw (one after another, with replacement). Answer is simple: just take 8/11 multiplied by 3/11 to get the answer. I am told that I can do this because the events are independent hence I can use P(X ∩ Y) = P(X)P(Y). Here, X is the event that you draw a green marble in the first draw and Y is the event that you draw a blue marble in the second draw.
My problem arises from something I observed from another problem I am given. In this example, the marble is NOT replaced. If the question remains the same i.e. find probability that I will draw a green marble on the first draw and then a blue marble in the second draw, then here I am told the answer is 8/11 x 3/10 since the total number of marbles decreases by 1 after the first draw. I am taught to visualise this by drawing a tree diagram. The thing is, in this case, aren't the two draws NOT independent, precisely because my first draw decreases the total number of marbles in the bag thus affecting the probability of my second draw? And yet, the equation P(X ∩ Y) = P(X)P(Y) still holds - and I'm told this equation is only for independent events and doesn't happen if that's not the case. Here, X is the event that you draw a green marble in the first draw and Y is the event that you draw a blue marble in the second draw.
Please help me reconcile this apparent contradiction, thanks :)
Comment: What exactly is your $X$ and $Y$ in the second case?
Comment: Have edited my post to indicate this (in bold, for the first case too). Thanks!
Answer: You are right in noting that $\mathbf{X}$ and $\mathbf{Y}$ are not independent in the second example. However, the identity $P(\mathbf{X} \cap \mathbf{Y}) = P(\mathbf{X})P(\mathbf{Y})$ has not been used in this example. Instead, the answer is evaluated using the expression $P(\mathbf{X} \cap \mathbf{Y}) = P(\mathbf{X})P(\mathbf{Y|X})$, which is the definition of conditional probability. Note that $3/10$ is not equal to $P(\mathbf{Y})$ in the second example, instead it is equal to $P(\mathbf{Y}|\mathbf{X})$. You can calculate $P(\mathbf{Y})$ using the total probability theorm; however, this I will leave to you as an exercise :).
Answer: You are probably confusing the difference between $P(X \cap Y)=P(X)P(Y|X)$ where $P(Y|X)$ is probablity of $Y$ happening given that $X$ happened and independence equation.. This equation, whether or not $X,Y$ are independent, always holds.
In the second case, in calculating $P(X\cap Y)$ You did not use $P(X\cap Y)=P(X)P(Y)$ but rather $P(X \cap Y)=P(X)P(Y|X)$. When you found probability of picking blue marble, you already assumed that you picked a green marble on first draw. That corresponds to $P(Y|X)$, not $P(Y)$.
Let's calculate $P(Y)$. Drawing a blue marble in second draw can happen in two different ways: you either have $GB$ or $BB$ (green first, blue second and two blues in a row). So
$$
P(Y)=P(GB)+P(BB)=P(\text{second draw is $B$} | \text{first draw is $G$}) \cdot P(G) + P(\text{second draw is $B$} | \text{first draw is $B$}) \cdot P(B)=\frac{3}{10}\cdot\frac{8}{11}+\frac{2}{10}\cdot \frac{3}{11}=\frac{3}{11}
$$
Then you can see, $P(X\cap Y)=\frac{8}{11}\cdot \frac{3}{10} \neq \frac{8}{11}\cdot \frac{3}{11}=P(X)P(Y)$. So indeed the two events are not independent.
The moral is, always identify what events you are referring to. In this case you confused the events $Y$ and $Y|X$, leading to a false contradiction.

In fact, you can see that if $X,Y$ are independent, $P(X)P(Y)=P(X \cap Y)=P(X)P(Y|X)$ so if $P(X)\neq 0$ then $P(Y)=P(Y|X)$. So in literal terms, $X,Y$ are indepent if and only if $P(Y|X)=P(Y)$, that is, probability of $Y$ does not depend on whether or not $X$ happened (ie independent in intuitive sense).
Comment: Oh, now I see. Thank you so much!!


get child element using xpath and php

Question: I have this sample xml file:-
<products>
   <product_id value="1">
       <tab_id value="251">
            <dist_region value="5" />
            <dist_region value="10066" />
            <dist_region value="10069" />
       </tab_id>
   </product_id>
</products>

I am trying to get tab_id child element using XPathand I want result in set of child elements.
My expected output is as follows:-

dist_region,dist_region,dist_region

MY XPATH:-
$tab = $product->xpath('//tab_id/*');

Can anyone suggest what is the XPath to get child elements?
Thanks.
Comment: Can you show your code?
Comment: @NullVoid jsut try this xpath `$tab = $product->xpath('//tab_id/*');`
Comment: Are you giving me a suggestion or you have tried that XPath?
Comment: What's wrong with your xpath? It looks good to give those children. What's your question??
Comment: What does make this question different from your previous one? [how to get all attribute using php xpath](http://stackoverflow.com/questions/16646379/how-to-get-all-attribute-using-php-xpath)
Answer: The xpath you tried works for me. So, Try the next code:
$sxml = new SimpleXMLElement($xml);
$xpath = $sxml->xpath('//tab_id/*');

$array = array();

foreach ($xpath as $child)
{
    $array[] = $child->getName();
}

echo implode(',',$array);

It gives you your desire output: dist_region,dist_region,dist_region.
Been $xml your XML file.
Comment: I slightly edited your answer: You don't need to cast an array to an array; (also) you should not cast anything to an array you foreach over (that is bad practice in PHP); `getName()` has the actual name of the element - not the value attribute. *If* you want to select all value attributes as array: `echo implode(',', $sxml->xpath('//tab_id/*/@value'));` - :-)
Comment: Thanks @hakre. I didn't knew that :)
Comment: @LuigiSiri if i want to all attribute then what i do? i am try this... `$tab = $product->xpath('//tab_id/ancestor::product_id/descendant-or-self::*/@*');`
Comment: and use this function attributes();
Comment: If you want to get the value attribute, use the xpath hakre recommended: '//tab_id/*/@value'. And inside the for each just append $child to $array. _$array[] = $child;_
Comment: @JackPhp, Did this answer was helpful back then?
Answer: Your XPath should be based on specific condition like value (if it is <tab_id id='256'> then more readable)
$result = $product->query('//tab_id[@value=' . $id . ']/*');

and then loop through it like below
if($result->length){
    foreach ($result as $item):
        echo "Value: ".$item['value'];
    echo "
";
endforeach;
}

Comment: Actually there are such XML files where `id`s are provided and users want to get specific node based on condition. So thought on that way. But I will sure keep your suggestion in mind next time. :) [Here](http://stackoverflow.com/questions/16648243/xml-domdocument-php-get-node-where-attribute-value) is one example.
Comment: Why should there have to be a condition like `@value=' . $id . '`? There is no reason at all for that, you don't need IDs in XML
Comment: `` to get a specific `tab_id` (if there are more) then we can get it. `$id` is assumed that it will be initialized by a required value.
Comment: Sure, but no one asked to get a specific `tab_id` element. Quite the contrary, as in the input example there is only one `tab_id` so having an id would be unnecessary. If there are multiple `tab_id`s, maybe one would process all of them. Or maybe there is some other condition. You are making assumptions which are not given anywhere. You don't need ids, this is not SQL.
Comment: @dirkk I appreciate your feedback but I specified generic solution to keep in mind if there are more nodes and would have to pick specific one based on condition. Although not an issue.
Comment: Maybe one wants to process more nodes? There is nothing wrong about that. Your solution is not generic, it is in fact very specific. I am just picky about this, because people with little XML/XPath knowledge (and maybe a background in SQL) might think after reading your answer that you really should have some sort of id in XML, which is absolutely not true.
Comment: @NullVoid: Even so if, this has been answered already on this website to a large extend. Reference the answer with a hyperlink instead of adding another one - especially as it is not clear what the OP asks for.
Comment: @hakre, Yes. Definitely.

get child element using xpath and php


Jersey2 é diferente de Jersey v2.x?

Question: Estou tentando implementar Swagger no Jersey e existe a implementação para ambos os Jerseys. Querisa saber se Jersey2 é diferente de Jersey v2.x? ou é a mesma coisa.
Answer: Jersey (ou JAX-RS) é uma dependência que auxilia na implementação de servidores RESTful em Java. Essa dependência possui duas versões macros, Jersey1 (ou simplesmente Jersey) e Jersey2, no caso o 1.x ou 2.x indica que seria compatível com qualquer uma delas, sendo assim:
1.x indica que é compatível com 1.1/1.1.1/1.2/1.2.1/etc
2.x indica que é compatível com 2.1/2.1.1/2.2/2.2.1/etc
Lembrando que algumas coisas das versões 1.x podem não ser compatíveis nas versões 2.x e vice versa.

Jersey2 é diferente de Jersey v2.x?


How to pass values to asp pages from javascript?

Question: I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {

            var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
            var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
            var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
            var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
            var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
            var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;

             var stat = document.getElementById('drp_state').value;

            $.ajax({
                async: false,
                type: "POST",
                url: "DealerDetails.aspx/UpdateDealer",
                data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $("#drp_support").get(0).options.length = 0;
                    $("#drp_support").get(0).options[0] = new Option("--Select--", "0");
                    $("#drp_support").unbind("change");

                    $.each(msg.d, function (index, item) {
                        $("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);

                    });

                    $("#drp_support").bind("change", function () {
                        sprtengId = $(this).val();
                    });
                },
                error: function () {
                    alert("Error");
                }
            });

        }

And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
    DataSet update = new DataSet();
    try
    {
      update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
    }
    catch {}
    return update;
}

#endregion

When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
Comment: Please check for any syntax error in your script if other worked functions are not working now.
Answer: There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;

Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr

also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;

Make sure you debug and variables you have defined are initialized.
Answer: remove   static from

public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
  DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
  Int32 DlrLan, Int32 DlrMob)
          {
              DataSet update = new DataSet();
              try
              {
                  update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
              }
              catch { }
              return update;
        }
function btn_upgrade_onclick() {
              var dealerID = "1";
              var dlr = "1";
              var dlrname = "abc";
              var addr1 = "india";
              var addr2 = "delhi";
              var addr3 = "delhi";
              var mobno = "1234567890";
              var stat = "";
              var DlrLan = "123";
              var Dlrddd = "1123";
              $.ajax({
                  type: "POST",
                  url: "AutoComplete.asmx/UpdateDealer",
                  data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
  addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
  + DlrLan + "', DlrMob:'" + mobno + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(data) {
                      $("#drp_support").get(0).options.length = 0;
                      $("#drp_support").get(0).options[0] = new Option("--Select--", "0");
                      $("#drp_support").unbind("change");
                      alert(data);
                      $.each(msg.d, function(index, item) {
                          $("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
                      });
                $("#drp_support").bind("change", function() {
                    sprtengId = $(this).val();
                });
            },
            error: function() {
                alert("Error");
            }
        });
    }


Is it possible to fetch data from a key?

Question: Is it possible to get any user readable data from key like below
uchar DELTA_PUB_KEY[]  = {
0x7c, 0x5b, 0x31, 0x88, 0x25, 0x64, 0x43, 0xaa,
0x34, 0x97, 0x6b, 0x7d, 0x22, 0x9a, 0x56, 0xdd,
0x5e, 0xab, 0x2f, 0xd6, 0x10, 0x34, 0x12, 0x6b,
0x12, 0xfa, 0x34, 0x54, 0x33, 0xee, 0x32, 0xde,
0x13, 0x54, 0x12, 0x23, 0x98, 0x7e, 0xe6, 0xee
0x34, 0x72, 0x91, 0xfb, 0x67, 0x98, 0x56, 0x34
};

I got a requirement to see what is there inside a key similar to above.
And also what is the information I should get with the below command
To print out the components of a private key to standard output:

     openssl rsa -in key.pem -text -noout

Will that command be used to get the required data? I think it is not possible to read any information from a key, but I need your opinion. Please help me in getting the data from a key.
Comment: Why is this tagged `m2crypto`? Your code example doesn't appear to be Python.
Comment: I am a python developer and used M2Crypto in my applications. I thought of knowing if any M2Crypto users is succeeded in reading data from key
Answer: If you have a key in a structured format, such as a PEM-encoded RSAPrivateKey ASN.1 object, then you can use tools such as OpenSSL to print some information. Typically this will just be the labelled parts of the key.
For instance, running openssl rsa -in key.pem -text -noout would produce something like:

Private-Key: (512 bit)
modulus:
    00:bd:50:d9:87:f5:67:0f:61:f2:4d:f9:0b:5c:c5:
    0b:4d:c2:c9:7b:b4:fc:b0:d5:65:0e:ea:b8:36:33:
    3a:18:2d:1a:41:76:e5:46:b3:d3:35:34:29:85:ac:
    d2:2b:c5:d8:0b:30:80:9f:d5:dd:64:c3:d3:61:32:
    f9:67:8c:e9:4b
publicExponent: 65537 (0x10001)
privateExponent:
    38:ad:0f:b2:a8:41:26:55:c8:58:97:8a:53:47:9a:
    4e:b9:55:e0:77:1a:7f:46:23:6f:07:ce:06:4b:e7:
    c4:7c:97:bd:e7:02:f6:0b:28:14:24:d5:b9:48:23:
    a1:2c:01:bf:cd:60:40:a9:42:82:7e:1e:73:71:87:
    4b:58:d5:61
prime1:
    00:f3:0a:f4:7f:48:84:f3:d2:3c:f0:5b:25:d2:f5:
    46:76:b5:cf:7d:d3:39:37:03:ba:56:08:2e:ec:01:
    3b:0c:35
prime2:
    00:c7:68:a1:2e:22:53:03:83:27:f2:28:6a:54:f2:
    57:0c:d6:75:d5:ad:d9:ef:08:75:ab:ac:6b:18:59:
    37:cf:7f
exponent1:
    4a:52:5a:4c:26:18:0a:1b:8b:69:10:e6:73:29:70:
    3f:d2:ff:3d:81:ff:28:14:aa:c1:ae:44:f3:04:b9:
    52:d5
exponent2:
    70:39:37:34:b2:86:8b:9c:7d:97:b0:1d:1f:8f:7f:
    64:2f:32:03:be:a2:be:fe:c0:d2:8b:e7:7d:bd:80:
    46:5b
coefficient:
    00:81:44:0f:d2:71:a7:40:d1:31:43:4e:04:ce:c3:
    e4:67:fb:aa:8a:bc:dc:86:7a:74:7f:65:94:b5:b3:
    b4:f1:23

The example data you supplied doesn't appear to be ASN.1, so I'm not sure what information you could derive from it. It's only 40 bytes, so perhaps it's the modulus of a 320-bit RSA public key? If so, that's incredibly weak and not really worth using.
Comment: Sorry, that is a sample key only as I don't have permission to post the actual key. That is just to show that my key is similar. I have updated 8 more bytes making total of 48 bytes.
Comment: @RajeshKumar Is it a valid sample key? Or just a bunch of random bytes you invented?
Comment: Sorry if it caused any inconvenience to you, but it is a bunch of random bytes
Comment: @RajeshKumar Ok, well it's impossible for me to advise further then. I have no idea what format your data is in.
Comment: Thank you, any way your information has helped me that it is not possible to get any information from key except the labelled parts


Install FreeBSD kernel

Question: I'm trying to setup Asterisk, and one of the pre-installation tasks is setting up zaptel.  I get the message that I need to install the FreeBSD kernel source code to /usr/src.  When I run make buildworld I get the message make: don't know how to make buildworld. Stop
I'm a bit new to FreeBSD so I have no clue on how to proceed.  Any ideas are appreciated.
Answer: starting frome here would be a good idea
Answer: The problem is you don't have any files to build. Start with obtaining the kernel source codes.
Then use link petre provided or use this one

Install FreeBSD kernel


Which doctype should I use?

Question: Which doctype should I use, if I want to use costumizable divs. With divs animation, images moving, setting div opacity, etc.
I've tried to create a div through javascript, setting its background-color, position, width and height, and adding an onmouseover event to it.
Everything works ok untill I wanted to put a doctype at my html.
I've tried the transitional and strict, both made my div disappear.
So I've inserted the HTML5 type of doctype and my div appeared ok.
Well, I want to make my website with html4.
Is it possible?
Comment: If you website stopped working when you added doctype, it means you have errors in there. Run the validation on it.
Answer: Everything I've read lately seems to say that you should just use a plain doctype so the browsers can use the latest rendering standards.
<!DOCTYPE HTML >

Comment: I always use this, its the future, get used to coding for HTML5.
Answer: There are three Doctype versions for Html 4.01
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">

But the best solution is to use HTML 5's one
<!DOCTYPE html >

Answer: Adding HTML5 doctype will cause the browser to read it as a html5 document. You will have to keep it in mind. There is not that much difference in them. HTML5 is just a version with better readability. You will have to consider this when you write your code.

Which doctype should I use?


How to engrave these rest symbols in LilyPond?

Question: The original instrument for the music below is violin, I'm engraving this piece for another instrument using LilyPond v2.20.
How can I make the rest symbols that look like the first line below?
And, what does that measure in between the one with the "3" and the one with the "6" mean? It has curved ends.
Comment: Related: [Arbitrary length full-measure rests in LilyPond](https://music.stackexchange.com/questions/10103/arbitrary-length-full-measure-rests-in-lilypond)
Answer: What you appear to be looking for is \compressFullBarRests. This one uses a combination of rest symbols up to a limit and then this long bar with number on top. This limit is specified by MultiMeasureRest.expand-limit(default is 10), so set this to 1 to have every multi measure rest in that style, and to 0 to even use this style of single rests.
As for the the second rest: I'm not quite sure what this is supposed to mean.
Here is some code:
\version "2.20"

{
  \compressFullBarRests
  \override MultiMeasureRest.expand-limit = #1
  R1*3
  R1
  R1*6
  \time 2/4
  R2
}

Comment: @NicoleNaumann Do not fret, for helping logs matters. Without logs – how would we have fretboards? And without fretboards, how would there be anything to fret about?
Comment: If you want a multi-bar rest symbol with no number above it (as in the screenshot), insert `\once \override MultiMeasureRestNumber #'stencil = ##f` immediately before the rest in question.  You will also need to change the rest to `R1*2` (rather than `R1`) to get the multimeasure rest symbol rather than a whole rest.
Comment: @NicoleNaumann Talking about logs, I know a joke about logs. It basically goes something like that: After the big flood Noah told each pair of animals to be fertile and to multiply. But the adders said they were adders and thus couln't multiply. Later Noah went around to check if everything was right. Suddenly he sees the two adders at a big tree, busy with reproducing. He asks the adders: "I thought you were adders and couln't multiply?", to which they respond: "Ah, but by logs we can!"
Comment: @NicoleNaumann Yes, that is true. The assumption was that `\compressFullBarRests`would be too easily confused with `\compressMMRests`.
Comment: Thank you very much @lazy, your answer helps a log!
Comment: oh no, what a jokeful typo I've made XDDD !
Comment: just FYI, from LilyPond V2.21 on, \compressFullBarRests is renamed to \compressEmptyMeasures, according to the log here: https://lilypond.org/doc/v2.21/Documentation/changes/index.html

I'm using V2.23 now, because its new notation for gliding fingers is a must in my music notes, my instrument uses gliding finger very often. https://lilypond.org/doc/v2.23/Documentation/notation/inside-the-staff#gliding-fingers
Answer: If the special form of the second rest is to convey any meaning, it likely depends on what is happening in the other parts.  My guess would be that there is some variable amount of time spent here, due to a cadenza or spoken passage or stage instructions getting executed.
Comment: @NicoleNaumann:  See my comment on the other answer.
Comment: Yes, I think this is the case. This note is for the violin solo part of a violin concerto. You can see this on YouTube: https://www.youtube.com/watch?v=u0atl2wikzE

The part I posted is the very beginning of this converto. Do you happen to know how to engrave this "freely empty" notation using LilyPond?

How to engrave these rest symbols in LilyPond？


How to get a JSF resource bundle property value in backing bean?

Question: I am using JSF 2. I am trying to resolve a message bundle reference dynamically the a managed bean property. The value contains the bundle name as well as the key. This is required as the value may come from one of a few different bundles. I have tried many permutations, but the value from the bean seems to be always resolved as a literal String (outputting with EL brackets) and the bundle is never called to resolve and return the value. Any ideas?
I have tried:
#{bundle['key']}
${bundle['key']}
bundle['key']

They are outputted exactly as-is, also in a <h:outputText>. It works fine if I write it directly in the page. My theory is that JSF doesnt realise it has to process the String as an expression. Is there some way to force it?
Answer: EL will only be resolved in the view, not in the model. It would otherwise be a huge EL injection attack hole which allows endusers to enter arbitrary EL expressions in input fields and have them resolved. No, you cannot force it in any way.
You need to resolve it yourself. You can do that by either evaluating it programmatically using Application#evaluateExpressionGet():
FacesContext context = FacesContext.getCurrentInstance();
String value = context.getApplication().evaluateExpressionGet(context, "#{bundle['key']}", String.class);
// ...

Or, in this particular case, by just using the ResourceBundle API directly like as JSF is doing under the covers:
ResourceBundle bundle = ResourceBundle.getBundle(basename, FacesContext.getCurrentInstance().getViewRoot().getLocale());
String value = bundle.getString("key");
// ...

Comment: Thank you BalusC for your prompt and helpful response, this has answered my question.
Answer: Try this..
Resource Bundle referenced by msg
USD=$

xhtml code:
<c:set var="key" value="#{managedBean.currencyCode}" />
<h:outputText value="#{msg[key]}"/>

This should work..


Using SSH to upgrade from PHP 5.1.6 to PHP 5.3

Question: I have a virtual server with PHP 5.1.6. How can I upgrade to PHP 5.3 using SSH?
Thanks in advance,
John
Comment: It depends on several aspects. What is your distribution/version?
Comment: It sounds like you are running Red Hat Enterprise Linux or CentOS 5.5. See:

http://serverfault.com/questions/221251/how-do-i-install-php-5-3-on-centos/222034#222034
Answer: Depending on the server operating system / linux flavour it might be as easy as:
yum update php
or
apt-get install php
Be aware this will update you to the latest version of php not necessarily 5.3, also be aware this might break things to proceed with caution!
if your running a redhat based system you should also be able to find a PHP 5.3 RPM which you can install with rpm -uvh rpmname.rpm if you need a specific version of php that yum can't provide.
Comment: When I tried the yum update is said "yum: command not found"
Comment: in which case your probably not running a redhat based operating system try cat /etc/*-release and paste the result into your question.
Answer: download the new version of php and compile it.
Answer: Its depend in many things:

What distro you have.
What version of PHP you wont to use.
Is that necessary, because some php
versions 2.2.x some functions.

After you decide, you can login to your server using either ssh client such as Putty, or from command line and follow steps.


Can I find the term depth via $node without resorting to a taxonomy_get_tree or an SQL query?

Question: I'm trying to find all terms in a vocabulary associated with the current node, that do not have any children.
The most obvious way might be to use taxonomy_get_tree() and match with the returned array to find the childless. Another way is to use a function like this one, and it involves a MySQL query. While my current taxonomy is small and the performance concerns are minimal, I would like to avoid this if this info is already available somewhere.
So, how can I find the depth of a taxonomy term, in a more performance friendly way?
Answer: The data for taxonomy is in the database. If you want to get that data there is no way to do so without running a database query.
Any function that retrieves this data (including taxonomy_get_tree() and the function you link to above) has to run database queries to get at the data.
taxonomy_get_tree() is a bit heavy so I'd advise using the term_depth function you link to. If you want to increase performance slightly you can improve that function to offer a static page load cache. This will only make a difference if you call the function more than once in a single page load though:
function term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_result(db_query("SELECT parent FROM {term_hierarchy} WHERE tid = %d", $tid));
    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + term_depth($parent);
    }
  }

  return $depths[$tid];
}

Short of building your own cache mechanism that doesn't rely on the database (which would be a massive amount of overkill for this situation) I don't see any way of making this more performant.
Comment: C'mon Drupal, it was just *one more* detail, aside from the fairly exhaustive data inside $node :( This would have made my life so much more easy!
Comment: Thank you for the suggestion on making it a static variable. That will indeed help the speed...
Answer: Drupal 7 version of Clive's answer:
/**
 * Find the depth of a term
 */
function term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_select('taxonomy_term_hierarchy', 'th')
      ->fields('th', array('parent'))
      ->condition('tid', $tid)
      ->execute()->fetchField();

    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + term_depth($parent);
    }
  }

  return $depths[$tid];
}


what is the purpose of std::set>?

Question: I'm trying to dissect this websocket++ example https://github.com/zaphoyd/websocketpp/blob/experimental/examples/broadcast_server/broadcast_server.cpp
At line 126, there is typedef std::set<connection_hdl,std::owner_less<connection_hdl>> con_list;.  I'm wondering why it isn't merely typedef std::set<connection_hdl> con_list;.
I've read How does the Comma Operator work and http://en.cppreference.com/w/cpp/memory/owner_less but I'm not sure what the purpose is.
What is actually stored in the std::set?  What does std::owner_less actually do?  What is the purpose of making a container with this structure instead of storing the connection_hdls themselves?
Comment: This has nothing to do with the comma operator, and the page you linked to for `std::owner_less` should answer your question directly.
Comment: BTW, `connection_hdl` is a `std::weak_ptr`.
Comment: `std::set` takes multiple template parameters, but only the first is explicitly required; the rest have default types if you don't define them. The second parameter is a binary function used for sorting.
Comment: @Joe : If you read the page you linked to, you would know that `std::weak_ptr<>` has no `operator<`, so it simply wouldn't compile without a special comparitor. ;-]
Comment: @ildjarn ohhhhhhhhhhh, ok.  I'm new to c++, so it took a while to sink in lol.  you made it much clearer.  ty!
Answer: This has nothing to do with comma operator. A set<T> requires that T be less-than-comparable, i.e. operator < should be defined for T. The reason for this is that the set keeps its elements in an ordered fashion(via one kind of tree or another). You can supply a set with a second template argument - a functor that compares two elements so that the set can use that comparison. std::owner_less is a predicate template that operates on shared and weak pointers and performs owner-based (as opposed to value-based) ordering.

what is the purpose of std::set>?


Lack of memory (memorylessness)

Question: The purpose of this question is to gather material about "lack of memory" and to add new ideas about that.
If the conditional distribution of a given distribution is equal to unconditional distribution then that distribution possesses a "lack of memory" property. The exponential distribution contains "lack of memory". So my questions are
1) Is there any other distribution which has "lack of memory"?
2) What special properties are associated with exponential or other distributions (if exist) because of "lack of memory"?
Please provide interesting examples on applied side which will be helpful for learners to understand lack of memory. One example is here.
Comment: For Q1, the wikipedia page you link shows that by the definition of Memorylessness ($P( T>s+t | T>s ) = P(T>t)$), one can derive the only cont. distribution with the property is the exponential. I believe that if you assume a discrete distribution, the only solution is geometric.
Comment: @Cam.Davidson.Pilon yes, Geometric distribution posses "lack of memory", solution is [here](http://malaysia.answers.yahoo.com/question/index?qid=20110218001729AAFCwLH)
Comment: I'm more interested in the *if and only if* part, and yes, the wikipedia article you linked suggests that.
Answer: You have misstated the condition of memorylessness in your question.  A random variable $T \geqslant 0$ is said to have the memoryless property if it has the same distribution as $T-s|T>s$ for all $s \geqslant 0$.  If $T$ is interpreted as the time until some event then we can interpret memorylessness as saying that the distribution of the remaining time to the event is not affected by the elapsed time.
It is easily shown that the exponential distribution is the only continuous distribution with this property, and the geometric distribution is the only discrete (integer) distribution with this property.  Since memorylessness implies a particular distributional family in either case, formally speaking, every property of those families is a logical implication of memorylessness.

Lack of memory (memorylessness)


Additional Configuration to disable anonymous session cookies?

Question: I am running a clean install of Pressflow 6.28. I have set the following configurations:
Cache Mode: Normal;
Min Cache Lifetime: 5 minutes;
Page Cache Max Age: 1 day;
I have installed no contributed modules and have disabled all optional modules that ship with Pressflow.
I am seeing inconsistent behavior with setting session cookies with anonymous users. Sometimes a session is not set, but most of the time it is. When I login and logout, session remains set. If session is not being set and I run 'drush cc all' it begins to be set. I am wondering if there is perhaps some additional configuration I may be missing.
Comment: Pressflow won't disallow anonymous sessions altogether because sometimes they are needed (eg. for shopping cart). Anonymous visitors who don't login should not get session cookies, that's the only difference from standard Drupal in this respect IIRC. So I think what you are seeing is expected behaviour. Shouldn't be a problem anyway for most sites.
Answer: Make sure the $cookie_domain is set properly in settings.php, often if it's not set to the correct domain, particularly in proxy situations, you'll see inconsistent login behaviour.


Pool data for systematic review

Question: I am new to this website and to statistics as well. Currently I am writing a systematic review on complications and reoperations after distal radius fractures(Systematic review on the comparison of complications and reoperations after plaster casting, K-wire fixation, Kapandji intrafocal pinning, external fixation, dorsal plating, volar plating and intramedullary fixation of extra-articular distal radius fractures in adults).
I collected all the data and got stuck on the statistics. I tried to look for it in books, Google and YouTube but couldn't find the necessary information.
How do I pool the data shown below? And secondly how do I compare the pooled data from different treatment modalities? Your help would be highly appreciated!!!!
<code>Study   EF complications    EF total study population   Compl Rate
1   3                   23                          0,130434783
2   2                   20                          0,1
3   8                   30                          0,266666667
4   1                   16                          0,0625
5   31                  39                          0,794871795
6   26                  75                          0,346666667
7   22                  75                          0,293333333
8   0                   20                          0

Total   93                  298                         0,312080537
</code>
Comment: Persumably that is just a small part of your data-set? Can you give us more detail about what you do understand about meta-analysis and what you do not so we know what advice to offer? At the moment we have not much to go on.
Comment: Thank you for your fast reply. Yes, it is a small part of my data set. I want to know how I can pool the complication rate. This data are from the treatment with an external fixator. But I have similar data on other treatment modalities like volar plate osteosynthesis or k-wire fixation. How can I compare the pooled complication rates (what test do I use)?
Answer: You will need to set up your data-set with a column for treatment modality. You then need to decide on which transformation of the complication proportion you want to analyse, choices include: raw proportion, log transformed, logistic transformed, Freeman-Tukey arcsin transformed. When you get your software to do the transformation it should also give you the standard errors of those values. You then use inverse variance weighting to synthesise them In your case you also need to include treatment modality as a moderator so make sure your chosen software does meta-regression (which is what meta-analysis with one or more moderators is called. The moderator results will then tell you how much treatment modality affects the outcome.
One caution: I am assuming that each line in your final data-set comes from a separate study. If in fact you have a number of trials each of which compared two or more of the treatment modalities then you need something much more complicated to take account of that.
Comment: Thank you! I have all my data in a SPSS-file and tried to transform it. But I can't find any of your suggested transformations. And how do I choose what transformation to use? Can I send you my database?
Comment: I do not use SPSS I am afraid so cannot comment on that. You might look at the tag wiki http://stats.stackexchange.com/tags/meta-analysis/info for further information. I use this site to offer advice but I am unable to analyse people's data-sets. Sorry.
Comment: I understand. Thank you very much for your help. What statistical software do you use, so I can follow your instructions? I appreciate your help very much!!!!
Comment: There is software available in Stata. Here is their FAQ https://www.stata.com/support/faqs/statistics/meta-analysis/ There is also software in R which is summarised in the CRAN task view http://CRAN.R-project.org/view=MetaAnalysis I use R and the metafor package whose home page is here http://www.metafor-project.org/doku.php
Comment: I have read the book Introduction of Meta-Analysis by Borenstein which gives a good inside into meta-analysis. I have tried different programs like RevMan, RStudio with the Metafor package, SPSS with Wilson Macros. RevMan is very easy but doesn't work for my analysis because the data from the different treatments are from different studies and not directly compared in the studies. For weeks I have been working on the statistics. Could you please help me? I am willing to pay for your help.

Pool data for systematic review


Relationship between $Var(X)$, $Var(Y)$ and $Cov(X,Y)$ for random variables with zero mean

Question: I have two correlated random variables $X$ and $Y$, both with zero mean.
Are there any relationship/constraints between $Var(X)$, $Var(Y)$ and $Cov(X,Y)$, apart from the obvious $Var(X) > 0$ and $Var(Y) > 0$, or can they assume any value, provided that the two obvious constraints are met?
And if I go to higher order moments, e.g. $E[X^3]$, $E[Y^3]$, $E[XY^2]$, $E[X^2Y]$, are there non obvious relationships/constraints between those moments, the variances and the covariance?
Answer: When $\mathbb E[X]=\mathbb E[Y]=0$,
$$\text{Var}(X)=\mathbb E[X^2]\quad\text{Var}(Y)=\mathbb E[Y^2]\quad\text{Cov}(X,Y)=\mathbb E[XY]$$
and
$$2\vert\text{Cov}(X,Y)\vert\le\text{Var}(X)+\text{Var}(Y)$$
(since $\mathbb E[(X\pm Y)^2]>0$) and
$$\text{Cov}(X,Y)^2\le\text{Var}(X)\text{Var}(Y)$$
(by Jensen or Cauchy-Schwarz inequality).
When the moment generating function $\mathfrak m(t)=\mathbb E[e^{tX}]$ exists (in a neighbourhood of $0$), it expands as
$$\mathfrak m(t)=\sum_{i=0}^\infty \frac{\mathbb E[X^i]t^i}{i!}$$
which specifies constraints on the moments (as, e.g., $\mathfrak m(t)$ being positive near zero).
The most general result on moments is that

A sequence of numbers $(m_n)$ is the sequence of moments of a measure μ
if and only if a certain positivity condition is fulfilled; namely,
the Hankel matrices $H_n$, $${\displaystyle (H_{n})_{ij}=m_{i+j}}\quad 1\le i,j\le n$$
should be positive semi-definite.
Answer: They should be able to take any reasonable values, unless you introduce more constraints. For example consider
\begin{equation}
\begin{pmatrix} X \\ Y
\end{pmatrix} \sim N \left\{\begin{pmatrix} 0 \\ 0
\end{pmatrix}, \begin{pmatrix} \sigma_X^2 & \rho \sigma_X, \sigma_Y \\ \rho \sigma_X \sigma_Y & \sigma_Y^2
\end{pmatrix} \right\}.
\end{equation}
In this distribution, we can specify any $\sigma_X = \text{Var}(X) \geq 0$ and any $\sigma_Y = \text{Var}(Y) \geq 0$. We can also specify any $\text{Cov}(X, Y)$ such that $-\sigma_X \sigma_Y \leq \text{Cov}(X, Y) \leq \sigma_X \sigma_Y$ which is one the mathematical ("obvious"?) constraints of covariance; you can specify any valid value for the covariance by specifying an appropriate correlation coefficient, $\rho$.
For constraints on higher order moments, there are in general no "obvious" unless perhaps you have applied additional constraints to your problem.
Finally, the word "obvious" is cursed in mathematics; what is obvious to you may not be obvious to me, and vice-versa.
Comment: Thank you for your answer, and yes, I agree that I should not have used the "obvious" word, which reflects my poor knowledge of the subject: for me only some very small pieces of basic knowledge are "obvious".
Comment: So the restriction that $-\sigma_X \sigma_Y \leq \text{Cov}(X, Y) \leq \sigma_X \sigma_Y$ is a consequence of $X$ and $Y$ having a bivariate normal distribution, and doesn't necessarily apply to other distributions for which $|\text{Cov}(X, Y)|$ can exceed $\sigma_X \sigma_Y$?


How to prove $\sin(1/x)$ is not uniformly continuous

Question: How do I go about proving $f(x)=\sin(1/x)$ is not uniformly continuous?
(Or: different question, but same intention* how do I prove that $x\sin(x)$ is not uniformly continuous)
*I'm trying to grasp how one would prove $f$ is not uniformly continuous for functions other than the simple $x^n$. I have seen one technique being to set an $\epsilon$ and set $x, y$ in the form of $\delta$ (e.g. $\delta/2$, etc.) then subsequently proving that $f(x)-f(y)\ge\epsilon$
Comment: @Changwei: $\sin(x)$ is close to $x$ when $x$ is small, but  $\sin(1/x)$ is not close to $1/x$ when $x$ is small.  I am not sure what you intend by your hint.
Comment: Sketching a graph would be edifying. Note that you can select an interval $(\delta_1,\delta_2)$ (''near 0'') of arbitrarily small length such that $|f(\delta_2)-f(\delta_1)|=2$.
Comment: You may attempt to prove why $\frac{1}{x}$ is not uniformly continuous. Since $Sin[x]$ is close to $x$, the proof should be easy manipulation of symbols.
Comment: @Jonas Meyer: I do not mean to compare both functions when they are small. I mean the two functions are "similar". So an analogous proof should be able to constructed if the author notice $Sin[x]$ has a maximum difference of 2 near the point $\frac{1}{x}$ is not well-defined. In fact the author's statement is not clear, because by stating "is not uniformly continuous" one is assuming the function is in some underlying domain already. If it is an close interval with no singular points we may just apply Cantor's theorem.
Answer: Ultimately a very brief solution could be given to this problem, but I decided to write in some detail how you might approach it.
You want to negate the following: $$\forall \varepsilon>0,\exists\delta>0,\forall x,y, |x-y|<\delta\implies|f(x)-f(y)|<\varepsilon.$$
You can write out what that negation is rather mechanically, swapping universal and existential quantifiers, until you finally negate the implication by ensuring that $|x-y|<\delta$ and $|f(x)-f(y)|\geq \varepsilon$.  See here for a discussion of dissecting analysis problems like this by Tim Gowers.
That is, you want to prove:
$$\exists \varepsilon>0,\forall\delta>0,\exists x,y,\text{ such that } |x-y|<\delta\text{ and }|f(x)-f(y)|\geq\varepsilon.$$
Before giving the final argument, it is a good idea to experiment in a "backwards" fashion; think about where you want to end up and how you can get there.  Roughly, the conclusion "$|x-y|<\delta\text{ and }|f(x)-f(y)|\geq\varepsilon$" will be saying that $x$ and $y$ will be close while $f(x)$ and $f(y)$ will stay a distance $\varepsilon$ away.  The property of $\sin(1/x)$ that allows this to happen is that it oscillates like crazy between $1$ and $-1$ over smaller and smaller intervals of $x$ values.  So there will be "nearby" $x$ and $y$ such that $f(x)=-1$ and $f(y)=1$.  The distance between the function values here is $2$, while the distance between the input values can be arbitrarily small.  This leads to the conclusion that $\varepsilon = 2$ will be a sufficient choice.
Next, with $\varepsilon$ fixed at $2$, and $\delta>0$ arbitrary but fixed, you need to show that there are $x$ and $y$ with $|x-y|<\delta$ and $|f(x)-f(y)|\geq 2$.  As indicated above, the last part can be achieved by ensuring that $f(x)=-1$ and $f(y)=1$.  For what $x$ and $y$ is it true that $\sin(1/x)=-1$ and $\sin(1/y)=1$?  Use what you know about the sine function to answer this question (I'll leave this to you).  Notice that the choices of such $x$ and $y$ get arbitrarily close to $0$, and in particular you can choose such $x$ and $y$ with $0<x,y<\delta$, which implies that $|x-y|<\delta$.

Largely the same approach applies to $x\sin(x)$, except that its reason for not being uniformly continuous changes.  Now the problem is where $x$ gets very large, and the rate of oscillation doesn't change, but the amplitude does.  A hint is to consider the function values at $x=2\pi n$ and $y=2\pi n + c$, where $c>0$ is "small", as $n$ goes to infinity.
Comment: @Ramit: If somebody doesn't know that $\sin(1/x)$ osciallates when $x$ approaches $0$, that person should learn more about $\sin$ and $1/x$ and $\sin(1/x)$.  There is no need to start the proof before seeing what type of object you're dealing with.  How to check it depends on the function.  E.g., for $\cos(x)/x$, presumably you mean on the domain $\mathbb R\setminus\{0\}$, but it is enough to consider $(0,1)$ as the domain.  Near $x=0$ this function behaves like $1/x$.  If you can show that $1/x$ is not uniformly continuous on $(0,1)$, then you can probably extend the proof to $\cos(x)/x$.
Comment: Here is a useful general fact.  If $ainfinity you get 0, so as you said the x and y get arbitrarily close to 0. So I guess the "idea" is complete, which I get, but I don't know how one would close the actual "proof"
Comment: MathMathCookie: For $x$ I think you want $1/(2\pi k-\pi/2)$.  If you took $k=2$ in your formula for example, you get $\sin(1/x)=1$.  As a step toward finishing the proof you could invoke the fact that for all $\delta>0$, there exists a positive integer $k$ such that $1/(2\pi k-\pi/2)$ and $1/(2\pi k +\pi/2)$ are less than $\delta$.  (This is essentially a restatement of the fact that the sequences converge to $0$, but stated in a precise way to get the desired $x$ and $y$ such that $00$, there exist $x$ and $y$ with $|x-y|<\delta$ but $|1/x - 1/y|>1$.  You can even find formulas for $x$ and $y$ that will work, depending on $\delta$, if you want.
Comment: @JonasMeyer Hello Mr Meyer, thanks for the insightful answer! However I do not understand the last bit where you just concluded $|x-y|<\delta$ that is true. I cannot see the implications that make this true.  Do I have to substitute my $x$ and $y$ into $|x-y|<\delta$?
Comment: @CountDOOKU: that part was a little vague, leaving some work on analyzing the details of when the function is $1$ and $-1$. that happens at sequences converging to $0$ so you can choose them as small as you like, and I left out the details of writing that up.
Answer: Choose two sequences $T_n = \frac{1}{n}$ and $S_n = \frac{1}{n+\pi}$. Their difference goes to zero as $n$ goes to infinity. But $|f(S_n)-f(T_n)|=\left|2 \sin\left(\frac{n+\pi-n}{2}\right)\cos\left(\frac{n+\pi+n}{2}\right)\right|=\left|2 \cos\left(n+\frac{\pi}{2}\right)\right|=\left|2\sin(n)\right|>0$ for $n \in \mathbb{N}$, so the function is not uniformly continuous.


Como criar um vetor sem determinar seu tamanho em Java?

Question: Tenho uma classe TesteAplicacao que é para testar e um a classe Teste com atributos e métodos.
Ao criar um vetor em Java:
Teste[] t = new Teste[10];// veja que teve definir um tamanho

Teria como criar vetor sem tamanho definido igual em C?
Comment: @utluiz provavelmente ele está falando dos *array* definido em tempo de execução disponível no C99. Ou pode estar falando de ponteiros acessados como se fossem *arrays*, menos provável. De qualquer forma, é claro que sempre há um tamanho definido. https://en.wikipedia.org/wiki/Variable-length_array O que no Java é possível fazer direto.
Comment: Qual vetor em C não tem o tamanho definido?
Answer: Simples, use um ArrayList. O array do Java só pode ter tamanho fixo. Existem outras opções, mas quase sempre essa é a melhor.
Usaria mais ou menos assim:
ArrayList<Teste> t = new ArrayList<>(10);
t.add(new Teste());
t.get(0).nome = nome1;
System.out.println(t.get(0).nome);
t.add(new Teste());
t.get(1).nome = nome1;

Coloquei no GitHub para referência futura.
Iniciei a capacidade da lista com 10, mas poderia iniciar com qualquer tamanho. Isto não quer dizer que já terá 10 elementos na lista, apenas que ela já reservou esse tamanho na memória. 10 é o tamanho padrão na implementação atual, então nesse caso específico até não precisaria colocar. É bom usar um tamanho que acha que vai precisar para evitar realocações.
Só lembrando que isso permite ter uma coleção de dados que pode variar de tamanho em tempo de execução sem maiores preocupações, mas o Java permite facilmente definir um array normal sem tamanho determinado em tempo de compilação, igual ao C. O que não pode é ter seu tamanho trocado depois de criado, igual ao C.
Na verdade não existe dado em computação que não tenha seu tamanho determinado em algum momento, o que dá para fazer é determiná-lo o mais tarde possível (sua criação) e poder mudar o tamanho (costuma exigir realocação na maioria dos casos).
O ArrayList é apenas uma estrutura que gerencia as realocações para você.
Comment: Na arrayList como que faço para usar assim `t[0].valor = i; t[0].nome = nome1; t[1].valor = i; t[1].nome = nome1;..........`
Comment: @bigown Sim, a capacidade inicial é 10 -> [doc](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--)
Answer: Se você precisa de uma lista, sem tamanho definido, use Java.util.ArrayList ou LinkedList.
No Java não é possível criar um array com tamanho flexível.
Comment: Na arrayList como que faço para usar assim `t[0].valor = i; t[0].nome = nome1; t[1].valor = i; t[1].nome = nome1;..........`
Comment: com isso você quer adicionar um novo valor (add) ou alterar um valor existente (set)?
Answer: Não exatamente, o tamanho de arrays deve ser definido em algum ponto e você não pode alterar ele após isso. Uma alternativa seria apenas declarar seu array Teste[] t; e definir o tamanho em algum ponto posterior com algo como t = new Teste[size], contudo você ainda fica preso a necessidade de eventualmente determinar o tamanho. Outra, mais flexível, seria utilizar implementações da interface List, por exemplo ArrayList que é essencialmente uma classe que abstrai um vetor e pode possuir tamanho variável.
Exemplo de uso:
// instancia o objeto ArrayList
ArrayList<Teste> list = new ArrayList<Teste>();
// adiciona um item
list.add(new Teste());
// adiciona outro item
list.add(new Teste());
// etc, veja a doc de arraylist para os outros métodos.

Answer: Não é possível criar um vetor com tamanho variável. O que é possível fazer é variar dinamicamente o tamanho do vetor que é criado, como no C99.
Criando array variando o tamanho
Exemplo:
Test[] create(int size) {
    return new Test[size];
}

O código acima cria um novo vetor da classe Test com o tamanho passado por parâmetro. Logo você pode criar esse vetor do tamanho que precisar:
    Test[] array1 = create(10);
    Test[] array2 = create(20);
    Test[] array3 = create(lerEntradaDoUsuario());

Clonando o array com novo tamanho
Embora o Java não tenha suporte a redimensionar arrays, por questões de eficiência no uso de memória, a solução básica se você precisa aumentá-lo é fazer uma cópia do array atual num novo array com o tamanho desejado.
Isso é muito simples usando a classe Arrays do Java:
//cria o array inicial
Test[] array = new Test[10];

//coloca um elemento na primeira posição
array[0] = new Test();
array[0].nome = "Eu";

//imprime o tamanho atual do array
System.out.println(array.length);

//clona o array atual em um novo array com 20 posições
//atribuindo na mesma variável
array = Arrays.copyOf(array, 20);

//imprime o tamanho do novo array
System.out.println(array.length);

//imprime o valor do elemento para provar que ele ainda está lá
System.out.println(array[0].nome);

ArrayList
O exemplo anterior é interessante, mas é mais fácil usar uma implementação que já cuida devidamente disso.
Como já exemplificado em outras respostas, o ArrayList pode ser usado como uma estrutura de dados de tamanho variável.
Por debaixo dos panos, ele faz exatamente o que eu fiz no exemplo acima, isto é, ele tem um vetor interno que é redimensionado quando você adiciona mais elementos do que ele suporta num dado momento.
Answer: Um vetor precisa de um tamanho fixo, se você precisar de um vetor dinâmico pode instanciar um arrayList e usar a função toArray para transformar o array em vetor.
 List<Object> lista = new ArrayList<>();
lista.add("objeto1");
lista.add("objeto2");
Object[] vetor = lista.toArray();


Why is the System.IO.File class static

Question: I was wondering why is the File class static?
There are some methods that makes sense to be static like Create.
But, when I want to move a file I preffer to just specify the new location. The same applies to Copy, Open and more. I guessed this issue was already discussed somewhere, but a search didn't give any results but a general thread of why to create static methods.
I don't say that all the methods in File shouldn't be static, but there sure are methods that should be instance-related.
Answer: There is FileInfo class which has instance methods like CopyTo or MoveTo. But if you are performing single operation on file then it will be more efficient to use static methods of File class instead of creating instance FileInfo object. If you are performing multiple operations, then creating FileInfo will allow to skip additional security checks. Actually File is kind of service, which manipulates files. Maybe class name is not the best one.
Comment: Indeed, and if OP had simply [read the documentation](http://msdn.microsoft.com/en-us/library/system.io.file(v=vs.100).aspx) he would have found this: "The static methods of the File class perform security checks on all methods. If you are going to reuse an object several times, consider using the corresponding instance method of FileInfo instead, because the security check will not always be necessary"
Comment: I had no idea that class exists. It's a weird name for such a class
Comment: They had obviously already used the name "File" for the static class, so "FileInfo" was the best they could come up with. Naming things can be really hard sometimes, just because there are not enough suitable words.
Answer: File is static probably because File is only concerned about creating a connection to the (logical) contents of the (physical) file. FileStream on the other hand is not static, because it represents the data that can be read from the file. Think of File as referring to an address, where FileStream focuses on the content of said address the address. If you think about the separation between the physical container, and the logical contents, the separation begins to make more sense - singleton access to the container, but individualized access to the contents of each container you attach.

Why is the System.IO.File class static


How is /dev populated for Android

Question: I have a driver compiled and running on hardware running Android 4.3. By running, I mean 'insmod gipc' loaded the driver and it ran through initialization. It assigned the major number 243 to the driver as evident in the /proc/devices files. The example code application is looking for the following two files
<code>/sys/class/gipc/gipc1/name
/dev/gipc1
</code>
How should these files be created? Android does not have mknod and does not support udev. I do not really need the file in /sys/class, but without the file in /dev, I cannot access the driver.
Answer: I ended up using the following functions, class_create(), device_create(), and device_create_file() to accomplish this.  Not sure if there is a more preferred way, or a way of having the files automatically created.

How is /dev populated for Android


Does CKEditor5 have an embed button like CKEditor4?

Question: With CKEditor4 I was able to configure the editor to have embed buttons for entities (Webform, Taxonomy, or Node) like this using through Configurations >> Content Authoring >> Text editor embed buttons.

With CKEditor5, I am lost as it has only Drupal media embed.

Note: Merely changing CKEditor4 to CKEditor5 is not breaking existing functionality as of now.
How can I get Entity Embed buttons back in CKEditor5?
Is there any update regarding entity embed button that would be ported to Drupal core?
Answer: This is because the entity embed module does not support CKEditor5 yet - mainly because the way plugins are written in CKEditor5 is different than CKEditor4.
The status looks good. I think you can get it to work with

The latest dev release of the 'entity_embed' module.
A patch for the 'embed' module from https://www.drupal.org/project/embed/issues/3309747
Comment: @VishalKumarSahu - Embed module is a dependency of the entity embed module. You will need the latest dev release of the entity embed module and use the patch for the embed module. I have updated the answer.
Comment: So, I can try working with the embed module to get it work as Drupal Media embed is already there.
Comment: I will try to create another drupal instance for testing and contribute if succeed.


Does the tune of hymn 'With Harps and with Viols' derive from Mendelssohn's Symphony #5 scherzo?

Question: The tune for hymn With 'Harps and with Viols' was written by Philip Bliss in 1874:

Mendelssohn wrote his Symphony #5, 'Reformation' in 1830,
including this scherzo as movement #2:

They sound rather similar to me, yet I've never seen this mentioned anywhere. Could it just be a coincidence, or could Bliss consciously or unconsciously have been influenced by the symphony?
Comment: The rhythms are similar, the melodies are different.
Answer: No, I don't think so. They simply share a short rhythmic motive which is 8. 16 | 4 4 in 3/4. But they differ vastly in terms of melody and structure.

Does the tune of hymn ‘With Harps and with Viols’ derive from Mendelssohn’s Symphony #5 scherzo?


What should be $W$ in $I_W$ when choosing randomly uniformly a point $(x,y)$ inside triangle?

Question: We choose randomly uniformly a point $(x,y)$ inside triangle that it's points are $(0,0)$, $(0,1)$ and $(1,0)$. So we can say that:
$$
f_{X,Y}(x,y)=\frac{1}{S_B}=\frac{1}{0.5}I_{\{0<y<1,y<1-x,0<x<1\}}=2I_{\{0<y<1,y<1-x,0<x<1\}}=2I_{\{0<x<1,0<y<x-1\}}
$$
where $S_B$ is the area of the triangle.
I'm trying to build myself a formula of the indictor $I$ for any three points $(a_1,b_1)$, $(a_2,b_2)$ and  $(a_3,b_3)$. What should be $W$ in $I_W$ if we replace the three points above general $(a_1,b_1)$, $(a_2,b_2)$ and  $(a_3,b_3)$ points?
Answer: By contracting and sliding one edge of a triangle towards its opposing vertex, we can see that this covers the triangle interior completely, and that every point in a triangle can be uniquely referenced by two of its sides as all the triangles are similar.
Define a parameter for each edge, say $\alpha, \beta$, and then:
$$W=\{w=(x,y)+\alpha v_1+\beta v_2 : 0\le \alpha,\beta\le 1\}$$
where $v_1,v_2$ are the vector edges, and $(x,y)$ is their point of intersection.
Answer: In barycentric coordinates
a point internal to the triangle (or any other convex polygon) with vertices ${\bf v}_k$
is given by the weighted average of the verices with positive cooefficients
$$
\eqalign{
  & {\bf p} = \left( {\matrix{   x  \cr   y  \cr  } } \right)
 = {{a{\bf v}_1  + b{\bf v}_2  + c{\bf v}_3 } \over {a + b + c}}\quad \left| {\;0 \le a,b,c} \right. =   \cr
  &  = \alpha {\bf v}_1  + \beta {\bf v}_2  + \left( {1 - \alpha  - \beta } \right){\bf v}_3  =   \cr
  &  = \alpha \left( {{\bf v}_1  - {\bf v}_3 } \right) + \beta \left( {{\bf v}_2  - {\bf v}_3 } \right) + {\bf v}_3
  = \quad \left| \matrix{
  \;0 \le \alpha ,\beta \left( { \le 1} \right) \hfill \cr
  \;\left( {0 \le } \right)\alpha  + \beta  \le 1 \hfill \cr}  \right. \cr}
$$
So $\alpha , \beta$ are the coordinates inside a right triangle with unit sides.
Since
$$
\left( {\matrix{
   {dx}  \cr
   {dy}  \cr
 } } \right) = \left( {\matrix{
   {x_1  - x_3 } & {x_2  - x_3 }  \cr
   {y_1  - y_3 } & {y_2  - y_3 }  \cr
 } } \right)\left( {\matrix{
   {d\alpha }  \cr
   {d\beta }  \cr
 } } \right)
$$
then the Jacobian is constant and non null if the vertices are not aligned.
Therefore a uniform distribution of $(\alpha , \beta)$ will translate in a uniform
distribution of $(x,y)$.


Exists $c \in \mathbb{R}$ where $A \cap (c + \mathbb{Q}) = \emptyset$, where $A$ has Lebesgue measure $0$

Question: Suppose $A \subset \mathbb{R}$ has Lebesgue measure $0$. Does there exist $c \in \mathbb{R}$ such that $A \cap (c + \mathbb{Q}) = \emptyset$, where $c + \mathbb{Q} = \{c + x : x \in \mathbb{Q}\}$ and $\mathbb{Q}$ is the rational numbers?
Answer: First we see that $\mu ( A- \mathbb{Q}) = 0$ indeed, $A- \mathbb{Q} = \bigcup_{q\in \mathbb{Q}}A-q$ therefore
$$\mu ( A- \mathbb{Q} ) =\mu (    \bigcup_{q\in \mathbb{Q}}A-q ) \leq \sum _{q\in \mathbb{Q}} \mu(A-q    )=0$$
So since $A-\mathbb{Q}$ has measure zero there is a $c\not \in A-\mathbb{Q}$ therefore
$$A\cap (c + \mathbb{Q}) = \emptyset.$$
Comment: Hey @clark, do you mind clarifying why you can choose a $c \in \mathbb{R}$ where $c \not\in A - \mathbb{Q}$ since $\mu(A \setminus \mathbb{Q}) = 0$ which then satisfies the claim? Thanks.
Comment: @Darkdub Here $A-\mathbb{Q}=\{a-q|q\in \mathbb{Q},a\in A\}$. Also notice $A\cap(c+\mathbb{Q})$ is non-empty iff $c\in A-\mathbb{Q}$.


VPN Troubleshooting

Question: I'm having continuing trouble with a SonicWall VPN. Does anyone know where I can get a trouble-shooting protocol that can help me find the problem?
Comment: Please be more specific when you ask questions.
Comment: What kind of trouble?  Are you getting error messages?  What's working and what isn't?  Please describe the symptoms of the problem, and there would be less chance of the question getting closed.
Answer: Have you tried SonicWall support?
Comment: e;fb.  Support is the way to go when you have no idea what is going on which is typically the case when no detail is provided.
Comment: Sonicwall is a great place, as mentioned. However, they will likely want a bit more detail as well if they are going to assist with the issue
Comment: Yeah, but at least they're paid to pull teeth.
Answer: To troubleshoot VPN issues use the following steps:

Login to the web management interface
Go to Log -> Categories
Under each of the VPN categories (VPN, VPN Client, VPN IKE, VPN IPSEC, VPN PKI)
Disable your VPN connection
Enable your VPN connection
Go to Log -> View and watch for error messages.

After getting your error messages, go to: Sonicwall's Knowledge base and enter in the error message in the search string.  Usually the error messages are in all capitals, like: NO_PROPOSAL_CHOSEN.
In my experience, most of the problems come down to the setup of the VPN parameters not matching up between each end of the tunnel.  Specifically the ID used for the local and peer IKE IDs.  It is our practice to always use the SonicWALL Identifier as this is the most reliable.
Good luck

VPN Troubleshooting


Calculate formula between integer $i$ and $j$

Question: Background (actually I refers to AES shift row):
A and B are $4$ x $4$ matrices
<code>A = |0 4 8 12 |
    |1 5 9 13 |
    |2 6 10 14|
    |3 7 11 15|

B = |0 4 8 12 |   // no shift
    |5 9 13 1 |   // shift 1 column to left
    |10 14 2 6|   // shift 2 columns to left
    |15 3 7 11|   // shift 3 columns to left
</code>
In $A$, when $i = 0 to 15$ in sequence
In $B$, $j$ equals to $0 ,5, 10, 15; 4, 9, 14, 3; 8, 13, 2, 7; 12, 1, 6, 11$
Question:
How to calculate the formula of function $f(i) = j$ that $f(0)=0, f(1)=5, f(2)=10$?
Comment: Can you rewrite the question using LaTeX? Also, explain what work you have done so far. I don't know what one formula of variable $0, ..., 16$ to present $j$ means.
Comment: I guess the OP is looking for a formula for a function $f$ where $f(0)=0$, $f(1)=5$, $f(2)=10$ and so on down the list.
Comment: I see, inside A $f(0,0) = 0, f(1,0)  = 1, f(2,0)  = 2, f(3,0)  = 3, f(0,1) = 4, f(1,1) = 5 ...$ so moving down a row adds 1 and moving right a column adds 4. Inside $B$, $f(0,0) = 0, f(1,0)  = 5, f(2,0)  = 10, f(3,0)  = 15, f(0,1) = 4, f(1,1) = 9 ...$ so it must be some sort of shifting function.
Comment: According to https://www.wolframalpha.com/input/?i=0,+5,+10,+15,+4,+9,+14,+3,+8,+13,+2,+7+... it would be a(n + 3) = a(n) - 1 (for all n>=1).
Comment: @Axion004: is it possible to calculate the formula use operators (+, -, *, /, reminder...)?
Comment: Please use MathJax
Answer: \begin{align}
f(i)& = \begin{cases}
i & \text{ if } i \mod 4 = 0\\
(i + 4) \mod 16 & \text{ if } i \mod 4 = 1\\
(i +8)  \mod 16& \text{ if } i \mod 4 = 2\\
(i +12) \mod 16 & \text{ if } i \mod 4 = 3
\end{cases}\\
& = (i+4(i \mod 4)) \mod 16.
\end{align}
Here $ \mod $ refers to reminder.


cbind each row from one data to another in R

Question: My dataset looks like this:
df1<-t(data.frame(1,2,3))
df2<-t(data.frame(4,5,6))
colnames(df1)<-c('A')
colnames(df2)<-c('B')
> df1
   A
X1 1
X2 2
X3 3
> df2
   B
X4 4
X5 5
X6 6

How can I merge each row in df1 to df2 so that I have something like this:
A  B
1  4
1  5
1  6
2  4
2  5
2  6
3  4
3  5
3  6

Thanks!!
Comment: Small side note: creating your example data frames would be much simpler as `data.frame(A = 1:3)` and `data.frame(B = 4:6)`.
Answer: You can use expand.grid:
expand.grid(A = df1, B = df2)
  A B
1 1 4
2 2 4
3 3 4
4 1 5
5 2 5
6 3 5
7 1 6
8 2 6
9 3 6

Answer: This question is likely to be a duplicate. Here are three similar solutions:

merge(df1, df2)
expand.grid(A = df1, B = df2)
tidyr::crossing(A = df1, B = df2)
Comment: I didn't realize that I can do that by a simple `merge` command. Thanks!!


Adding view/layouts in already inflated hierarchy in runtime?

Question: I wonder if it is bad practice to add view into view hierarchy in runtime into already inflated view.
Lets consider my example. I have following Activity class hierarchy

Base Activity - some base activity that include basic configuration for lifecycle methods , without inflating layout(setContentView).
SingleFramgentActivity it has setContenview method in onCreate method. Layout for this activity looks following

c
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout android:id="@+id/fragment_container"
                 xmlns:android="http://schemas.android.com/apk/res/android"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:orientation="vertical">

    </FrameLayout
    <ViewStub
        android:id="@+id/stub_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inflatedId="@+id/progress_bar_buttons"
        android:layout="@layout/inflate_stub_progressbar_bg"/>
</FrameLayout>

There are several problems here.
As you can see here, there is one fragment container FrameLayout for holding current fragment as far as it is SingleFragmentActivity.
What I need to do is to add toolbar into my layout and should be present on all fragment inside this activity.
My layout in this case have to look like
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout android:id="@+id/fragment_container"
                 xmlns:android="http://schemas.android.com/apk/res/android"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:orientation="vertical">

    </FrameLayout>
    <include
        android:id="@+id/toolbar"
        layout="@layout/include_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"/>
    <ViewStub
        android:id="@+id/stub_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inflatedId="@+id/progress_bar_buttons"
        android:layout="@layout/inflate_stub_progressbar_bg"/>
</FrameLayout>

There are several problems here.
1. I have already inflated layout in my SingleFramgentActivity class. So I only have way to add to already inflated hierarchy, getting root view and calling addView method. If so please see next question.
2. I need only to add some view, I need to add layout file to view hierarchy BETWEEN two already existent views. FrameLayout and ViewStub because of Z placing of view in FrameLayout.
There several solutions for this problem
1. Include toolbar in each fragment where I need it (in all fragments inside activity) It seems not the best way to do , because of code duplication. (Don't repeat yourself rule).
2. Use some basic ToolbarFragment class and also in this case I have to add all required views by inherited fragments in runtime.
3. Use some Decorator class ToolbarActivity and as I have described above to add into already inflated view hierarchy.
4. Use layout the same as for SingleFramgentActivity but to put there toolbar include tag and rename class into SingleToolbarFragmentActivity. Seems that Single Responsibility Principle has been just broken. And what If need only toolbar without fragment container or vice versa.
So I need advice what is the best way to do this. Is not bad practice about performance ?
Please suggest what is better to use in this case not to cause performance issues and keep code as readable as possible
Answer: There is no performance problem about adding views at runtime if you are not adding them one by one, or changing its layout bounds or, what is the same, calling multiple times to requestLayout/invalidate. Anything than that should not cause any performance problem.
Given that, what I usually do in your case is create a lets call it BaseActivity with some methods that can be extended like hasToolbar():boolean and in the moment of the creation of this activity I inflate what is needed and add it to the view. That is one approach, but any of those you mention can work without a performance problem since inflating a single layout is not so time consuming (like happens in ListViews for example).


Changing colors balls

Question: There are three boxes with balls in them:
$$\text{First box - 13 red balls}$$
$$\text{Second box - 15 green balls}$$
$$\text{Third box - 17 blue balls}$$
You can get one ball in a hand and you should get always exactly 2 balls (one for your left hand and one for your right hand).

If you have balls from same color in your left and right hand just return them in the box.
If you have balls with different colors in your hands paint them in the third color and return them in the third's color box.

For Example:
Pick 1: If you get one red ball in your left hand and one red ball in your right hand just return them in the red box.
You will be at the end of first picking with:
$$\text{First box - 13 red balls}$$
$$\text{Second box - 15 green balls}$$
$$\text{Third box - 17 blue balls}$$
Pick 2: If you get one red ball in your left hand and one blue ball in your right paint them in green and return them in green box.
You will be at the end of first picking with:
$$\text{First box - 12 red balls}$$
$$\text{Second box - 17 green balls}$$
$$\text{Third box - 16 blue balls}$$
You can pick balls as many times as you want.
The questions are:
<code> 1. Is it possible to have the same number balls in each box?

 2. Is it possible to have two boxes with same number of balls?

 3. Is it possible all balls to become in one color (to be in one box)?
</code>
My Answers to the three questions are NO. However, they are based just on trying to get all the balls in one box or to have two boxes with the same number of balls.
How can I approach this mathematically and is No the correct answer to the three questions?
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020) to format.
Comment: This is not quite clear. I'm not sure how much of that is a language issue – if you have the opportunity to go over this with someone with a better command of English, that might help. a) Where you say "pick two balls in each hand", it appears you mean "pick two balls, one in each hand"? b) Presumably where you write "bow" you mean "box"? c) The role of the boxes is not clear. You don't describe the initial number of balls in each box, and it seems that it can't change since the balls are always returned to their box.
Comment: From parts of what you write, I get the impression that you actually mean that the balls are sorted into boxes according to their colours, so the boxes would just be a different way of talking about the colours. Is that correct? Otherwise, please clarify the role of the boxes.
Comment: Thank you both. I have modified the question. Hopefully now it is clearer.

The boxes are just added by me to have some kind of a container for the balls. The main idea is that we have three groups of balls with three different colors
Comment: [Related question](https://math.stackexchange.com/questions/3081761/drawing-balls-of-an-urn-probability-of-one-colour-run-out-with-replacement)
Comment: This would be a lot easier to understand if there were only one box. Even the questions would become simpler: "*the same number of each color*", "*the same number for two colors*", and "*all balls the same color*".
Answer: Consider the three numbers mod $3$.
Originally, they are $13,15,17$, so the numbers mod $3$ are $0,1,2$, in some order.
Every step of changing colors can be described as follows: first reduce each number by $1$, then add $3$ to one of the numbers.
From this description, it should be clear that after any number of steps, the three numbers mod $3$ will remain $0,1,2$, in some order.
This means that no two numbers will ever be equal, which gives answer "no" to your second question; it consequently implies answers "no" to the first and third question (as they are special cases of the second question).
Comment: Thank you. This explains how I can proof the obvious from the excel table that I made.

Changing colors balls


php remove character > when importing csv file

Question: Please i need help, i am importing data from csv with php and i need to remove following character ">" from instock row in csv while importing. (Quantity array in php)
CSV ROW instock - check here
// MAIN CYCLE
$row_num = 0;
if (($handle = fopen($remote_csv_file, "r")) !== false) {
  while (($data = fgetcsv($handle, 100000, ";")) !== false) {
    $row_num++;
    if ($row_num == 1) {
      // SKIP FIRST LINE (HEADER)
      continue;
    }
    //quantity = EAN --> STOCK
    if ($data[2] == '' || !is_numeric($data[3])) {
      // SKIP EMPTY VALUES
      continue;
    }
    //price = EAN --> PRICE
    if ($data[2] == '' || !is_numeric($data[1])) {
      // SKIP EMPTY VALUES
      continue;
    }
    //price bezna = EAN --> PRICE W
    if ($data[2] == '' || !is_numeric($data[0])) {
      // SKIP EMPTY VALUES
      continue;
    }

// INPUT SANITIZATION
$ean13         = trim($data[2]);
$quantity      = ($data[3] >= 0) ? $data[3] : 0;  //  need to remove ">" character from CSV row "instock" when importing data
$price         = ($data[1] >= 0) ? $data[1] : 0;  //
$price_wholesale   = ($data[0] >= 0) ? $data[0] : 0;  //

Thanks for any help
Comment: What research have you done on "how to remove a character from a string"? Also note that you need to remove it _before you make a numeric comparison_.
Answer: A simple trim() should do that for you using a space and the greater than sign as the characters to remove
trim($data[3], ' >');

Example
$data = ['a','b', 'c', ' > 12 '];

echo trim($data[3], ' >');

RESULT
12


Robocopy Blow Away and Recreate?

Question: I have a question about ROBOCOPY which I have not been able to iron out in my research.
When copying directories recursively with the /E flag and where the directory already exists at the target, does ROBOCOPY:

delete the existing directory and re-create it? or
ascertain that the directory already exists, and continue with its work using the existing directory.

I think the answer is 2, but would like to be sure, if possible.
Answer: Robocopy will reuse the directory found on the destination. If copying security information as well, it will then apply the correct ACL settings to the directory. The same for owner information.

Robocopy Blow Away and Recreate?


Probability of width of a confidence interval being less than a value

Question: Let independent random variables $X1, X2,…, Xn$ be identically normally distributed with unknown mean $μ$ and unknown variance $σ^2$:
(a) Determine the 95% confidence interval for μ, $n=51$,  $\bar{x}=10$,  $S^2 = 0.8$ where:
$\bar{x} = \frac{1}{n}\sum_{i=n}^n x_i$ and $S^2 = \frac{1}{n-1}\sum_{i=1}^n(x_i-\bar{x})^2$
(b) Suppose $\sigma^2=0.5$. Find the probability that the width of the 95% confidence interval for $\mu$ is $\leq$ 0.3.

My idea so far:
Boundaries: $[10-0.15, 10+0.15] = [9.85,10.15]$
$P(9.85 \leq X \leq 10.15 |\mu=10,\sigma^2=0.5) \approx 0.168$
However, I find this probability intuitively low since the width of the 95% CI according to my workings is:
$10 \pm 1.96\sqrt{0.5/51} = 10 \pm0.194$
which gives a width of:
$2*0.194=0.388$
Thus, intuitively I thought that that the probability would be way higher.
Am I having a faulty approach or is it just my intuition that is wrong?
Comment: I don't quite understand. You have an estimate of the standard deviation ($S^2=0.8$), from which you can directly compute your CI (for what probability? 0.95? Or is this number what you are actually looking for?). So the CI is either wider than 0.3 or narrower. There is no probability involved on the CI width any more.
Comment: @S.Kolassa-ReinstateMonica You're totally right, I've probably misinterpreted the question, I've updated it with the actual question aswell. Thanks in advance.
Answer: a)  Confidence intervals look like
$$ \hat{\mu} \pm z_{1-\alpha/2}\dfrac{S}{\sqrt{n}}$$
So your interval should me $ 10 + 1.96 \sqrt{\dfrac{0.8}{51}}$
b) Note that the width of the interval is a function of the size of the sample standard deviation.  The length is
$$ 2 z_{1-\alpha/2}\dfrac{S}{\sqrt{n}}$$
All but the $S$ are fixed quantities.  Note that $(n-1)S^2/\sigma^2 \sim \chi^2_{n-1}$.  Can you finish from here?
Comment: Thanks a lot, please check my updated answer.
Comment: You can verify you answer by using simulation.
Answer: Alright so after the feedback I've tried this for (b):
width $= 2*z_{0.025}*\frac{S}{\sqrt{n}} < 0.3 \implies S < \frac{0.3 \sqrt{n}}{2*1.96} = 0.547$
And thus we want the probability:
$P(S_x< 0.547 |\sigma^2=0.5) \Leftrightarrow$
$P(S_x^2< 0.3 |\sigma^2=0.5) \Leftrightarrow$
$P(\frac{50*S_x^2}{0.5}< \frac{50*0.3}{0.5}) \Leftrightarrow$
$P(\chi_{50}^2 < 30) \approx 0.0112 $
Is this a correct approach?
Thanks in advance!


Como instanciar um objeto dessa classe no C#

Question: Estou lendo a apostila da Caelum sobre C# e orientação a objeto, aí coloquei em Conta.cs o seguinte código:
namespace Banco
{
    class Conta
    {
        public int numero;
        public string nome;
        public double saldo;

        public bool Sacar(double valor)
        {
            if (this.saldo >= valor)
            {
                this.saldo -= valor;
                return true;
            }
            return false;
        }
    }
}

Tem a classe Conta com o método Sacar.
Diz que para instanciar um objeto tem que fazer o seguinte:
private void button1_Click(object sender, EventArgs e)
{
    Conta r = new Conta();
    r.numero = 1;
    r.nome = "Flano";
    r.saldo = 300;

    if (r.Sacar(250.0)) {
        MessageBox.Show("Operação realizada com sucesso!");
    } else {
        MessageBox.Show("Saldo insuficiente!");
    }
}

Eu entendo como funciona tudo, só não sei onde colocar esse "button".
Comment: Seu objeto do tipo `Conta` já está instanciado, poderia ser mais claro na sua dúvida ? porque pelo que entendi, você tem esse código de botão e não sabe onde colocar correto ?
Comment: Não se preocupe com a classe `Conta` para isto. Ela é apenas seu modelo, ela não tem relação com a apresentação que você está tentando fazer. Claro, que você usa ela na apresentação mas ela em si não faz parte da apresentação. Você copiou isto no projeto ou mandou o VS gerar o código do Form para você e só adicionou este trecho? A apostila mostra todo o código ou só deu esse trecho? Está me parecendo que falta você criar todo o Form (o VS gera o código para você) e depois encaixar esta parte.
Comment: Eu sei que a classe é a referência para eu instanciar os objetos. Deve ser isso mesmo, deve está faltando criar o formulário. Mas lá estava assim, não mostrava como criar o form.
Comment: Isso @EnzoTiezzi eu instanciei, mas não sei onde colocar.
Comment: primeiro você precisa identificar se seu projeto, é um `Windows Form`, caso seja você precisará colocar um botão na sua tela, clicar sobre esse botão 2 vezes e incluir esse código que está no método `button1_Click` no código que ele gerar automaticamente, que será semelhante a esse que você tem.
Comment: O Button será colocado na Interface Gráfica. https://lh3.googleusercontent.com/-MRRwz5qyaE8/Tn0EKfJ8E9I/AAAAAAAABAY/16jDCAKW4cs/DynamicButtonsInWinforms.gif
Comment: O visual Studio tem um atalho de teclado para indentar o código automaticamente: `CTRL + k + d` ;)
Comment: Obrigado pessoal, identifiquei aqui tudo. Valeu mesmo.
Answer: 1-) Abra o Visual Studio;
2-) Crie um projeto Windows;
3-) Você deve ver agora o desenho de um formulário. Se não vê, fuce aí até encontrar;
4-) Deve haver uma aba a esquerda com diversos controles. Expanda a aba, encontre um controle Button e o arraste para o formulário. Pode deixar na posição que quiser;
5-) Dê um duplo clique nesse botão que você colocou no formulário!
6-) ???
7-) Lucro!
6-) Isso vai abrir o arquivo de código do formulário, já com um método de clique do botão pronto para você preencher. Por baixo dos panos, o Visual Studio também já associou o evento de clique do botão a esse método.
Ponha seu código que trata a conta dentro desse método gerado pelo Visual Studio. Daí é só rodar a aplicação e ver como funciona, depurar e tudo o mais.
Essa metodologia toda também funciona com um projeto web. Mas projetos web são um pouco mais complexos, por isso recomendo focar em aplicações Windows e aplicações de console até dominar os conceitos que estás a aprender por enquanto.
É importante mais a frente entender também como a associação do evento de clique é feita ao método. Então fuce bastante, ok? Uma das principais características de bons programadores é a curiosidade. Boa sorte!
Comment: O último parágrafo é o mais importante.
Comment: Consegui rapidinho. Estou consciente que é uma pergunta básica, mas é que estou vindo da web. A faculdade tá cobrando aí tomei vergonha na cara para estudar. Obrigado, deu certo!
Comment: Valeu, vou olhar tudo.


Windows RDP: Attack targeting real account names

Question: We have a Windows 2012 R2 server hosted in a datacenter, and we are using RDP for its administration. Automatic updates are enabled.
RDP login is not allowed for the Administrator account, and there are several user accounts with RDP enabled.
I recently found in the logs that there was a brute force attack ongoing that was targeting one of the accounts that actually exists on the server.
Looking deeper in the logs, I found that at least 3 accounts have been targeted recently. And this cannot be a coïncidence since the account's names are complex.
I have now restricted the connection to the IPs of my company, and the problem is solved (I know that this should have been done before but we had reasons not to do it).
However, I am still wondering how the attacker(s) managed to get the names of the accounts. Is it a known security flaw of RDP?
EDIT: There are a few elements that I did not mention: This server is a virtual machine, and both this VM and the hypervisor (Windows 2012 R2 also) are behind a router and share the same public IP. RDP is NATed with a public port that is not the default one, and this is the only NATed port. This machine hosts an HTTP server (kestrel) that can only be accessed through a reverse proxy (nginx) installed on another machine.
Comment: @HumanJHawkins This is the point. If there was a flaw in the RDP protocol allowing someone to get the account names, I could assume that it was a random attack. Otherwise, the problem is not the same... There are only 4 people who have an account on this system, for maintenance and administration. They are aware of the security rules, so I can expect that they did not wrote down their identifiers on a blog page as a reminder.
Comment: I suggest limit Access IP for RDP , Best way is using vpn to connect user to your local network and then access RDP to them , whitout limitation security don't have any meaning
Comment: Given that RDP was open, perhaps file sharing was open too?  If [this setting](https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-access-do-not-allow-anonymous-enumeration-of-sam-accounts-and-shares) isn't turned on, account enumeration may be possible - I'm not sure of the details.
Comment: @Harry Johnston: RDP was the only Windows service opened, actually the machine is behind a router and RDP is NATed.
Comment: RDP [does allow you to see the login screen](https://digi.ninja/blog/rdp_show_login_page.php) if NLA isn't enabled, and depending on how Windows is configured this may expose usernames.  Might this have been the problem?
Comment: @HarryJohnston: This is interesting, because I'm using NLA but with the option you suggested I can bypass NLA and reach the login screen. Some default setting that I should check I believe... Anyway, the login screen does not seem to expose any user name: There are only two inputs, one for the user name and one for the password. The user name is pre-filled with the account I'm using on my own computer.
Comment: What do you see if you open the virtual console?
Comment: If I open the virtual console on the hypervisor, I can see the login screen with a list of all the accounts that are available on this server. Do you mean that this list could also be available through RDP if it is visible on the console?
Comment: Possibly?  I thought that was only true if NLA wasn't enforced, but I'm not entirely certain.  There's a site our security team pointed me at recently that might have information about this stuff, I'll see if I can have a look tomorrow and get back to you.
Comment: OK, the site is https://www.shodan.io/ (free account needed) and if you put an IP address into the search box then if RDP was available at that address (when the address was last scanned, I guess) it shows a screenshot.  Unfortunately I can't find any information on that site about what exactly it is doing to *get* these screenshots but perhaps that will be helpful anyway.
Comment: The server does not seem to be referenced. However I have tried with another server that has RDP opened and it was referenced but the screen capture was black. Anyway, I will keep that address in my bookmarks as there are some valuable informations here. And thank you very much Harry for the time you have spent helping me.
Comment: How certain are you that the usernames were not intentionally or unintentionally exposed. What avenues for such exposure might there be? Are they so cryptic that a person would be motivated to store them (regardless of policy) somewhere for reference that then might have been compromised? Were they stored or communicated in a form that might have been backed up to a less secure location? Does anyone who knows them have a potential grudge against your employer or someone else there?
Answer: Overview
We cannot know for sure how they got the account names without knowing more details.
From my personal experience, I will give you the most common ways bad guys get this info.

Assume Breach
There is a saying in the advanced cyber security field;

There are two types of organizations: those that are breached, and
those that don't know that they are breached.

Since you are running an Active Directory Domain Services environment, it is easy for an attacker to dump a list of all account and use an application like BloodHound to chart a course to domain admin.

Easy Access
The bad guy can compromise a single domain joined workstation (may be through phishing or something else) then dump a list of all users and computers from the AD DS instance. You can't easily defend against something like this as this behavior is core to how AD DS works. You can easily dump everything as a standard user, no special or priv permissions are needed to do this.

Identity Perimeter
Security Through Obscurity is no longer an option, back in the early 2000s and 90s, it may have been but with automation and tools like BloodHound, you get the picture.
Security needs to be at the network and identity layer. A network only security perimeter is just a foolish as a Security Through Obscurity. Wired Magazine ran an article on this back in 2013.
An example of a security control that can help breaches at an identity level is multi-factor authentication. There are many more but that is an answer for a different question.

RDP/SMB Account Dumping
To the best of my knowledge, I am not aware of any attacks via RDP or SMB that would dump usernames from a computer as a direct result of the attack. I am aware of attacks that can gain access to the computer as an admin then with those rights they could dump, but not a direct attack that could dump.

Links

Securing Privileged Access
Privileged Access Workstations
ESAE/Red/Priv Forest
Microsoft Identity Manager
mimikatz (password/secret dumping)