How to re-add a RAID-10 failed drive on Ubuntu?

Question: I have a problem that I can't seem to solve. We have a Ubuntu server setup with RAID-10 and two of the drives dropped out of the array. When I try to re-add them using the following command:
mdadm --manage --re-add /dev/md2 /dev/sdc1

I get the following error message:
mdadm: Cannot open /dev/sdc1: Device or resource busy

When I do a "cat /proc/mdstat" I get the following:
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [r$
md2 : active raid10 sdb1[0] sdd1[3]
    1953519872 blocks 64K chunks 2 near-copies [4/2] [U__U]

md1 : active raid1 sda2[0] sdc2[1]
    468853696 blocks [2/2] [UU]

md0 : active raid1 sda1[0] sdc1[1]
    19530688 blocks [2/2] [UU]

unused devices: <none>

When I run "/sbin/mdadm --detail /dev/md2" I get the following:
/dev/md2:
    Version : 00.90
Creation Time : Mon Sep  5 23:41:13 2011
   Raid Level : raid10
   Array Size : 1953519872 (1863.02 GiB 2000.40 GB)
Used Dev Size : 976759936 (931.51 GiB 1000.20 GB)
  Raid Devices : 4
  Total Devices : 2
Preferred Minor : 2
Persistence : Superblock is persistent

Update Time : Thu Oct 25 09:25:08 2012
      State : active, degraded
Active Devices : 2
Working Devices : 2
Failed Devices : 0
Spare Devices : 0

     Layout : near=2, far=1
Chunk Size : 64K

       UUID : c6d87d27:aeefcb2e:d4453e2e:0b7266cb
     Events : 0.6688691

Number   Major   Minor   RaidDevice State
   0       8       17        0      active sync   /dev/sdb1
   1       0        0        1      removed
   2       0        0        2      removed
   3       8       49        3      active sync   /dev/sdd1

Output of df -h is:
Filesystem            Size  Used Avail Use% Mounted on
/dev/md1              441G  2.0G  416G   1% /
none                   32G  236K   32G   1% /dev
tmpfs                  32G     0   32G   0% /dev/shm
none                   32G  112K   32G   1% /var/run
none                   32G     0   32G   0% /var/lock
none                   32G     0   32G   0% /lib/init/rw
tmpfs                  64G  215M   63G   1% /mnt/vmware
none                  441G  2.0G  416G   1% /var/lib/ureadahead/debugfs
/dev/mapper/RAID10VG-RAID10LV
                  1.8T  139G  1.6T   8% /mnt/RAID10

When I do a "fdisk -l" I can see all the drives needed for the RAID-10.
The RAID-10 is part of the /dev/mapper, could that be the reason why the device is coming back as busy? Anyone have any suggestions on what I can try to get the drives back into the array?
Any help would be greatly appreciated.
Thanks!
Comment: Isn't sdc1 already part of md0?
Comment: Yeah, you are correct.
Answer: Sorry, in-fact the two drives that dropped out are not being mounted for some reason. SDC1 is already used in md0.


What causes the countries on this shirt to seem out of alphabetical order?

Question: I attended a few matches of the Copa América Centenario last year, hosted in the United States, and bought a t-shirt at an official FIFA merchandise stand at a match in Chicago. See pictured.

While it seems like all sixteen of the countries that participated in the tournament are listed in alphabetical order clockwise around the shirt, there are two teams that do not follow this pattern. I'm not going to count the United States, which appears at the top of the circle (the USA hosted the tournament and prominent spots on advertisements are often reserved for FIFA host countries).
Colombia and Chile are out of order and should be switched. I guess this could just be an oversight because both of the countries begin with C, but that would surprise me. Do either of these countries have a different name that would cause them to be in this order?
The other country that is out of order is Argentina. I'm really confused why Argentina appears in between Uruguay and Venezuela. Argentina's official name is the Argentine Republic (República Argentina in Spanish), but that shouldn't move it on the list.
Does Argentina have another English name that would place it between Uruguay and Venezuela alphabetically? Are the countries on the shirt ordered in a different language besides English? Was the quasi-alphabetical ordering simply a mistake?
The complete list of countries are, in clockwise order from the top:

United States (host)
Bolivia
Brazil
Colombia
Chile
Costa Rica
Ecuador
Haiti
Jamaica
Mexico
Panama
Paraguay
Peru
Uruguay
Argentina
Venezuela
Comment: I seem to be hearing the conversation between the designers: _—Argentina goes first alphabetically. —Yes, but the host is USA. —OK, then flip them in the logo_. Yes, I know _United States_ would go before Uruguay, not after.
Comment: @fedorqui, that's a genuine answer! And yes, United States won't but USA would go after Uruguay.
Comment: If the case was use Republica Argentina, then the order would be bad anyway, since Brasil isRepublica Federativa del Brasil, Uruguay is Republica Oriental del Uruguay, y Venezuela is Republica Bolivariana de Venezuela
Answer: As it is practically unlikely that we get the most genuine reason, the only thing left for us is to speculate. And by combining the network consensus I am posting a community wiki answer:

Columbia and Chile are out of order and should be switched but it could be an oversight because both countries begin with C. - Observation by Jacob Shetler.
Argentina should go first alphabetically, but the host is USA, so the designers probably simply decided to switch them - Observed by fedorqui and corrected by gdrt.


Intra- and inter-rater reliability on the same data

Question: I've read some of the answers here (specifically the 'Inter-rater reliability for ordinal or interval data' one). I'm still somewhat perplexed though!
I have data for 4 raters, who each rated every subject's CT scan, on two occasions, for the presence or absence of 9 signs. The two readings were separated by a washout period. As such, my data looks like this (for each sign/variable):
A1  A2  B1  B2  C1  C2  D1  D2
0   1    1   1   0   1   0   0
1   1    0   0   1   1   1   1
etc

With A1 representing the first reading by rater A, and A2 the second, and so on. Calculating the intrarater reliability is easy enough, but for inter-, I got the Fleiss Kappa and used bootstrapping to estimate the CIs, which I think is fine. Except, obviously this views each 'rating' by a given rater as being different 'raters'. I thought about using the ICC with the WinPepi function which can provide interrater agreement for fixed raters, but I suspect it might not be appropriate for binary data?
Would you just get the Fleiss and report it as such?
PS: The answer provided below by StasK is brilliant, and did clarify some things, but because of an ambiguity in the original question it isn't quite what I was looking for...
Answer: I assume that A through D are different symptoms, say, and 1 and 2 are the two raters. As you tagged this in Stata, I will build a Stata example. Let us first simulate some data: we have a bunch of subjects with two uncorrelated traits, and a battery of questions, tapping upon these traits. The two raters have different sensitivities to each of the traits: the first rater is a tad more likely than the second rater to give a positive answer on question A, but slightly less likely to give a positive answer on question B, etc.
    clear
    set seed 10101
    set obs 200

    * generate orthogonal individual traits
    generate trait1 = rnormal()
    generate trait2 = rnormal()

    * raters' interecepts for individual questions
    local q1list 0.3 0.7 -0.2 -0.4
    local q2list 0.5 0.5 0 -0.5

    * prefixes
    local letters a b c d

    forvalues k = 1/4 {
      local thisletter : word `k' of `letters'
      local rater1     : word `k' of `q1list'
      local rater2     : word `k' of `q2list'
      generate byte `thisletter'1 = ( `k'/3*trait1 + (3-`k')/5*trait2 + 0.3*rnormal() > `rater1' )
      generate byte `thisletter'2 = ( `k'/3*trait1 + (3-`k')/5*trait2 + 0.3*rnormal() > `rater2' )
    }

This should produce something like
      . list a1-d2 in 1/5, noobs

       +---------------------------------------+
      | a1   a2   b1   b2   c1   c2   d1   d2 |
      |---------------------------------------|
      |  1    1    0    0    1    0    1    1 |
      |  0    0    0    0    0    1    1    1 |
      |  0    0    0    0    0    0    0    0 |
      |  1    0    0    1    1    1    1    1 |
      |  0    0    0    1    1    1    1    1 |
      +---------------------------------------+

which I hope resembles your data, at least in terms of the existing variables.
A fully non-parametric summary of the inter-rater agreement can be constructed by converting the binary representation into a decimal representation. The outcome a1=0, b1=0, c1=0, c4=0 is 0000b=0; the outcome in the first observation is 1011b = 11, etc. Let us produce this encoding:
      generate int pattern1 = 0
      generate int pattern2 = 0
      forvalues k = 1/4 {
        local thisletter : word `k' of `letters'
        replace pattern1 = pattern1 + `thisletter'1 * 2^(4-`k')
        replace pattern2 = pattern2 + `thisletter'2 * 2^(4-`k')
        tab pattern*
      }

This should produce something like
      . list  a1- d2 pat* in 1/5, noobs

        +-------------------------------------------------------------+
        | a1   a2   b1   b2   c1   c2   d1   d2   pattern1   pattern2 |
        |-------------------------------------------------------------|
        |  1    1    0    0    1    0    1    1         11          9 |
        |  0    0    0    0    0    1    1    1          1          3 |
        |  0    0    0    0    0    0    0    0          0          0 |
        |  1    0    0    1    1    1    1    1         11          7 |
        |  0    0    0    1    1    1    1    1          3          7 |
        +-------------------------------------------------------------+

Now, these patterns are perfectly comparable using kap:
        . kap pattern1 pattern2

        Agreement   Exp.Agrmt    Kappa     Std. Err.      Z        Prob>Z
        -----------------------------------------------------------------
        54.00%        17.91%     0.4396     0.0308      14.25      0.0000

You can play with the sample size or with the differences between raters to produce a non-significant answer :). This kappa suffers from a serious drawback: it does not reflect the fact of having some common items: the patterns 0001 and 0000, even though they match by 75%, would be considered non-matches within this approach. So it is an extremely conservative measure of the inter-rater agreement.
To get fair estimates of all the ICCs, you would need to run a cross-classified mixed model. Let us first reshape the data to make it possible:
        generate long id = _n

        * reshape the raters
        reshape long a b c d , i(id) j(rater 1 2)

        * reshape the items
        forvalues k = 1/4 {
          local thisletter : word `k' of `letters'
          rename `thisletter' q`k'
        }
        reshape long q , i(id rater) j(item 1 2 3 4)

Now, we can run xtmelogit (or gllamm if you like it better) on this data:
        . xtmelogit q || _all : R.rater || _all: R.item || _all: R.id, nolog

        Note: factor variables specified; option laplace assumed

        Mixed-effects logistic regression               Number of obs      =      1600
        Group variable: _all                            Number of groups   =         1

                                                        Obs per group:
        min =      1600
        avg =    1600.0
        max =      1600

        Integration points =   1                        Wald chi2(0)       =         .
        Log likelihood = -697.55526                     Prob > chi2        =         .

        ------------------------------------------------------------------------------
        q            |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
        -------------+----------------------------------------------------------------
        _cons        |  -.7795316   .9384147    -0.83   0.406    -2.618791    1.059727
        ------------------------------------------------------------------------------

        ------------------------------------------------------------------------------
        Random-effects Parameters    |   Estimate   Std. Err.     [95% Conf. Interval]
        -----------------------------+------------------------------------------------
        _all: Identity               |
        sd(R.rater)                  |   .1407056   .1627763      .0145745    1.358408
        -----------------------------+------------------------------------------------
        _all: Identity               |
        sd(R.item)                   |   1.797133   .6461083      .8882897    3.635847
        -----------------------------+------------------------------------------------
        _all: Identity               |
        sd(R.id)                     |    3.18933   .2673165      2.706171    3.758751
        ------------------------------------------------------------------------------
        LR test vs. logistic regression:     chi2(3) =   793.71   Prob > chi2 = 0.0000

        Note: LR test is conservative and provided only for reference.
        Note: log-likelihood calculations are based on the Laplacian approximation.

This is a cross-classified model with three random effects: subjects, raters and items, assuming that they are uncorrelated (which is wrong for this data; see below). Let us now estimate the ICCs:
        . local Vrater ( exp(2*_b[lns1_1_1:_cons]) )
        . local Vitem ( exp(2*_b[lns1_2_1:_cons]) )
        . local Vid ( exp(2*_b[lns1_3_1:_cons]) )
        . nlcom `Vrater' / (`Vrater' + `Vitem' + `Vid' + _pi*_pi/3 )

        -----------------------------------------------------------------------
        q     |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
        ------+----------------------------------------------------------------
        _nl_1 |   .0011847   .0027384     0.43   0.665    -.0041824    .0065519
        -----------------------------------------------------------------------

        . nlcom `Vid' / (`Vrater' + `Vitem' + `Vid' + _pi*_pi/3 )

        ------------------------------------------------------------------------
        q     |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
        ------+----------------------------------------------------------------
        _nl_1 |   .6086839   .0903816     6.73   0.000     .4315393    .7858285
        ------------------------------------------------------------------------

        . nlcom `Vitem' / (`Vrater' + `Vitem' + `Vid' + _pi*_pi/3 )

        -----------------------------------------------------------------------
        q     |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
        ------+----------------------------------------------------------------
        _nl_1 |    .193265   .1121376     1.72   0.085    -.0265206    .4130506
        -----------------------------------------------------------------------

(Hint: I figured out the names of the parameters by matrix list e(b).)
These are ICCs corresponding to raters, subjects and items, respectively. The zero ICC of the raters actually makes sense in the context of how the data were generated: there is no systematic effect in the sense that one rater consistently rates the condition better or worse than the other rater. There is an interaction between rater and item, but the model does not reflect it. True to life would be something like
 xtmelogit q ibn.item##ibn.rater, nocons || id:

With this specification, you would have to get ICCs by an even more complicated mix of the variance components and the point estimates from the fixed effects part of the model.
If you have the patience (or a powerful computer), you can specify intp(7) or something like that to get an approximation more accurate than the Laplace approximation (a single point at the mode of the distribution of the random effects).
Comment: Wow, awesome response! Just to let you know: in Stata there's a system macro (`c(alpha)`) that returns all the lowercase letters (a-z). So, instead of defining the local macro `letters` to loop over `a b c d`, you can loop directly over the first 4 elements of `c(alpha)`. (Sorry, I've noticed only now that this question is rather old).
Comment: (+1) Impressive response.  Welcome to our site!
Comment: Thanks! I spent some time thinking over it... and then yet another idea came to mind, so I spent even more time thinking about it :)


mySQL - How to autogenerate field values

Question: I have a table that contains thousands of URLs. Each URL will have a corresponding folder, so I was considering using mySQL to create a short and usable folder name for each existing URL and for new URLs as they are added to the table.
What I would like is to specify something like a field 5 chars long of chars a-z, and have mySQL autogenerate values for that field.
Can the mySQL engine do this natively, or would I have to do this in code?
Answer: Just use an auto-generated long/bigint ID and convert it after all from/to base 36 or 64.
Comment: +1: integers take less space, 5 a-z characters isn't going to be human readable in most iterations, and AUTO_INCREMENT provides a unique value vs having to roll your own & maintain it
Answer: Depending on whether you want to be able to easily determine the URL the folder name is associated with, you might find that using a UUID will provide you with a suitable way.
<code>INSERT INTO t (`url`, `uuid`) VALUES('http://www.example.com/', UUID());
</code>
Other mechanisms along the same line include using MD5() and SHA1()
http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
http://dev.mysql.com/doc/refman/5.0/en/other-functions.html
Note that these are going to be longer than 5 chars that you mentioned, though it's possible you'll need more than that to allow sufficient space.


OpenCv is pre-installed in google Colab, but i want to add one extra module from opencv_contrib. how to achieve this?

Question: I am working on google Colab and for the pre-installed opencv the functionality works fine, but i want to use "BRISQUE" which is not fully released but can be installed with opencv-contrib. There are methods which are followed but they are not for google colab. So not working for me.I actually want "quality" module from opencv-contrib to be appended to my opencv. The link to the module is https://github.com/opencv/opencv_contrib/tree/master/modules/quality
Screenshot of sample program is attached which is giving error..

Any help would be appreciated.
Thanks in advance.
Comment: The package you need is `opencv-contrib-python` and you can install it running `!pip install opencv-contrib-python`.
Comment: when i run !pip install opencv-contrib-python, it shows Requirement already satisfied. But the result i want is to use the quality module of opencv-contrib, which still gives error. the hider file quality.hpp is unknown to google colab. @marcoromelli
Comment: You can't run C++ code in Google Colab. You have to use Python.
Comment: That isn't true @marcoromelli . As i had successfully done a few. This is one of the few links you could try on google colab "https://www.wikihow.com/Run-CUDA-C-or-C%2B%2B-on-Jupyter-(Google-Colab)"
you can run c++ code by putting %cu on top of the Cell
Comment: Ok so it doesn't make sense to install `opencv-contrib-python`. I guess you'll have to recompile OpenCV from source including the "contrib" module: https://docs.opencv.org/4.2.0/d7/d9f/tutorial_linux_install.html
Comment: @marcoromelli, I tried many methods, one of which was to
1) download opencv latest from gethub,
2) extract it and then make an empty folder name build inside it
3)then download opencv-contrib from get hub and extract it.
4)then configure and build opencv-contrib modules inside build directory,

I did all these, and build was also successful, and i can see the module i wanted in opencv/build/module
but when i try header of  that module #include. i still get the same error
Answer: <code>!pip install  opencv-python==188.8.131.52
!pip install  opencv-contrib-python==126.96.36.199
import cv2
</code>
this worked for me. Load cv2 in the same cell. IF you load seperately, it takes a default version


Finding $P(A\cap B')$

Question: Suppose $A$ and $B$ are events in the same sample space. Also $P(A \cap B)  = 0.5$ and $P(B') = 0.25$. Find value of $P(A\cap B')$.
My try: The solution gives $\frac{1}{6}$ but I think the information isn't enough. We know value of $P(B)$ and $P(B\cap A')$ for sure but there is no constrain on $P(A\cap B')$.
Comment: You are correct.  There is not enough information.  All we can conclude is that $P(A\cap B') + P(A'\cap B') = 0.25$ but how much of that $0.25$ lies in $A\cap B'$ and how much of it lies in $A'\cap B'$ is not determined.  Might there possibly be an additional constraint that you left out?  By chance, might $A$ and $B$ be independent?  It is wrong to assume they are independent without being told, but I could imagine that is exactly what the proposed solution did.
Comment: @JMoravitz Thanks for your help. If you post it as an answer I can accept that.
Answer: From $P(B')=0.25$ it follows that $P(B)=0.75$.  From that and $P(A\cap B)=0.5$ it follows that $P(A'\cap B)=0.25$.
It follows that $P(A\cap B')+P(A'\cap B')=0.25$ however from the given information alone this is not enough information to distinguish further.  We can say that $0\leq P(A\cap B')\leq 0.25$ but every value in that range is possible.  For simple examples of the extremes, consider the uniform distribution on $\{1,2,3,4\}$ and $B=\{2,3,4\}$ and compare the case where $A=\{1,2,3\}$ versus the case where $A=\{2,3\}$.  Both examples satisfy the given conditions of $P(A\cap B)=0.5$ and $P(B')=0.25$.

If we were given as an additional piece of information that $A$ and $B$ are independent (which I cannot stress enough is not a valid assumption to make under normal circumstances) then we could proceed further.
Given that $P(A\cap B) = 0.5$ and given that $A$ and $B$ are independent, it follows that $0.5 = P(A)\cdot P(B)$ (which is invalid if $A$ and $B$ were not independent).
From that and that $P(B)=0.75$ it follows that $P(A)=\frac{.5}{.75}=\dfrac{2}{3}$
From here it follows that $P(A\cap B') = \dfrac{2}{3}\times .25 = \dfrac{1}{6}$
Again... this followed from a flawed assumption that $A$ and $B$ are independent.  If this was not given in the problem statement then this is incorrect.

Finding $P(A\cap B')$


Does a system of equations consisting of a linear equation and a quadratic equation have infinitely many solutions?

Question: A system of equations consisting of a linear equation and a quadratic equation has infinitely many solutions.
Is the statement true?
Can the statement be true even sometimes?
Comment: Not in general, since, for example $x^2+y^2=-1$ has no solution.
Comment: The new title is greatly improved over the original. Try to keep titles informative.
Answer: No, not at all. Consider a line and a circle. The intersection can atmost be 2 points. Or a line and a parabola for that matter.
Answer: If you work in the projective plane $\mathbf P^2(\mathbf C)$, the intersection of the corresponding algebraic varieties is in general a finite set, and consists of $2$ points, unless  the line is a component of the conic.
In greater dimensions, say in $\mathbf P^r(\mathbf C)$, you get an algebraic variety of dimension $\ge r-2$, hence it has an infinite number of points.


Saving $100 at the start of each month

Question:

I plan to save $100 at the start of each month for the next two years. How much will I have at the end of the two-year period (to the nearest cent) if interest rates remain at 8% per annum (compounded monthly)?

I am having trouble answering this question confidently. A walkthrough would be amazing.
Answer: First, $8\%$ per year is $\frac 23\%$ per month.  The first $\$100$ you save is on deposit for $24$ months.  Each month it is multiplied by $1+\frac 23\%=\frac {302}{300}$.  So at the end it is worth $100 \left( \frac {302}{300} \right) ^{24}$.  Each successive deposit is there for one less month.  This gives you a geometric progression to sum:  $$100\left(( \frac {302}{300})+( \frac {302}{300})^2+( \frac {302}{300})^3 \dots ( \frac {302}{300})^{24}\right)$$
Comment: How do you work out 2/3 % per month is equivalent to 8 % pa?
Comment: @user619818:  dividing by $12$ as there are $12$ months in a year.
Comment: @RossMillikan In that case, shouldn't $\left(\frac{302}{300}\right)^{12} = 1.08$?
Comment: @RodrigodeAzevedo:  No, when we have a stated rate like $8\%$ per year it ignores compounding.  Compounding monthly raises the actual rate to about $8.3\%$
Answer: This is an annuity. You pay at the start of each month, so it is an 'annuity due'. You want the future value (how much will it be worth at the end?). You may have formulas from lectures that give you the answer. If not, note that Ross's answer is a geometric series $$ R a \left( 1 + a + a^2 + \cdots + a^{23} \right) $$ What is the sum of a geometric series?

Saving $100 at the start of each month


loadKeyMaterial method deprecated, tell me the alternative

Question: configureBody(request, requestData.getBody())
            configureHeaders(request, requestData.getHeadersAsMap())
            String keyPassphrase = "password";

            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream("Resources/certificates/selfsigned.jks"), keyPassphrase.toCharArray());

            SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, "password").build(); //(keyStore, "password").build()

            HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();

            HttpResponse response = httpClient.execute(request, httpClientContext)

coming error:- groovy.lang.MissingMethodException: No signature of method: org.apache.http.ssl.SSLContextBuilder.loadKeyMaterial()

i am using httpclient4.5.5 jar. loadkeyMaterial method was deprecated in httpclient4.4. kindly suggest some alternative.
Answer: You should use loadKeyMaterial from org.apache.http.ssl.SSLContextBuilder instead fo from org.apache.http.conn.ssl.SSLContextBuilder which is deprecated.
So, basically change your imports:
// The one deprecated to be removed from your code
//import org.apache.http.conn.ssl.SSLContextBuilder;
// The good one
import org.apache.http.ssl.SSLContextBuilder;

Comment: import java.security.KeyStore
import javax.net.ssl.SSLContext
import org.apache.http.client.HttpClient
import org.apache.http.ssl.SSLContexts
import org.apache.http.ssl.SSLContextBuilder
class HttpclientRequest {
void loadcer(){
String keyPassphrase = "password";
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("Resources/certificates/selfsigned.jks"), keyPassphrase.toCharArray());
SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, "password").build();
Comment: HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
}
}


Xcode: EXC_BREAKPOINT (EXC_ARM_BREAKPOINT, subcode=0xe7ffdefe)

Question: I'm getting an EXC_BREAKPOINT (EXC_ARM_BREAKPOINT, subcode=0xe7ffdefe) error while running my app on a iOS7 device.
The thing is, it runs smoothly on iOS7 simulator.
By using breakpoints, I've found the error occurs in line 6.
required init(coder aDecoder: NSCoder) {
    personPicker = ABPeoplePickerNavigationController()
    super.init(coder: aDecoder)
    personPicker.peoplePickerDelegate = self
}
 /*error line*/ @IBAction func BPressed(sender: AnyObject) {
 self.presentViewController(personPicker, animated: true, completion: nil)
}

This error is new, and didn't appeared on my device until I've added these lines into the code;
        let url = NSURL(string: urlPath)
        let request = NSURLRequest(URL: url!)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
            println(NSString(data: data, encoding: NSUTF8StringEncoding))
        }

Also; the debugger points the error to this line:
0x16a7f0:  trap

And gives this output in the console:

fatal error: attempt to create an Unmanaged instance from a null pointer

This error causes a black screen on device even though I've changed nothing in storyboard.
Thank you for taking your time.
Edit: This error showed no result in search engines, but I think it may be related to obj-c.
Comment: Are you at any place in your code using an Int (or any other dataType) that might get a value so large that you get a bit overflow? As I said, I only had the problem on by 4S and iTouch (32-bit devices), but it was working perfectly on my iPhone 6. Well, I was using normal Ints to store the value from arc4random(). Changing this to UInt32 instead solved my problem.

http://stackoverflow.com/questions/28177192/app-crashes-on-iphone-4s-but-no-other-device-possible-issue-with-skphysicsconta
Comment: I'm getting the exact same error (including subcode), but I'm not seeing anything in the console. It's working fine on my iPhone 6, but crashing on my 4S and iPod Touch. Seems to be the case both in the simulator and on actual devices. The problematic line for me is an append call to an array of Coordinate (which is a struct of x and y Ints).
Comment: A nice perspective, indeed.
But doesn't the ios simulator emulate 32-bit?
My code uses a lot of variables actually, but the max value is 13 digits for int and 40 for string.
Comment: Isn't that the problem then? My understanding is that Int on a 32-bit device can only store values up to 2^31 or 2 147 483 648 which is 10 digits. Attempting to store 13 digits in that would cause a bit overflow (or crash apparently in Swift). What happens if you use Int64 or UInt64? And yes, I believe the simulator does emulate 32-bit which is why it crashes.
Comment: I'm going to change those variable types with the ones you suggested.

It runs smoothly in iOS7 simulator, crashes on iOS7 4S device.
Comment: Changed the ints to string, since I wasn't doing any mathematical equations with those digits.
Yet the error stands still.
(The ints were for confirmation codes.)
Comment: iPhone 4s is 32 bit. There are various iOS7 simulators, for 32 and 64 bit devices. iPhone 4s simulator should behave same as iPhone 4s.
Answer: I ran across this issue today when testing some Swift code against an old iPad 2 (I think it's an iPad 2 -- it's model MD368LL/A), running iOS 8.1.3.  It turned out that the problem existed everywhere that I was calling something like:
Int(arc4random() % <someInt>)

This worked fine on later iPads, iPhone5S, iPhone6, etc.  Fixed by changing code to:
Int(UInt32(arc4random()) % UInt32(<someInt>))

I think it was a register overflow on the older hardware.
Comment: Exact same issue for us: crash when doing String(intA + intB) on older devices. Explicitly marking as UInt32 fixes.
Answer: I ran into this problem, in iPhone 5, which is iOS 10.3.3.
let date = Date()
// Crashes in `iPhone 5`, but works in `iPhone 5s`.
let time: Int = 1000 * Int(date.timeIntervalSince1970) //< Crash due to cast `Double` to `Int`

// This crashes in `iPhone 5`, and `iPhone 5s` too.
let time: Int32 = 1000 * Int32(date.timeIntervalSince1970)

// It works fine in `iPhone 5`, and `iPhone 5s`.
let time: Int64 = 1000 * Int64(date.timeIntervalSince1970)

Answer: In my case, this ended up being from a bit overflow issue if you cast too large of a number into too small of a type. E.g. Int(someNumber) if someNumber was an Int64 type.
iPhone 5c break at the offending line of code:


Block HTTPS websites

Question: I'd like to know is it possible to have a web proxy that can block specific https websites ? We have a national web proxy that blocks Http websites for porn ,..etc but we have a problem of intercepting https websites , how can we solve it ?
Comment: What are you currently using for your filtering?
Answer: There are two basic options for this. The first is to block websites by IP address. This has the obvious issue that it's going to require resolving all of the names on your blacklist, which may change over time, and that it will block innocent sites which happen to share an IP addr. with porn sites (although, if you're only blocking the IPs for https, the second issue should be reasonably minor - most sites use one IP per SSL site, to prevent cert errors).
The other way is to get a proxy that can do SSL MitM. Obviously, this will either present your users with certificate errors on accessing any https website, or require the installation of your CA on every computer using the proxy. It will also leave you with important privacy issues.

Block HTTPS websites


How to remove the Day field from a Date?

Question: I want to remove the day field from a Date dropdown of a webform. How to do that? I tried with hook_form_alter() without success. Any suggestions?
Thanks
Comment: @sokratis please either post your solution as an answer to the question and mark it accepted, or vote to close/delete your question
Comment: can you post the code you tried, also you have to make sure to add a day before saving, you can use a custom validate function to handle this.
Comment: Finally I solved this creating two separate fields without the day.Also thanks for your answer.
Comment: You can use the same concepts mentioned in my answer to this question:

http://drupal.stackexchange.com/questions/12510/default-date-field-values-like-today-10-hours-30-minutes/12940#12940
Answer: There seems to be no coding-free way to achieve this but to create a separate Number-type field for year and month.


How to select every date before now in timestamp?

Question: my database feild type is timestamp here is my code I used it but It also gave me today date
I need every date before today
"SELECT * FROM {mytable} WHERE  date <".$now_timestamp."  "

please help me
Thank you
Comment: here is $now_timestamp variable
Comment: $now = new DateTime('now');
  $now_timestamp =$now->getTimestamp();
Answer: You could just use strtotime() to get yesterday's date instead of using a DateTime object:
$yesterday = strtotime('-1 day');

$sql = 'SELECT * FROM {mytable} WHERE date < :timestamp';

$result = db_query($sql, array(':timestamp' => $yesterday));

Answer: Timestamp is basically how many seconds have passed since 1st Jan 1970 UTC. To get the exact timestamp of Yesterday at 23:59 hour 59th second I can think of the following approach:
$yesterday = strtotime(((string) date('d-m-Y', strtotime('-1 day', time()))) . ' 23:59:59');

It's not really elegant, but if you really need exact time, then the above code should do the trick.
A breakdown of what's happening is:
$now = time();
$yesterday = strtotime('-1 day', $now);
$yesterday_date = date('d-m-Y', $yesterday);
$yesterday_date_string = (string) $yesterday_date . ' 23:59:59';
$yesterday_timestamp = strtotime($yesterday_date_string);

Comment: Feedback on downvote?


How should I read the timing on this measure of Rachmaninoff 32 10?

Question: I'm working on Rachmaninoff's piano prelude Op 32 No 10, and I'm having trouble combining the left and right hand on m. 47 (screenshot below).
Basically, I can't figure out which right hand notes line up with the left hand accompaniment. There's just too much going on here for me to calculate it correctly. The time signature is "C" so I'm already confused because as far as I can tell these notes don't even add up to 4 quarter notes. How can I parse this so I can tell how to play it?
I will note that the C appears again later in the piece, so is it implied that the time signature changed in the middle where this bit is? I can't find any such indication, though.
Comment: I think what confused you was the "double" notes on the right hand, whereas these should actually be *triples*. :) Once you see triples there, it would suddenly align in your mind perfectly.
Answer:
The time signature changes to 3/4 two measures before the one in question.
The left-hand part is in sextuplets per quarter note, and the left hand is in sextuplets per eighth note. Thus, there is a metrical 2:1 relationship between the two hands.

So it should line up as shown below — the note heads (or rests) in red are played together:
Comment: @temporary_user_name The left hand is six sixteenth-notes per quarter note. So what you see is and eighth-note (= 2 sixteenths), followed by a sixteenth, tied to another eighth (= 2 sixteenths), and then another sixteenth: thus, the quarter-note is divided into six equal parts, each represented by a sixteenth-note.
Comment: OMG I could NOT find that time signature!!! Thank you. This is a really well made graphic assistant.
Comment: I guess I was really confused by this measure because I didn't think you could have a sextuplet of 4 notes....I thought that was 6 notes, *played* as 4....I didn't really know what to call 4 notes played as 6, or how to count it. I'm still not sure I understand that part. I'm sitting here counting and still struggling to get this to come out to 3 quarter notes.
Comment: @temporary_user_name Another way to look at it is that both LH and RH are divided into twelve 32nd notes per quarter note (= six 32nd notes per eighth-note). Now the LH can be viewed as an eighth note (= four 32nds), followed by a sixteenth (= two 32nds). That's the first half beat, and the rest are the same, ignoring the ties. This is what is shown by the annotated image: the first chord in the LH goes with four 32nds in the RH, etc.
Comment: This has been really helpful, thank you!
Answer: @Aaron beat me to the punch on this one (+1) but I will share this image I created that shows how the notes line up in the original image. You can see that the alignment is very good between the staves. My hand drawn lines not as much ;)


How to correct Path Manipulation error given by fortify?

Question: I need to read the properties file kept in  user_home folder.
PropsFile = System.getProperty("user.home") + System.getProperty("file.separator")+ "x.properties";

Fortify is giving path manipulation error in this line. The number of correct values is large so blacklisting is the only way possible. So to avoid it i changed the code as below.
String propsFile = null;
StringBuffer sb = new StringBuffer();
String xProperties = "x.properties";
String userHome = System.getProperty("user.home");  // *
if(userHome.contains("..\\"))
 userHome = userHome.replace("..\\", "");
if(userHome.contains("../"))
 userHome = userHome.replace("../", "");
if(userHome.contains("./"))
 userHome = userHome.replace("./", "");

String fileSeperator = System.getProperty("file.separator");    // *
  if(fileSeperator.equals("/") || fileSeperator.equals("\\")){
    sb = sb.append(userHome).append(fileSeperator).append(xProperties);
    propsFile = sb.toString();
  }

but still fortify is giving me the same errors in (*) marked lines ( although the validation is done ).
How can i remove the error ?
Answer: Instead of trying to remove the Fortify error, I urge you to think about the security vulnerability.
The problem is that user.home could be crafted, possibly with the -D vm arg, to allow any file named x.properties potentialy anywhere on the system to be opened, or be destroyed.  For example, setting user.home to /usr/local would not be detetcted by your blacklisting.  Any file called /usr/local/x.properties could then be read or overwritten.
You need to challenge why any value of user.home can be allowed.  You need to check that the path you get from user.home starts with a certain location (say, /home).   This is caled whitelist validation and is a common and well-known fix for security vulnerabilities.  Once you do establish that the supplied path has a root in a known location then do you your blacklisting for directory transversal.
I know this is a pain but the attempt to fix this with blacklisting alone is fraught with peril and will never fix the problem.  And it is a real security issue, not just a Fortify error.


Capturing Mouse Cursor and Draw on Image Buffer c#

Question: I'm working on a screen recording application and I can capture the screen but without mouse cursor. I used DXGI, SharpDX and Media Foundation.
My question is. Is it possible to write the mouse cursor on image buffer so the the image buffer I sent to mediafoundation has already mouse cursor in it before it encode to a video? Saw lot of sample here how to include mouse cursor in screen capture but what they did is convert both image to bitmap and then combine both. I already tried that but performance is not good and cpu usage is so high and also fps is low. without cursor I can capture 60fps smooth. Thanks in Advance
Answer: it is possible implement your task, but it needs copy some code from C++ on C#. In my project Desktop Screen Capture on Windows via Windows Desktop Duplication API with Drawing of Cursor's Image you can find the suitable solution. It is based on using a special
Direct3D11 texture - it is created with MiscFlag - D3D11_RESOURCE_MISC_GDI_COMPATIBLE. It allows GDI rendering on the surface via IDXGISurface1::GetDC and using of Windows function DrawIconEx for drawing cursor's image. The drawing of cursor is executed by Windows function and is done in context of video memory.
Regards.
Comment: I'm stack at  IDXGISurface1::GetDC. I cant find the wrapper of this code in SharpDX.
Comment: Why you can not find? Check link [SharpDX-DXGI API](http://sharpdx.org/wiki/class-library-api/dxgi/#api-Interfaces) - it has `IDXGISurface1GetDC??????The interface extends the by adding support for using Windows Graphics Device Interface (GDI) to render to a Microsoft DirectX Graphics Infrastructure (DXGI) surface.`
Comment: found it thanks its now working


Solving side lengths using trigonometric functions

Question: I have to find the side length of $h$ in the figure below using trigonometric functions. The whole triangle is a right triangle (I forgot to denote that in the drawing).
I know the answer is $446$ units, but I don't know how to solve this. My previous attempts ended up getting me answers that don't make sense (a hypotenuse less than the other side lengths, for example).
Can someone give a good hint or explain the solution?
Comment: Just to be clear, I know I'm supposed to use the Pythagorean theorem. I just haven't been able to apply it successfully yet.
Comment: I see no reason to use the Pythagorean theorem here. You're not interested in the hypotenuse, really.
Answer: $\tan(29^{\circ}50')=0.57=\frac{h}{392+x}$
$\tan(49^{\circ}10')=1.157=\frac{h}{x}$
These are 2 equations in two unknowns, can you take it from here?
Answer: Please use Law of sines to find the length of the sides.
In particular, denote the line in the middle by $a$.
Then from triangle on the left you know that
$$\frac{a}{\sin 29^{\circ} 50'} = \frac{392}{\sin 19^{\circ}20'} $$
Note, the second angle of $19^{\circ}20'$, it comes from the the external angle equation, i.e. $\alpha + 29^{\circ}50' = 49^{\circ}10'$.
From triangle on the right
$$\frac{a}{\sin 90^{\circ}} = \frac{h}{\sin 49^{\circ}10'} $$
Therefore,
$$h = 392 \cdot \frac{\sin 29^{\circ} 50'}{\sin 19^{\circ}20'} \cdot \sin 49^{\circ}10' \approx 446 $$
Answer: Hint: Express $\tan(49^\circ10')$ and $\tan(29^\circ50')$ as ratios of sides. You get two equations with three unknowns. Is there a final way to relate some of the unknowns so that you get three equations?
Answer: Solve the following equation:
$$(h\cot49^{\circ}10'+392)\tan29^{\circ}50'=h$$


Kubernetes resource request relative to node resources

Question: HPA needs the pod has resource request defined in order to calculate metrics to know when to schedule new pods.
Is there a way to specify that the CPU request of a pod is the 75% of the node resources? Like if the machine has 4 cores, it should use cpu: 3, and if the machine has 8 cores, it should use cpu: 6.
I would like to be able to scale up the node fleet without having to change the kubernetes definitions.
Comment: it's impossible in k8s. Requests are for scheduling to a one of the node all over the cluster where that that type of a resource is available to place the pod. You cannot say "this pod requires 75% of a node something" just because 75% is about nothing from node to node. Somewhere 75% is X, somewhere 75% is Y. The scheduler counts values, not percents
Comment: Is not possible, the closest thing available on k8s today is setting resources requests and limits in each container within a pod. But the units are not in %. You can read [here](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) to understand.
Comment: Guys, would any of you consider to convert your comments into the answer? They are pretty much solving the OP question.
Answer: I'm placing this answer for better visibility for community. As already stated in the comments  this is not possible. Fix percentage request might be problematic since it will request every time the same amount of resources when being scheduled to a node. But nodes can be different from each other hence you might get yourself in situation where one pod will request 75% cpu  of node-1 which has 16 cpu and in another situation the pod will request the same amount of node-2 which has on 4 cpu. This makes the value very inconsistent across node pool and not very specific. For that very reason Kubernetes uses milicores to request resources.
This was well described in the comments above:

"Somewhere 75% is X, somewhere 75% is Y"   – [Konstantin Vustin]

You can read more about resources here.


Membros estáticos são coletados pelo GC quando não são mais necessários?

Question: Em uma classe que tenha uma variável estática, ela existe por toda a aplicação. O objeto vinculado é coletado em algum momento?
Exemplo:
public class Exemplo {
    private static List<int> lista = new List<int>();
}

Answer: A variável nunca será coletada, ela fica em uma área estática e como você mesmo disse, dura o tempo da aplicação. Então qualquer objeto referenciado por ela se manterá vivo o tempo todo. O objeto estático é uma das raízes de pesquisa do GC, então ele pegará uma referência e mantém o objeto vivo.
Mas obviamente que existe como a variável deixar de referenciar aquela variável. Em algum momento a aplicação pode trocar a referência para outra referência e aí se o objeto anteriormente referenciado não tiver outras referências ele será coletado.
Claro que se anular essa variável também deixa de ter essa referência.
Se ainda existir uma referência para o objeto é possível assiná-la para esse campo estático novamente. Se não tiver mais referências para ele não tem como usar o objeto novamente. A ressurreição só pode ocorrer durante a finalização dele, o que deve ser evitada. Mas isto é outro assunto.
public class Exemplo {
    private static List<int> lista = new List<int>();
    public static TrocaLista() {
        lista = new List<int>(); //o objeto anterior ficará sem referência
    }
}

Coloquei no GitHub para referência futura.
Na verdade se a variável tiver o atributo ThreadStatic a própria variável pode ser coletada depois do fim da thread.


Can you develop relative pitch just by playing music?

Question: I started playing an electric piano (Yamaha EZ-40) about a few months ago. At around the same time I also used the software GNU Solfege to test myself. I must say I failed miserably at recognizing intervals.
Then when I tested myself again yesterday, I still failed miserably, but less so than I had previously. Can one develop relative pitch just by playing music? Does the feedback of listening to the changes in frequency while covering those distances on the keyboard help you develop relative pitch? Or should I include GNU Solfege sessions in my training say at least once every week?
I read the followig question: Is there a way to develop "perfect pitch"? I am not interested in perfect pitch as music is just my hobby. Honestly I would like to have perfect pitch but I am unwilling to put in the necessary effort.
Comment: One crazy difficult exercise for ear training is: try to whistle a chromatic scale.
Comment: Play *Mario Kart: Double Dash!!* long enough and you should notice one thing about the music: the final lap music is a faster and **pitch-shifted** version of the regular racecourse music. I'd say that listening to music in this somewhat idle fashion can and likely will improve the melody recognition aspect of relative pitch, but it doesn't seem like an efficient way to improve interval recognition.
Answer: Yes, you can develop relative pitch through rote practice. But there are plenty of good courses out there that would likely save you a lot of time.
Ultimately what you are learning is how to label what you are hearing and as such each person starts with their own strengths and weaknesses. As always combining multiple approaches tends to give the best results. So finding a course that works for you and then giving special attention to your weaknesses with rote practice would get you there in no time.

As a jumping off point, this is the book that I just ran into at a music store but has worked for me.
Ear Training for the Contemporary Musician by Keith Wyatt, Carl Schroeder, and Joe Elliott
http://books.google.com/books?id=1Rkt69YkkusC


Não sei porque que meu programa não funciona!! EM C

Question: No exercício eu preciso criar uma struct e envia-la para a função que verifica se o numero eh par, se sim ele envia para outra função que devolve o numero /2.
<code>#include <stdio.h>
#include <stdlib.h>

struct dados{
int numero;
char nome[5];
};

void manipula_um_par (int *a){
    *a = *a/2;
}

int *manipula_pares (struct dados x[10], int w){
    int z;
    for(z=0;z<w;z++){
        if (x[z].numero %2==0){
            manipula_um_par(&x[z].numero);
        }
    }
    return x[10].numero;
}

int main(){
    struct dados v[10];
    int a[10];
    int x;
    for(x=0;x<10;x++){
        printf("\nDigite o nome do %d aluno: ",x+1);
        fflush(stdin);
        fgets(v[x].nome, 20, stdin);
        printf("\nDigite o %d numero: ",x+1);
        scanf("%d",&v[x].numero);
        }
    *a = manipula_pares(&v.numero,10);
    for(x=0;x<10;x++){
    printf("--- %d ",a[x]);
    }

    return 0;
}
</code>
Comment: `x[10]` não existe. `x` é um array de dez elementos: `x[0]`, `x[1]`, ...`x[9]`.
Answer: Arthur,
Corrigi o erro que tinha e fiz algumas sugestões de melhoria.
Comentei as melhorias no código para ter uma referência melhor sobre o que estou falando.
<code>    #include <stdio.h>
    #include <stdlib.h>

    // É uma boa prática de programação definir os números que são usados em vários lugares, com um define, vocÊ pode alterar a quantia sem risco de esquecer algum lugar
    #define NUM_ALUNOS 10

    struct dados{
      int numero;
      char nome[5]; // Não alterei, mas 5 é pouco para um nome, sugeriria utilizar um vetor maior
    };

    // É uma boa prática de programação definir os protótipos das funções no início do programa (aconselho pesquisar sobre)
    void manipula_um_par (int *a);
    void manipula_pares (struct dados *x, int w);

    int main()
    {
        struct dados v[NUM_ALUNOS];
        // int a[10]; Neste caso, não será necessário utilizar este vetor
        int x;

        for(x = 0; x < NUM_ALUNOS; x++)
        {
            printf("\nDigite o nome do %d aluno: ",x+1);
            // fflush(stdin);
            // fgets(v[x].nome, 20, stdin);
            scanf("%s", v[x].nome); // Acredito que o scanf servirá bem neste caso

            printf("\nDigite o %d numero: ",x+1);
            scanf("%d",&v[x].numero);
        }

        // *a é a mesma coisa que a[0], então neste caso, você não estará mudando todo o vetor de inteiros, você só estará mudando o primeiro vetor
        // Já que você já passa o struct v, não tem necessidade de utilizar o vetor a, pois você já esta passando os dados dentro do vetor e só precisa imprimir
        // Se você quisesse utilizar o "a", você teria que passado como parâmetro manipula_pares(&v.numero, 10, a) e trocaria o protótipo da função para void manipula_pares (struct dados *x, int w, int *a); e modificaria dentro da função o vetor a
        // Foi trocado o retorno da sua função, pois não precisaremos mais do retorno, já que alteramos tudo dentro da própria função
        // Como o *a é a mesma coisa que o a[0], então isso é um inteiro e sua função estava retornando um porteiro de inteiro e colocando um inteiro
        // *a = manipula_pares(&v.numero,10);
        manipula_pares(v, NUM_ALUNOS);

        for(x=0;x<NUM_ALUNOS;x++)
        {
          // Como foi falado, troquei para ao invés de imprimir o vetor a, imprimir direto a struct
          printf("--- %d ", v[x].numero);
        }

        return 0;
    }

    void manipula_um_par (int *a)
    {
        *a = *a/2;
    }

    void manipula_pares(struct dados *x, int w)
    {
        int z;
        for(z=0;z<w;z++)
        {
            if (x[z].numero % 2 == 0){
                manipula_um_par(&x[z].numero);
            }
        }
    }
</code>
Um último comentário, é uma boa prática colocar nomes mais representativos em suas variáveis/funções, assim fica mais fácil de outras pessoas ler e entender o fluxo do seu código e para o que serve cada pedaço de código.


Entity Framework and a Dynamics NAV database

Question: I'm currently working on an Intranet application project, using ASP.NET MVC 3.
One of the primary requirements is that all data created with the application must be available in the clients' ERP software as well; they work with MS Dynamics NAV. Accessing the data is not really a problem, as NAV uses SQL-Server as its database.
In fact I already have a working prototype, that uses Entity Framework for data access. The main issue here is that my company also develops quite a lot of custom functionality within the ERP, and thus some of the database tables I have to read from and write to often change. This would not really be a problem in a usual situation, but here, each and every field in the database is marked as not null, a very annoying feature of Dynamics NAV. That means that every field added to a table breaks my code, as Entity Framework tries to insert null when it doesn't know of a field.
Can any of you think of a solution that would not require regenerating the model after each change in the tables ?
Edit : Unfortunately our client still uses version 4.0 of Nav, so webservices are not an option.. I have already developed another application for them (part of a Warehouse management system which runs on mobile terminals), accessing SQL Server directly, but it was not quite the same scale.
Answer: If your requirement is to integrate with ERP like Dynamics NAV you should pass all data access through its application server. I think Dynamics NAV expose web services for communication with application server. Accessing its tables directly is way to disaster especially due to transactions and possible deadlocks. EF will make this even worse because you will not be able to tweak queries.
Application integration through database requires full control over SQL generated by all accessing applications.
The answer to your main question is no. The point of database first development is to regenerate your model after each database modification - especially if each database modification is breaking change (another reason why integration through database is not a good choice for you).
Comment: Thanks a lot for your answer. I've updated the question providing some more details. I guess we'll have to use raw SQL then. I would have used web services if the client had a more recent version of Nav.
Comment: I developed some application with older version of Navision as well but still we accessed it through application server. It used MSMQ for communication and custom handlers of application specific messages.
Comment: Ok, I'll have to look into that. It may well be the solution for me. Thanks again !


How to get one ( representative) number from 2 sensors with many measurements

Question: I have 2 temperature sensors in a field gathering data 24h every day (every half an hour frequency). For instance I want to pick a day. On Friday I have 48 measurements from T1 sensor and 48 measurements from T2 sensor. If I calculate the average of T1 values in the morning hours and get avg_T1. Then I calculate average of T2 sensor in the morning hours and get avg_T2. So, until now I have 2 numbers. Then, I get the average of avg_T1 and avg_T2 and have the avg_T. Can avg_T be a representative number of the field of day Friday for an average temperature that characterizes the field those specific morning hours? Can it stand from a scientific point of view?
Answer: If you have equal confidence in the reliability of the two sensors and equal confidence in their accuracy at different times then your best average for all the observations is their average, which you can calculate as the average of the two separate averages.
Whether this can "stand from a scientific point of view" depends on what you want to use that average for. The answer might depend on how much variation there is in the measurements. I can imagine that averaging the midnight and noon temperatures might not make sense. So this question does not have a mathematical answer.


Excepção no Thread "Main" java.land.NullPointerException em com.Login.Login.mai(Login.java:18)

Question: Hoje eu tentei fazer um sistema de login (de novo), só que desta vez usei um array unidimensional para guardar meus valores. Quando executei o meu programa, o Eclipse acusou um erro (ponteiro nulo para ser mais específico), minha teoria é que atribuir um valor ao array causou o erro.
Segue abaixo meu código:
package com.Login;
import java.util.Scanner;
import java.util.Random;

public class Login {
    Random r = new Random();

    String[] valores;
    boolean isSessionValid;
    int sessID = r.nextInt();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Login log = new Login();

        System.out.println("Digite o nome do usuário:");
        log.valores[1] = in.nextLine();
        System.out.println("Digite sua senha:");
        log.valores[2] = in.nextLine();

        System.out.println("Digite novamente a senha:");
        log.valores[3] = in.nextLine();
        if(log.valores[3].equals(log.valores[1])){
            System.out.println("Você está logado!");
            log.isSessionValid = true;
            System.out.println("Sua Sessão é:"+log.sessID);
        }
    }

}

Simplesmente o código atribui o nome de usuário a log.valores[1] e a senha a log.valores[2] e log.valores[3] serve somente para confirmar a senha.
Comment: Só uma pequena observação, vetores começam do indice 0, é bom se acostumar e se adaptar a isso.
Answer: Esse erro indica que está tentando acessar um objeto que não foi inicializado. Resolverá inicializando o vetor. Aparentemente 4 posições são suficientes. Talvez até 3 se começar pelo índice 0:
String[] valores = new String[4];

Coloquei no GitHub para referência futura.
O código tem outras coisas ruins, mas vou me ater ao perguntado.
Veja mais em O que é a NullPointerException e quais são suas principais causas?.
Comment: Vou fazer uma canônica sobre isto, todo dia tem uma pergunta sobre isto e é muito básico. Assim é melhor fechar como duplicata. Este é praticamente um erro de digitação (ainda que tecnicamente não seja).
Comment: Estava com o dedo no publicar quando a notificação da sua resposta apareceu kkkk
Comment: Obrigado a todos :D


How to do a logistic regression with the results of different factor analysis methods

Question: I have a large amount of variables (24) to predict a Y/N value, and I would like help for writting a procedure that automatically tries the different results of the factor selection to see how good the regression turns out to be, and of course I want to save the best model for later use.
Comment: You may find helpful those related posts http://stats.stackexchange.com/questions/6856/aggregating-results-from-linear-model-runs-r http://stats.stackexchange.com/questions/1812/fa-choosing-rotation-matrix-based-on-simple-structure-criteria
Comment: Mallows Cp http://en.wikipedia.org/wiki/Mallows'_Cp  Here's a paper on Cp http://mlrv.ua.edu/2008/vol34_1/Lieberman-Morris.pdf
Answer: First of all, consider if the factor analysis is the right way to do feature extraction. I would suggest to use principal component analysis to make dimension reduction first and then use extracted features as predictor variables. Depends on your settings you should also use appropriate cross-validation regime to access your prediction.
Comment: I would entirely agree with Andrej. This is one of those rare cases where principal components will probably do a better job than factor analysis.
Comment: Sorry I have one doubt, should I include in PCA the variable I want to predict?
Comment: No, leave your dependent variable (Y/N variable in your case) out of PCA dimension reduction. You can read my article about same topic at the http://goo.gl/lJh5s
Answer: You could find useful the 'logisticPCA' package.
Is an R package for dimensionality reduction of binary data.
https://cran.r-project.org/web/packages/logisticPCA/vignettes/logisticPCA.html


Boundary between Lexer and Parser

Question: I'm working on a pet project and I have to implement a lexer/parser. I'm reading about the subject and prototyping a simple math parser to understand as I go along.
There is something I still don't understand quite right, and it's the boundary between the lexer and the parser. Consider the following syntactically wrong expression:
+1.234.2 + pi

I'm currently lexing this into the following:
UnaryPlusOperatorToken: Lexeme "+" Pos: 1
NumberToken: Lexeme "1.234.2" Pos: 2
TriviaToken: Lexeme " " Pos: 9
BinaryAddToken: Lexeme "+" Pos: 10
TriviaToken: Lexeme " " Pos: 11
ConstantToken. Lexeme "pi" Pos: 12

Ok, so a couple of things here:

Should the lexer really care about the erroneous extra decimal period in the NumberToken and add an error to the "error bag" I'm threading through the whole parsing context or should it be the parser that catches this later on?
Should the lexer distinguish '+' being a unary operator in one context or a binary operator in another? Or should it simply generate a PlusToken and then let the parser figure out what it is?

I'm finding it rather hard to understand where the limit between both is.
Comment: IMHO 1. NumberToken should be "1.234" followed by an "InvalidToken: `.`" 2. Interpretation is a job for the parser.
Answer: Here's my take on it:

Should the lexer really care about the erroneous extra decimal period in the NumberToken and add an error to the "error bag" I'm threading through the whole parsing context or should it be the parser that catches this later on?

Let's see what your options are and compare the pros and cons:

If you stop scanning at the second decimal, your parser will get the following two tokens: 1.234 .2 and will have to issue an error like "unexpected token".
If the lexer scans 1.234.2 as a single token, you'll be easily able to issue an error like "invalid number".

The second choice will issue a much better error message, and is as easy to implement as the first choice, so I'd say it's the better solution. You have an invalid token here, treat it as such.

Should the lexer distinguish '+' being a unary operator in one context or a binary operator in another? Or should it simply generate a PlusToken and then let the parser figure out what it is?

Nope. The lexer should just output a + token. It's the parser's role to further interpret that token's meaning in the context of a parser rule.

The limit between the lexer and parser can be quite fuzzy at times. While some concerns could easily go on either side without any problems, others will bite you later if you make the wrong call, so it's worth being extra careful while making design choices.
Comment: Thanks! Should I understand then that the lexer shouldn't be adding errors to the parsing context at all and let the parser do that job later on?
Comment: The lexer can certainly issue errors, but these errors will mostly be of the "malformed token" kind. Errors like "this token doesn't belong here" are best left for the parser to deal with. But again, it depends. For instance, suppose you want to forbid expressions like `4--2` (instead of allowing them to be parsed like `4-(-2)`), it may be easier to deal with the token sequence `-` `-` from the lexer directly, but that depends on your implementation.

Boundary between Lexer and Parser


When should I pass something to saveHTML() function?

Question: All I want to know what's the difference between these:
$post_content_html = $dom->saveHTML($dom->documentElement);

And
$post_content_html = $dom->saveHTML();

My tests say there isn't any different. But when exactly should I pass $dom->documentElement to saveHTML() function?

My full code which removes all attributes except specific ones:
// to make tags stable, wrap them into  tag
$post_content_html = "".$post_content_html.""

$dom = new DOMDocument;
$dom->loadHTML(mb_convert_encoding($post_content_html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//@*');
foreach ($nodes as $node) {
    if($node->nodeName != "src" && $node->nodeName != "href" && $node->nodeName != "alt") {
        $node->parentNode->removeAttribute($node->nodeName);
    }
}
// maybe I have to pass $dom->documentElement to the saveHTML() function
$post_content_html = $dom->saveHTML();

// string  tag which been wrapped
$post_content_html = preg_replace('/^/', '', $post_content_html);
$post_content_html = preg_replace('/<\/html>$/', '', $post_content_html);

Comment: Never, because as you noted, that does nothing. Instead, try passing a different `DOMNode` to it.
Comment: @NiettheDarkAbsol I've added my full code, still are you believe I shouldn't pass `$dom->documentElement` to it?
Comment: Passing `documentElement` literally does nothing.
Comment: @NiettheDarkAbsol I see, thank you .. also as a consult, I add `` tag surround the input because I want to keep tags in the right place. I mean, see [this](https://3v4l.org/qt1Kr), if I don't wrap it into `` tag, the position of `` tag will be changed. So what I'm doing is right?
Answer: From the manual:
The first argument is:

Optional parameter to output a subset of the document.

So you pass it an argument if you don't want to save the whole document.
There is no point is passing it the documentElement since that is the whole document.
Comment: Thank you .. upvote. Just one thing, I've added my full code, still are you believe I shouldn't pass `$dom->documentElement` to it?


Python: multi-line text file reading as single line

Question: I'm trying to read in a text file containing words separated by new lines. However, I can't seem to get PyCharm to recognise the linebreaks. I've tried everything, including changing the Line Separator settings, but it still treats the text file as a single line. Any solutions?
inFile = open("words.txt", 'r')
wordList = []
for line in inFile:
    wordList.append(line.strip().lower())
len(wordList) # returns 1

inFile = open("words.txt", 'r')
inFile.readlines() # returns 1 line containing all words

Text file: https://courses.edx.org/assets/courseware/v1/1e89542cc136bc1e496aac7130cac1ba/asset-v1:MITx+6.00.1x+2T2018+type@asset+block/ProblemSet4.zip
IDE: PyCharm 2018.2.4 on macOS
Thanks
Comment: Python interpreter runs this fine on my end.
Comment: `'AIRTIME\n', 'AIRTIMES\n'` ..This is the output of your code. Each word is on a new line. What exactly is your expected output?
Comment: Must be something wrong with my IDE/interpreter as my output comes through as a list of length 1...

wordList
['a i ad am an as at ax be by do em en ex go he hi ho if in is it me my no ... ']

Anyway I tried the alternate method posted and it works
Answer: Just make this:
with open("words.txt", "r") as file:
     words = file.read().split()

print(words)

and you will get:
['AA', 'AAH', 'AAHED', 'AAHING', ......]

If want all words in one huge string, just avoid the split() method:
with open("words.txt", "r") as file:
         words = file.read()


Advice for figuring out unusual rhythms when composing

Question: I've been taking lessons in composition for a couple of years now, and one of the only things I've had any difficulty with is converting difficult passages i've improvised and decided to include, into the piece itself. I have no problem with the pitches of the notes, articulations, dynamics etc. however the exact rhythms/note timings , i just can't quite figure out past the second bar.
I'll attach the passage i'm trying to notate as a youtube video here:

Any advice on tackling writing this down would be greatly appreciated, as I'm not even quite sure about the time signature in some places, to begin with it feels like 6/8, but actually tapping that rhythm to work out all of the note lengths and write them down gets quite difficult for me.
I believe it starts something like this (Image removed because i'm not allowed to post more than 2 links :( ) ; (N.B. This piece is in D major and i've written this half way through the manuscript on sibelius so that's why it looks like that) but even after this single bar it gets  quite frustrating to have to keep on going back to the piano to find out where a single note fits in, and I haven't really got very far with this part for a few weeks (just been writing other parts instead)
Thanks
EDIT: Spent a few hours today fiddling with the rhythms, time signatures etc. and haven't really got very far, and I'm still not sure what the time signature even is, as I've rewrote it like this:  but the second bar still doesn't sound quite right when i play it back on Sibelius... Like how I'm playing the first two right hand chords in the second bar faster than just 2 quavers, but if i shorten them in Sibelius, then the notes in the bass don't fit any more.
EDIT 2:
I've bought and successfully connected a MIDI cable to my PC from the electric piano, and I've got it to work, and as I expected, what it writes is largely gibberish, but I'm sure is in some way useful (Because, of course, the note pitches are still correct)(n.B i've changed what notes i'm playing a little but the rhythms have remained no less difficult):
Obviously the rhythms are written incorrectly so I was wondering what would be the best way to maximise my ability to make use of this?
Answer: My first suggestion would be to slow down the music to half speed, if you haven't tried that already. You can do that with a YouTube video by clicking on the settings gear icon and selecting the speed. It might make certain passages a little clearer to hear what note is being played when. For instance, I'm noticing that the first note is probably a pickup note, and the right hand arpeggio is on the downbeat of the first measure.
I'd also consider that the piece isn't being played strictly to tempo in all places. There does seem like there might be some liberties being taken with the performance. The only suggestion with that I can make is to listen for the "feel" of the phrasing, and do your best to identify where phrases start and stop. In this kind of music they're more likely going to be at the beginning/ends of measures.
Answer: I would start by ignoring the left hand, and figuring out how to notate the right hand part on its own. From about 0:20, it seems to have two beats in the bar (a quarter note, then four 16th notes). Before and after that, there seem to be a lot of irregular tuplets (5:4, etc) so figure out where the main beats are and fit the rest of the notation around them.
Software like "Transcribe" from http://www.seventhstring.com/ can be useful. You can "mark" the beats on the audio recording by tapping the tempo (which doesn't have to be regular) and then move the markers around till you get something which matches the way the music sounds. When you are happy with that, you can work on the details of how to notate each individual beat in the score, without losing track of the "big picture". "Transcribe" can also help identify the pitch of notes, if that is a problem.
Of course computer playback of your notation in strict tempo won't sound anything like the original.
Comment: I've downloaded Transcribe and played the music back very slowly, but i'm having trouble actually tapping the beat at all, because the arpeggios syncopate with the right hand quite a lot, and i'm not sure if the measure starts when there's a new chord in the right hand, or when i start a new arpeggio on the left, and not to mention it feeling like the time signature changes a couple of times. Would it perhaps be worth it to buy a MIDI cable and write directly into Sibelius with that, (even though I know it's usefulness will be rather limited) ?


Vários Select Sum com parametros de tabelas relacionadas

Question: Tentei fazer uma consulta SubSelect quando um usuario quiser pesquisar o Patrimônio por Produto, por Localização e por Situação o Total da soma seja alterada. E ele só soma o Patrimônio em que Ativo = true. Segue o comando Sql que fiz. Por favor, peço ajuda.
<code>SELECT USUARIO.[usu_codigo], Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0)) As Soma,
    (SELECT Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0)) WHERE PATRIMONIO.[pat_codproduto] = PRODUTO.[prod_codigo] And ((PRODUTO.[prod_nome]) = ?)) As SomaProduto,
    (SELECT Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0)) WHERE PATRIMONIO.[pat_codlocalizacao] = LOCALIZACAO.[loc_codigo] And ((LOCALIZACAO.[loc_nome]) = ?)) As SomaLocalizacao,
    (SELECT Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0)) WHERE PATRIMONIO.[pat_codlocalizacao] = PATRIMONIO.[pat_situacao] And ((PATRIMONIO.[pat_situacao]) = ?)) As SomaSituacao
FROM USUARIO, PATRIMONIO, PRODUTO, LOCALIZACAO
GROUP BY USUARIO.[usu_codigo], PRODUTO.[prod_nome], LOCALIZACAO.[loc_nome], PATRIMONIO.[pat_situacao]
HAVING(((USUARIO.[usu_codigo]) = ?));
</code>
Answer: Funcionou desse jeito, não sei como vai ficar em termo de performance. Alguém tem alguma sugestão para simplificar este select?
SELECT DISTINCT *
FROM (SELECT USUARIO.[usu_codigo], Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0))
FROM USUARIO LEFT JOIN PATRIMONIO ON USUARIO.[usu_codigo] = PATRIMONIO.[pat_codusuario]
GROUP BY USUARIO.[usu_codigo] HAVING(((USUARIO.[usu_codigo]) = ?))
UNION ALL
SELECT PRODUTO.[prod_nome], Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0))
FROM PRODUTO LEFT JOIN PATRIMONIO ON PRODUTO.[prod_codigo] = PATRIMONIO.[pat_codproduto]
GROUP BY PRODUTO.[prod_nome] HAVING(((PRODUTO.[prod_nome]) = ?))
UNION ALL
SELECT LOCALIZACAO.[loc_codigo], Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0))
FROM LOCALIZACAO LEFT JOIN PATRIMONIO ON LOCALIZACAO.[loc_codigo] = PATRIMONIO.[pat_codlocalizacao]
GROUP BY LOCALIZACAO.[loc_codigo] HAVING(((LOCALIZACAO.[loc_codigo]) = ?))
UNION ALL
SELECT PATRIMONIO.[pat_situacao], Sum(IIF(PATRIMONIO.[pat_ativo] = true, (PATRIMONIO.[pat_valortotal]), 0))
FROM PATRIMONIO
GROUP BY PATRIMONIO.[pat_situacao] HAVING(((PATRIMONIO.[pat_situacao]) = ?)));


Test if samples are paired

Question: I have two samples without further information. In order to apply a t-test I want to know if they are paired. Is there a test in R that allows you to check if two samples are paired?
Comment: R does not know if you measured ben's blood pressure twice or ben's and his brother jimmy's blood pressure once.
Answer: R cannot possibly check whether the samples are paired as this requires qualitative information about the sample. You need to know whether the data of those two samples are from the same individuals / whatever is examined here.
Answer: There is currently no way to know this in R. at max, you can check their correlation, and if they are highly correlated, this gives you a tiny bit of idea that they might be paired. However, this is not a conclusive test for paired sample.
Two samples can be called pairs because of several different reasons.
Examples of paired samples include:
• pre-test/post-test samples in which a factor is measured before and after an
intervention,
• cross-over trials in which individuals are randomized to two treatments and then the
same individuals are crossed-over to the alternative treatment,
• matched samples, in which individuals are matched on personal characteristics such as
age and sex,
• duplicate measurements on the same biological samples, and
• any circumstance in which each data point in one sample is uniquely matched to a data
point in the second sample.
Anything opposite of this would be independent samples. So the identification of paired samples depends on your knowledge of data.

Test if samples are paired


How to know my RAID controller card and Host Bus Adapter's BIOS and Firmware version?

Question: I use
RAID: Broadcom MegaRAID SAS 9380-8e
HBA: Broadcom SAS 9300-8e
Main Board:Intel S2600IP
to connect a JBOD server.
The O.S. is CentOS Linux 4.18.0-240.1.1.el8_3.x86_64
I was wondering that how to get my RAID card and HBA's BIOS version and FW version in linux?
Answer: You'd use LSI's storcli to query the adapter, e.g.
storcli /c0 show

Comment: Thanks for the answer!


Given a linear function, how can I find the Ker?

Question: Given the linear function
$f : (a, b, c, d, e) ∈ R^5 → (a − d, a − d, e − d, c) ∈ R^4$
How can I find the Ker?
Please help me.
Comment: Solve for $f(a,b,c,d,e)=(0,0,0,0)$
Comment: @Akababa What do you mean?
Comment: @Mark Please, if you are ok, you can accept the answer and set it as solved. Thanks! http://cdn.sstatic.net/img/faq/faq-accept-answer.png
Answer: Equal all the coordinates to zero...:
$$\begin{cases}a-d=0\\
a-d=0\\e-d=0\\c=0\end{cases}\;\;\implies a=d=e\;,\;\;c=0$$
so
$$\ker f=\left\{ (a,b,0,a,a)\;|\;a\in\Bbb R\right\}$$
Comment: @Mark I believe you...but you'll have do to an extra effort. This is **very basic** stuff and you must try harder to understand it, so I'll leave it to you to re-read your notes or text book and make a serious effort to complete the answer.
Comment: Thank you! The exercise also asks me to find one of its basis and its
 dimension. How can I do?
Comment: For dimension: how many "free variables" does the set of elements in $\;\ker f\;$ have? And now choose that number of elements that will be linearly independent.
Comment: I don't understand.
Comment: One of its basis is $(0,1,0,0,0)$ and its dimension is $2$?
Comment: The dimension is correct, but then you need **two** elements in its basis. The vector you've given **indeed** belongs to $\;\ker f\;$ . Now you need *another one* that'll be linearly independent with this first one. Nice
Comment: I thought I had to find one basis. Well, the other one is $(1,0,0,1,1)$?
Comment: @Mark You really need to go again over the basic things, so do yourself a favour and re-read your notes/text book, otherwise you'll find much harder problems later. A basis for a linear space **has to have** as many elements as the space's dimension, so in your case "a basis" has to be a set with two elements. One single vector cannot possibly be a basis!
Comment: DonAntonio is completely right, if you miss basic concept you can't learn all what follow by that, revise the concept of basis, it is a crucial point to understand linear algebra
Answer: Given $f:R^n\to R^m $ note that $\ker f$ is defined as the set of all $x\in R^n$ such that $f(x)=0$, in this case we have
$$f(a, b, c, d, e)=(a − d, a − d, e − d, c)=0\implies\begin{cases}a-d=0\\a-d=0\\e-d=0\\c=0\end{cases}\implies\begin{cases}a=d\\e=d\\c=0\end{cases}$$
thus set $d=t\in R$ and $b=s\in R$ we have
$$\ker f=\{(t,s,0,t,t)\in R^5 \quad t,s\in R\}$$
and $\ker f$ has dimension 2 since you have 2 free parameters and a basis is
$$v_1=(1,0,0,1,1) \quad v_2(0,1,0,0,0)$$
Comment: The above is wrong for two reasons: (1) because the basis is in $\;\Bbb R^5\;$ and not in $\;\Bbb R^4\;$ , so the elements you say are a basis ofr the kernel cannot possibly be. (2) You are trying to give the whole solution to the OP but, as you can see, he's struggling **and learning** trying to cope with my answer. Thus I'd say you check your answer to correct it and then just give hints or so for the OP to make an effort to understand this so basic stuff.
Comment: Sorry DonAntonio my intent was to help bur I've made a few of confusion, you are right I revise


C# Listview DrawColumnHeader behind Vertical Scroll Bar

Question: I have a listview that I am owner drawing the column headers, sub items and items. My problem is when I draw the column header it does not draw the background past the last actual column. I am left with a space with the default column header background when there are not enough items in the list view to show the vertical scroll bar.
Is there a way I can paint the background of this space or permanently show the vertical scroll bar?
Here is a picture of my issue.
The code I am trying to use actually is compiling, but when I try to call the method I get a TypeLoadException saying the method 'ShowScrollBar' has no implementation.
<code>[DllImport("user32.dll")]
static extern int ShowScrollBar(IntPtr hWnd, int wBar, bool bShow);
</code>
Comment: Permanently showing the vertical scrollbar is tricky but apparently possible, see here: http://stackoverflow.com/questions/8690643/how-to-force-vertical-scrollbar-always-be-visible-from-autoscroll-in-winforms
Comment: I tried that. When I run the application it does not recognize that method and stops compiling. Did some more research and I have it correct, but it still won't let me compile.
Comment: If it doesn't compile you don't have it right. Add the code you have to the answer and we'll see..
Comment: @TaW, I added the code to my question.
Comment: I fooled around with my code. I had the DllImport and the ShowScrollBar method in a custom class. This is when I get the TypeLoadException. If I move the method and its DllImport into the form code I do not get an exception. But the method still does not work. It complies fine but it does not keep the scroll bar there always. If I can get the method to work, I would rather have it in my custom class so other forms can call it without adding it to each forms code.
Comment: Please also add the code that calls ShowScrollBar!
Comment: @TaW, ShowScrollBar(listTodaysCalls.Handle, 1, true);
Answer: My way of solving this issue was to switch to a DataGridView. Much more customizable and I only need details view. If anyone else has this problem, make the switch. You won't regret it.


How should I configure properly my LAN to use IPv6 for communication on LAN and WAN?

Question: I would like to use IPv6 on my LAN and would like to be able to go out to the WAN as well.
My network is a classic IPv4 environment. It works well.
My ISP provides Global Unicast IPv6 address on the WAN interface of my router (pfsense 2.5.2).
I can ping google's IPv6 address from my router:
<code>PING6(56=40+8+8 bytes) <my-global-unicast-iv6-address> --> 2a00:1450:400d:806::200e
16 bytes from 2a00:1450:400d:806::200e, icmp_seq=0 hlim=118 time=17.492 ms
16 bytes from 2a00:1450:400d:806::200e, icmp_seq=1 hlim=118 time=12.482 ms
16 bytes from 2a00:1450:400d:806::200e, icmp_seq=2 hlim=118 time=12.134 ms
16 bytes from 2a00:1450:400d:806::200e, icmp_seq=3 hlim=118 time=11.707 ms
16 bytes from 2a00:1450:400d:806::200e, icmp_seq=4 hlim=118 time=21.414 ms

--- 2a00:1450:400d:806::200e ping6 statistics ---
5 packets transmitted, 5 packets received, 0.0% packet loss
round-trip min/avg/max/std-dev = 11.707/15.046/21.414/3.814 ms
</code>
Behind the router the same thing does not work. I cannot ping google's IPv6 address.
I need help to configure the LAN side properly.
May I ask your assistance please ?
EDIT:
I had a call with my ISP and confirmed that ping might not work from my LAN. Maybe the the contact was not the right person to answer all my question because he answered that he does not know why but ping should not work but everything else should. Weird.
Comment: Did you forget to enable prefix delegation? I think pfSense has it off by default.
Comment: I forgot really. It is now enabled. Thx. Problem is not solved yet though. I am still working on it.
Answer: Finally I have found the answer. Let's see what I have:

pfSense is being used as a router/firewall on my LAN.
I got Global Unicast IPv6 address from my ISP on my WAN interface. (GUIPv6 is routable on Internet.)
pfSense need to be configured properly to get Global Unicast IPv6 address from the ISP on the LAN interface.
Interfaces --> WAN --> DHCP6 Client Configuration --> DHCPv6 Prefix Delegation size="60" --> Save
Interfaces --> LAN --> General Configuration --> IPv6 Configuration Type="Track Interface"
Interfaces --> LAN --> Track IPv6 Interface --> IPv6 Interface="WAN"
Interfaces --> LAN --> Track IPv6 Interface --> IPv6 Prefix ID="0" --> Save
Services --> DHCPv6 Server & RA --> Router Advertisements --> Router mode="Managed" --> Save
Services --> DHCPv6 Server & RA --> DHCPv6 Server --> "Enable DHCPv6 server on interface LAN"
Range from="::1000"
Range to="::2000" -- > Save

Abovementioned steps set up pfSense to be able to dynamically assigns GUIPv6 addresses on LAN.
Answer: Well, you need to have routable network from your provider for that. If there is no routable network, what router should route then?
Comment: Forget NAT with IPv6. Ask your provider for a suitably sized network, and bear in mind that the smallest subnet you should *ever* deploy outside a PtP-link is a /64. My *home* ISP hands me a /48.
Comment: What do you mean "routable network" ? My ISP routes the IPv6 traffic. At least I think they do because ping works between my pfsense's interface and google's interface.
Comment: routable network is an opposite of 'directly connected'. You provider must have something like `2a00:1450:4006:80d::0/64 via 2a00:1450:4006:80e::feab dev te10/11/12` in their routing table. (where  2a00:1450:4006:80e::feab is your router IP, and 2a00:1450:4006:80d::0/64 is your routable IPv6 network). If you have IP addresses allocated to you with provider IP (gateway) been in the same network, than you can't route it.
Comment: Fine. You say I need to add a Unique Local IPv6 address to my LAN interface and need to add a record to the route table that points to the Global Unicast address? Is it working like IPv4 routing ?
Comment: I have found an article about the IPv6 NAT: https://docs.netgate.com/pfsense/en/latest/nat/npt.html Is this the right way to solve my issue ? Could anybody confirm that ?


Comparing the spread of data from differently-sized populations

Question: I have what seems like a simple but fundamental question. Some posts on CV seem to be along similar lines, but not quite address what I'm trying to understand (for instance Comparing percentages from different sample sizes).
Suppose I rolled six dice and counted the number of 6s that came up in each roll. I wouldn't be too surprised to see the total number of 6s vary a lot between zero and six, and over the course of many rolls I'd expect to get a mean of one 6 per roll. If I rolled sixty dice, I'd expect to get a mean of ten 6s per roll, however I'd be really surprised if I rolled sixty 6s, or zero sixes. Next I divide the results for each group of dice by the number of dice in the group (and the number of rolls). In each case I should find that the probability of any particular die rolling a 6 is 1/6. But I'd expect the spread (measured say by the standard deviation) to be much tighter in the group of sixty dice than the group of six dice, since the extreme tails of the distribution (all zeros or all sixes) are much less likely to occur in the group of sixty dice than in the group of six dice. Am I right so far? So if you showed the data for both groups of dice to someone who didn't know that the two groups were different sizes, it will look like the dice in the smaller set are behaving more randomly than the dice in the larger set.
Now apply this to a comparison between real-world data like traffic accidents in a small town vs a large city. Suppose you wanted to find the probability of someone in each case being injured in a car accident. Injuries per capita would give a value for the mean probability of being injured. But it seems to me that the spread of the data would be narrower in the large city than the small town, and hence make the drivers in the small town seem more erratic than they truly are.
Anyway, I'm pretty sure I've just rediscovered a fairly basic problem in statistics, but I'm not sure what the name of the problem is or what to google to find out more about it. I'm don't think this is a t-test or ANOVA question, because I'm not explicitly trying to compare two samples to see if they're drawn from the same population (in fact, in the traffic accident example I explicitly know they're not).
So is there a way to rescale or represent the spread of the data which doesn't bias the spread from large populations to look better (more tightly-constrained) than the data from small populations? In other words, a population-independent measure of the spread of data, which is robust to having the data rescaled so as to interpret the mean as a probability (i.e. a value between 0 and 1)?
Thanks in advance
Answer: In your car accident problem it might be appropriate to model the number of accidents per year
as Poisson for both a town and a city.
The mean would likely be larger for the city over a year.
For a Poisson distribution the mean and variance
are numerically the same, so the variance would
also tend to be larger for the city.
Here is an example of a city with $\lambda_c = 700$ accidents per year and a town with
$\lambda_t = 100.$
set.seed(2022)
city = rpois(10, 700)
mean(city); var(city)
[1] 703.8
[1] 1023.067
town = rpois(10, 100)
mean(town); var(town)
[1] 108.2     # less than 704
[1] 69.51111  # less than 1023

For only ten years you can't expect the sample mean to be a close estimate to the population mean
or the sample variance to be close to the
population for either city or town. But in my example, the sample
mean and variance are both larger for the city.
It is easy to do a simulation to show that the
sample variance for the town is indeed almost
always smaller than the sample variance for the city. In the simulation, the town had the smaller
variance $9997$ out of $10/,000$ comparisons.
set.seed(609)
ratio = replicate(10000, var(rpois(10, 100))/
                        var(rpois(20, 700)))
mean(ratio < 1)
[1] 0.9997

Addendum: You don't say anything about
doing a test to see if you can distinguish
the accident rates between 25 smaller
cities (maybe $\lambda_1 = 300)$ and five larger ones (maybe $\lambda_2 = 350).$
Then the Poisson counts will be nearly normal, but the variances may be larger for larger cities. So, a Welch t test will be OK (not assuming equal population variances. For example, comparing 25 cities (where $\lambda_1 =300)$ with
5 larger cities (where $\lambda_2 =350)$
will typically give a significant result, as in the example below:
t.test(rpois(25,300), rpois(5, 350), alt="less")

        Welch Two Sample t-test

data:  rpois(25, 300) and rpois(5, 350)
t = -5.1896, df = 4.8313, p-value = 0.001931
alternative hypothesis:
true difference in means is less than 0
95 percent confidence interval:
      -Inf -29.68011
sample estimates:
mean of x mean of y
   300.64    349.40

If we simulate this scenario $100\,000$
times, we find that a significant
difference (5% or less) is found most
of the time--the power of such a test
is above 99%.
set.seed(609)
pv = replicate(10000,
      t.test(rpois(25,300), rpois(5, 350),
       alt="less")$p.val)
mean(pv <= 0.05)
[1] 0.9983

Comment: Ah yes, thank you. I feel quite silly now for not thinking of how things might be different with a Poisson distribution rather than a Gaussian. More food for thought...


Post request with AngularJS failed with Response for preflight has invalid HTTP status code 404 in Slim Framework

Question: I am developing login form in angular js using slim api integration.I am using multiple api in slim on this project but the error shown only when i am trying to login using post request. In that when i am send the login request using post request to the server it throwing the error on console like.
Failed to load resource: the server responded with a status of 404 (Not Found)
XMLHttpRequest cannot load http://example.com/Youin-api/v1/business/login. Response for preflight has invalid HTTP status code 404

My backend code:
$app->post('/business/login', function() use($app) {
 $postvar = json_decode($app->request->getBody(), true);
verifyRequiredParams(array('emailid', 'pwd'));
$email = $postvar['emailid'];
$pwd = $postvar['pwd'];

// validating email address
validateEmail($email);

$db = new DbHandler();
$response = $db->loginBuser($email, $pwd);

// echo json response
echoRespnse(200, $response);
});

controller:
public function loginBuser($email, $pwd)
 {
        $response = array();
        $stmt = $this->conn->prepare("SELECT BID from business_login_tbl WHERE emailid = ? and login_pwd = ?";
        $stmt->bind_param("ss",$email,$pwd);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        if($num_rows > 0)
    {
            $response["code"] = "Success";
            $response["error"] = false;
            $response["user"] = $this->getBusinessuserByEmail($email);
        }
        else
        {
            $response["code"] = "failed";
            $response["error"] = true;
            $response["message"] = "Oops! Username of password Missmatch";
    }
    return $response;
}

my echo function:
function echoRespnse($status_code, $response) {
        $app = \Slim\Slim::getInstance();
        // Http response code
        $app->status($status_code);
        // setting response content type to json
        $app->contentType('application/json');
        echo json_encode($response);
    }

i am using cors also:
$app = new \Slim\Slim();
$response = $app->response();
$response>header('Access-Control-Allow-Origin', 'http://example.com');
$response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

I am don't know what wrong with my front and back end code.Thanks in advance..!
Comment: Possible duplicate of [AngularJS POST Fails: Response for preflight has invalid HTTP status code 404](http://stackoverflow.com/questions/33660712/angularjs-post-fails-response-for-preflight-has-invalid-http-status-code-404)
Comment: no it's not a duplicate.i am using slim framework and also the error is only showing when i am trying to login.i am using multiple urls in slim on same project.
Answer: When you make a request via $http service with Content-Type application/json and custom headers(X-...), the browser does a preflight request to check CORS headers. The preflight requests is just an HTTP OPTIONS request to the specified endpoint. If your API does not implement the OPTIONS handling you probably get the 404 error and cannot process the request.
Comment: okey, i am accept it.how can i implement this on slim freamework..?
Comment: I am enable it but still error not cleared.$app = new \Slim\Slim();
$response = $app->response();
$response>header('Access-Control-Allow-Origin', 'http://example.com');
$response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
Comment: I am not familiar with slim, but something like this should do it: `$app->options('', function () {
    // Your logic here..
});`
Answer: It seems that your API doesn't have the endpoint that you are calling, or your implementation rises an error which leads to 404 (maybe the user does not exists). Which url are you calling? Do you have something like this in your backend?
$app->post('<login-url>', function () {
    // Your logic here..
});

If you provide some more info we can investigate and try to help you.
Answer: The problem you are running into is CORS.
Cross-Origin Resource Sharing.
I recently published some docs on how to enable it.
http://www.slimframework.com/docs/cookbook/enable-cors.html
Take a look and let me know if you have any questions or run into any problems.