What is a minimum sample size for a paired t-test and what is a non-parametric equivalent if data is non-normal?

Question: I have 4 sample pairs, let's say (x1, y1),...,(x4, y4).

What is the minimum sample size for a paired t-test?
Which assumption should I check for paired t-test?
If my data is non-normal, what is an alternative non-parametric test?
Comment: You will have very small power with only 4 pairs unless the effect size is huge (for example, if $x_i$ is the weight of a butterfly and $y_i$ is the weight of the tree you found it on).
Comment: @shabby Because effect size depends on a *standard deviation* of a response, I don't see how butterflies and trees provides a good example.
Comment: great example! I will use it in my consulting now :-)
Comment: @whuber: good catch; I suppose comparing the _logs_ of weights might correct for this (assuming variation and measurement noise are geometric).
Comment: This question: [Is there a minimum sample size required for the t-test to be valid?](http://stats.stackexchange.com/questions/37993/) may also be of interest to readers of this thread.
Comment: I'm just curious, I noticed a recent paper Jovanelly and Lane (2012) attempted to do a paired T-test with a sample size of 1 for both means. I was under the impression this was a poor idea. Can someone clarify this for me?
Comment: A link to the paper, and perhaps a brief explanation of the context would be good.
Comment: @naught101  I wonder if Curious means this one: http://benthamscience.com/open/togeoj/articles/V006/65TOGEOJ.htm
Answer: With such a small sample size the normality assumption is rather important. You may consider the Wilcoxon signed rank test if you think this assumption is faulty.
If the population is normally distributed, there is no minimum sample size. If the mean difference is small relative to the population variance, then you will have very little power as well. However, it is possible to get good power even with a very small sample size.
As an example suppose your pairwise differences were normally distributed with (unknown) variance $\sigma^{2} = 1$. Below are monte carlo estimates (using 10000 sims) of the power for incrementally larger values $0, .5, 1, ..., 5$ of the mean pairwise differences
<code>      Mean Difference  Power
 [1,]             0.0 0.0512
 [2,]             0.5 0.1097
 [3,]             1.0 0.2934
 [4,]             1.5 0.5250
 [5,]             2.0 0.7467
 [6,]             2.5 0.8975
 [7,]             3.0 0.9648
 [8,]             3.5 0.9925
 [9,]             4.0 0.9976
[10,]             4.5 0.9998
[11,]             5.0 0.9999
</code>
So we can see that it is possible for the paired $t$-test to still have good power when the mean difference is pretty large in comparison to the variance of the differences (at least 2x as large in this case), even if $n=4$. Please keep in mind that this all goes directly out of the window if the differences are not normally distributed.
You can look at these powers for other values of the mean difference and variance if you like using the R code below (note: the critical value for the $t$-test when $n=4$ using the usual .05 cutoff is 3.182446. The null value to be tested is assumed to be 0).
<code>U=seq(0,5,by=.5)
V=U-U
sig=1

for(k in 1:11)
{
   Z=rep(0,10000)
   for(i in 1:10000)
   {
      diffs=rnorm(4,mean=U[k], sd=sig)
      z=(mean(diffs)-0)/(sd(diffs)/sqrt(4))
      Z[i]=z
   }
   V[k] = mean(abs(Z)>3.182446)
}
X=cbind(U,V)
colnames(X)=c("Mean Difference", "Power")
X
</code>
Comment: In R you can get the same results using the more user friendly `power.t.test`, that gives you flexibility on what you keep fixed. E.g. the example above becomes `for (k in 0:11){cat(sprintf("%f %f\n", k/2,  power.t.test(n=4, delta=k/2, sd=1, type="paired")$power))}`
Comment: I read somewhere that the Wilcoxon test requires a larger sample size `n > 20`. Can you comment on that?
Answer: There is no minimum sample size for a t-test.
But as @shabbychef noted, you will have very little power.
Comment: may have very little power. If the normality assumption holds, the t-test will still be more powerful than the signed rank test, for one. I'd imagine this is also true for various other non-parametric tests. So, it still may be best to use the t-test.
Comment: @Glen_b, I don't understand what ***"the probability that the data is actually normal will be zero"*** is supposed to mean. If it's a statement about how all assumptions are probably wrong, then you can a poke a hole in literally any procedure (including the signed rank test - that still requires a random sample right ;)). Regarding your second point, I would say it depends very heavily on the type of departure from normality. Some departures from normality may actually increase the power of the test. Perhaps you can expand on what you meant, specifically.
Comment: Technically, wouldn't the minimum sample size be two pairs, since the standard deviation/error would be undefined with only one sample?  R's `t.test` refuses to perform the test with only one sample.
Comment: @macro while the t-test does have a power advantage at the normal, the probability that the data is actually normal will be zero - and it doesn't take terribly big shifts from normality for the t-test to lose the (surprisingly small) power advantage it has at small sample sizes when its assumptions are true. It would be like saying "Why buy insurance - if I drive perfectly, it would be a waste of money"
Comment: @DavidJ.Harris  Yes, of course.
Comment: @macro for example, one needs only be working with distributions that look fairly normal but are a bit heavier tailed before the signed rank test has better power than the t. Why would fractionally better power *at* the normal be particularly useful?  The efficiency of the t relative to the signed rank test can be quite low, but the loss of efficiency of the signed rank test against in even the worst cases for it relative to the t is not bad.
Answer: What is the minimum sample size for a paired t-test?
Generally speaking for the ordinary paired t-test, two pairs is the smallest, yielding 1 d.f.
However, if you have some specific criterion you want to satisfy or some specific cirmcumstance you hope to deal with, that may lead to a different answer.  You'd need to be more specific.
Which assumption should I check for paired t-test?
Normally*, I'd try to assess all of them, but if you only have 4 pairs, it's just about hopeless to try. You have four pair-differences, from which two d.f. would go to estimating the mean and variance of the differences (the location and scale not mattering for the assumptions), in essence leaving two d.f. to assess changing variance, dependence (in whatever form occur to you to look for, if any) and normality.
If my data is non-normal, what is an alternative non-parametric test?
Paired data: Wilcoxon signed rank test; or sign test; or any number of varieties of permutation test or bootstrap test (depending on how you construct your statistic/what exactly you want to test). All of them still have assumptions, of course.
But the t-test is at least reasonably robust to at least mild non-normality of the differences (and its the differences that are supposed to be normal). If the observations are say, mildly right-skew and not very heavy-tailed, the differences may be indistinguishable from normal even at large sample sizes. That said, there's little reason to avoid the signed rank test if non-normality is the main concern, but with 4 pairs, then you're pretty much stuck with a significance level of 12.5%

* To clarify, I mean "assess" in a fairly loose sense. I don't necessarily mean "look at my data", since the assumptions are mainly used to get approximately correct type I error rate. "Assess" will include consideration of what the likely situation would be under $H_0$, what kind of impact that might have on type I error rates, and so on. If I was considering power, I might also think about power under other sets of assumptions for $H_1$.


Is there a way to simplify my code?

Question: Hello for a project I have to encrypt and decrypt a txt file. Everything is working fine and the program works exactly how I want it, I was just curious if there is a way to simplify one section of it
int first;
            int second;
            int third;
            int fourth;

            long M = 0;

            if (toDecrypt.length() == 4) {
                first = ((toDecrypt.charAt(0) - '0') * 1000);
                second = ((toDecrypt.charAt(1) - '0') * 100);
                third = ((toDecrypt.charAt(2) - '0') * 10);
                fourth = toDecrypt.charAt(3) - '0';

                M = first + second + third + fourth;
            }

            if (toDecrypt.length() == 3) {
                first = ((toDecrypt.charAt(0) - '0') * 100);
                second = ((toDecrypt.charAt(1) - '0') * 10);
                third = toDecrypt.charAt(2) - '0';

                M = first + second + third;
            }

            if (toDecrypt.length() == 2) {
                first = ((toDecrypt.charAt(0) - '0') * 10);
                second = toDecrypt.charAt(1) - '0';

                M = first + second;
            }

            long temp = M;

What this section is doing is taking in my encrypted file line by line which are in numbers and decrypting it. The line can have anywhere from 2-4 numbers per line. Like I said the code is working perfectly I was just curious if I am able to simplify this or if I am overthinking it and if it works don't bother changing it. I suppose my overall question here is in the real world do coders/programmers attempt to make their programs more simplified or is it whatever option works first is what they go with?
Comment: Use some kind of loop
Comment: `first = ((toDecrypt.charAt(0) - '0') * Math.pow (10, toDecrypt.length() -1)`
Comment: Meaningful names would be a start.  Things like `M` and `first` have no context or bearing of understanding outside of your code.
Comment: Why not just `M = Long.parseLong(toDecrypt);`?
Answer: How about something like this:
long M = 0;
int hash = 1;
for(int i = toDecrypt.length() - 1 ; i >= 0; i--)
{
    M += (toDecrypt.charAt( i ) - '0') * hash;
    hash *= 10;
}

If you're just trying to read numbers from a file though, have you considered using something like a Scanner? You could use nextInt() function to get each number from the file. It seems like your loop is just converting a String to a number, right?

Is there a way to simplify my code?


Initial value problems for $y'=\frac{x+y}{x-y}$

Question: The solutions of the differential equation $y'=\frac{x+y}{x-y}$, are given implicitly by the relation $$\ln x = \arctan\frac{y}{x}-\frac{1}{2}\ln(1+\frac{y^2}{x^2})+c,\enspace c\in\Bbb{R}.$$
I'm considering the existence and uniqueness of arbitrary initial value problem $y(x_0) = y_0$. Let's say we write the equation as $f(x,y)=0$. The function will be continuously differentiable in $\Bbb{R^2}$. Then by the implicit mapping theorem, if we have points $a\in A$, $b\in B$ such that $f(a,b)=0$ where $A,B$ are open sets. Then for each $x_0\in A$ there will be unique solution $y(x_0)\in B$, which is differentiable and therefore continuous. Am I missing some key insights here?
Comment: For an ODE $y'=F(x,y)$, if $F,F_y$ are continuous in some neighborhood of $(x_0,y_0)$, then the initial condition $y(x_0) := y_0$ yields a unique solution.
Answer: Does this help:
One additional thing remains to do. Take $y=vx$, where $v$ is constant. The ODE gives $$v=\frac{1+v}{1-v} \implies v^2=-1, so this gives no real solution.
The general solution:
Ley $y=v(x)x$, where $v(x)$ is non constant. then $y'=v+xv'$ then the ODE becomes
$$v+xv'=\frac{1+v}{1-v}\implies xv'=\frac{1+v}{1-v}-v$$
$$\implies \int\frac{(1-v)dv}{1+v^2}=\int\frac{dx}{x}$$
$$\tan^{-1}v-\frac{1}{2}\ln (1+v^2)=\ln x +\ln C$$
$$\implies \tan^{-1}v=\ln Cx+\ln\sqrt{1+v^2}$$
$$\tan^{-1}(y/x)=D+\ln \sqrt{x^2+y^2}$$
which can be re written as
$$\ln x=\tan^{-1}(y/x)-\frac{1}{2} \sqrt{1+y^2/x^2}+D$$
Comment: @Moo You may see my answer again. I have solved it fully.


Adjust Elements after Manipulating String into AttributedString - Swift 4

Question: I have the following which allows me to create a bullet list which works really well, however, after the bullet list is created I need to manipulate the outputted Attributed string to have certain elements either in bold or in italics or both.
The function I have is:
@IBOutlet var label: UILabel!
let bulletString = ["String 1","String 2","String 3"]

label.attributedText = label.bulletPoints(stringList: bulletString, font: UIFont.stdFontMediumSeventeen, bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGreyColor, bulletColor: UIColor.darkGreyColor)

func bulletPoints(stringList: [String],font: UIFont,bullet: String = "\u{2022}",indentation: CGFloat = 20,lineSpacing: CGFloat = 2,paragraphSpacing: CGFloat = 12,textColor: UIColor = .gray,bulletColor: UIColor = .red) -> NSAttributedString{
    let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for string in stringList {
        let formattedString = "\(bullet)\t\(string)\n"
        let attributedString = NSMutableAttributedString(string: formattedString)

        attributedString.addAttributes(
            [NSAttributedStringKey.paragraphStyle : paragraphStyle],
            range: NSMakeRange(0, attributedString.length))

        attributedString.addAttributes(
            textAttributes,
            range: NSMakeRange(0, attributedString.length))

        let string:NSString = NSString(string: formattedString)
        let rangeForBullet:NSRange = string.range(of: bullet)
        attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
        bulletList.append(attributedString)
    }
    return bulletList
}

What I am looking for is a way to pass in a boolean to state if the bullet string requires either bold or italic text and if so what the elements of the intital string are that need this treatment.
The bulletPoints function sits in an extension file and works as expected.
Comment: Not clear what are you trying to achieve.. Do you want to modify existing attributed string by applying new attributes ? Or you want new parameters in function that are responsible for bold/italic?
Comment: So yes, I am looking for a function that I can invoke within the above function to set certain parts of the string(s) as bold or italic or both, but for the above function to be useable without these elements.
Comment: I don't understand what's your goal. How do you know where to apply the bold/italic (in other other, where to apply a new font)? If it's on an item of the list, just as you did `attributedString.addAttributes([NSAttributedStringKey.paragraphStyle : paragraphStyle], range: NSMakeRange(0, attributedString.length))` do the same with `NSAttributedStringKey.font` instead and a custom font.
Answer: Using a model to link the bold/italic to the strings in question, as Neil suggests, helps you in this case. Here's a version which links font traits to the strings for each bullet, then uses those when building up the string.
I've refactored your bulletPoints function as well, to remove the use of ranges and simplify it a little. It could stay in an extension (I assume you have it on UILabel?) but there's no reason for it to, since it returns the string anyway. I've written it as a function which could be used in any class
class ViewController: UIViewController {

    @IBOutlet var label: UILabel!

    override func viewWillAppear(_ animated: Bool) {
        let bulletStrings = [BulletString(string: "String 1", traits: []),
                             BulletString(string: "String 2", traits: [.traitBold]),
                             BulletString(string: "String 3", traits: [.traitItalic]),
                             BulletString(string: "String 4", traits: [.traitBold, .traitItalic])]
        label.attributedText = bulletPoints(stringList: bulletStrings, font: UIFont.systemFont(ofSize: 15.0), bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGray, bulletColor: UIColor.darkGray)

    }

    func bulletPoints(stringList: [BulletString],
                      font: UIFont,
                      bullet: String = "\u{2022}",
                      indentation: CGFloat = 20,
                      lineSpacing: CGFloat = 2,
                      paragraphSpacing: CGFloat = 12,
                      textColor: UIColor = .gray,
                      bulletColor: UIColor = .red) -> NSAttributedString {

        let bulletList = NSMutableAttributedString()
        for bulletString in stringList {
            let attributedString = NSMutableAttributedString(string: "")
            let bulletAttributes: [NSAttributedStringKey: Any] = [
                .foregroundColor: bulletColor,
                .font: font]
            attributedString.append(NSAttributedString(string: bullet, attributes: bulletAttributes))

            let textAttributes: [NSAttributedStringKey: Any] = [
                .font: font.withTraits(traits: bulletString.traits),
                .foregroundColor: textColor,
                .paragraphStyle : paragraphStyle(indentation: indentation, lineSpacing: lineSpacing, paragraphSpacing: paragraphSpacing)
            ]
            attributedString.append(NSAttributedString(string:"\t\(bulletString.string)\n", attributes: textAttributes))

            bulletList.append(attributedString)
        }
        return bulletList
    }

    private func paragraphStyle(indentation: CGFloat, lineSpacing: CGFloat, paragraphSpacing: CGFloat) -> NSParagraphStyle {
        let style = NSMutableParagraphStyle()
        let nonOptions = [NSTextTab.OptionKey: Any]()
        style.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
        style.defaultTabInterval = indentation
        style.lineSpacing = lineSpacing
        style.paragraphSpacing = paragraphSpacing
        style.headIndent = indentation
        return style
    }
}

struct BulletString {
    let string: String
    let traits: UIFontDescriptorSymbolicTraits
}

extension UIFont {

    func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont {
        let descriptor = self.fontDescriptor
            .withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits))!
        return UIFont(descriptor: descriptor, size: 0)
    }

}

If you wanted to have the bullets match the style of their strings, i.e. be bolded or italicised, you could just add the attributes in a single pass for each bullet
Answer: You can achieve it using multiple fonts and text ranges. If you know the ranges of the text on which you want to apply multiple styles, you can just use fonts. Check the below example.
let fullString = "Bold normal italic"
let attrString = NSMutableAttributedString(string: fullString, attributes: [.font: UIFont.systemFont(ofSize: 18.0)])

let range1 = (fullString as NSString).range(of: "Bold")
let range2 = (fullString as NSString).range(of: "italic")
attrString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 20.0)], range: range1)
attrString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 20.0).italics()], range: range2)

label.attributedText = attrString

Whereas I use simple extension for UIFont.
extension UIFont {
    func withTraits(_ traits: UIFontDescriptorSymbolicTraits) -> UIFont {
        if let fd = fontDescriptor.withSymbolicTraits(traits) {
            return UIFont(descriptor: fd, size: pointSize)
        }
        return self
    }

    func italics() -> UIFont {
        return withTraits(.traitItalic)
    }
}

So basically, what you need to know is, which text should be marked as italic, bold and normal. Afterwards just calculate the ranges for those texts in your original text using NSString.range(of: ) and update the attributes appropriately.
Note: You can also calculate the range using start and endIndex. For reference check this SO answer.
Comment: Thanks for this can you provide an example as per my function and call in my question please
Answer: One of the possible ways to make it work with the function mentioned in the question - to modify stringList parameter.
First of all let's define model class BulletString:
class BulletString {
   var text: String
   var attributes: [NSAttributedStringKey : Any]?

   init(string: String) {
      text = string
   }
}

Now your bullet stringList in you function should be [BulletString] type. Define two bulletStrings and pass them to your function. Here is a working solution with your function:
    let bulletString1 = BulletString.init(string: "string1")
    bulletString1.attributes = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 18.0)]

    let bulletString2 = BulletString.init(string: "string2")

    let bullets = [bulletString1, bulletString2]

    label.attributedText = bulletPoints(stringList: bullets, font: UIFont.systemFont(ofSize: 17), bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGray, bulletColor: UIColor.darkGray)
    label.textColor = .black

func bulletPoints(stringList: [BulletString], font: UIFont,bullet: String = "\u{2022}",indentation: CGFloat = 20,lineSpacing: CGFloat = 2,paragraphSpacing: CGFloat = 12,textColor: UIColor = .gray,bulletColor: UIColor = .red) -> NSAttributedString{
    let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for bulletString in stringList {
      let formattedString = "\(bullet)\t\(bulletString.text)\n"
      let attributedString = NSMutableAttributedString(string: formattedString)

      attributedString.addAttributes(
        [NSAttributedStringKey.paragraphStyle : paragraphStyle],
        range: NSMakeRange(0, attributedString.length))

      attributedString.addAttributes(
        textAttributes,
        range: NSMakeRange(0, attributedString.length))

      // Here your custom attributes you provided in BulletString
      if let attr = bulletString.attributes {
        attributedString.addAttributes(attr, range: NSMakeRange(0, attributedString.length))
      }

      let string:NSString = NSString(string: formattedString)
      let rangeForBullet:NSRange = string.range(of: bullet)
      attributedString.addAttributes(bulletAttributes, range: rangeForBullet)

      bulletList.append(attributedString)
    }
    return bulletList
}

Results


Cast C struct double pointer to a Swift struct unsafe pointer

Question: I need to do the following C casting in Swift (4):
struct A ** castme = input
struct B * tothis = (struct B *)castme

In Swift, castme type is UnsafeMutablePointer<UnsafeMutablePointer?>!
I assume I am trying to cast to UnsafeMutablePointer! ?
Also, would it be correct to say that I could also cast *(castme) to a (struct B) directly? If yes, would it make casting easier by casting from UnsafeMutablePointer? to B ?
I saw this thread but wasn't able to get what I needed from it:
Cast to different C struct unsafe pointer in Swift
Comment: Hmmm, casting a _pointer to a pointer_ to a `struct` pointer is unsafe in C too as posted here.  Need to see more of code for details.
Answer: Let's think about that in terms of what's happening in C. When I do a cast of pointers in C, the data that represents the pointer type will now be treated as a pointer of a different type. The value of the pointer doesn't change, just how you treat it.
Swift doesn't like to do this kind of thing and doesn't encourage you to do it because while cheap, it's a fundamentally unsafe thing to do and can lead to corrupting data, jumping into space, bus errors, etc.
That doesn't mean that swift doesn't have the ability to do this. The link that you point to uses withUnsafePointerTo which tries to limit the scope of the use of the pointer. In your case, you probably want to look at unsafeBitCast (documentation here) which mimics the C pointer cast (it's not strictly the same as C casting in general, but for pointers it is).
let a:UnsafeMutablePointer<SomeType> = fetchASomeTypePointer()
let b = unsafeBitCast(a, to: UnsafeMutablePointer<SomeOtherType>.self)

This makes the data representing the pointer to SomeType now become a pointer to SomeOtherType.
Like I said before, this is a dangerous thing to do especially if you don't fully understand what you're doing.


WSOD using Drupal 6 module code in Drupal 7?

Question: Here is my code which worked perfectly in Drupal 6 but gives me a blank white page WSOD in Drupal 7.15 and views 7.x-3.3;
<code><?php

function ajaxview_menu() {

  $items = array();

  $items['replies'] = array(
    'title' => 'Replies',
    'page callback' => 'ajaxview_replies',
    'description' => 'Replies',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function ajaxview_replies($nid) {
  $node = node_load($nid);
  $viewName = 'Replies';
  $display_id = 'default';
  $myArgs = array($nid);
  print views_embed_view($viewName, $display_id, $myArgs);
 exit();
}
</code>
What has changed and what am I doing wrong?
Answer: Apologies it was a stupid mistake.
The machine name  for $viewName was "replies" not "Replies".
Doh!


Most efficient way to have multiple criteria in an IF statement

Question: Basically, I hoping to achieve 2 things here.

I want to know if there is a way to make this multiple criteria IF statement shorter/more efficient. ie. how would this be done if using VBA best practices?

Is there a way to name each column as a range or variable on sheet 'upload file'? This works fine, I just want to know if there is a way that is better or if there is a 'best practices' method that would work better.

Thank you
    If (bulksheet.range("b" & x).Value = "keyword" Or bulksheet.range("b" & x).Value = "product targeting") And bulksheet.range("d" & x).Value = campaign And bulksheet.range("p" & x).Value = "enabled" And _
bulksheet.range("r" & x).Value = "enabled" And (matchtype = "broad" Or matchtype = "phrase" Or matchtype = "exact" Or matchtype = "targeting expression" Or matchtype = "targeting expression predefined") Then
    uploadfile.range("a" & uploadrowcounter).Value = campaign
    uploadfile.range("f" & uploadrowcounter).Value = adgroup
    uploadfile.range("i" & uploadrowcounter).Value = keyword
    uploadfile.range("n" & uploadrowcounter).Value = "enabled"
    uploadfile.range("j" & uploadrowcounter).Value = targetingid
    uploadfile.range("k" & uploadrowcounter).Value = matchtype

Comment: It might be better to focus on one question at a time.
Comment: The most efficient approach would be to split up that long line into multiple nested `If Then` statements - no need to test C,D,E,etc if A and B already failed.   There's no "short-circuiting" in VBA so all clauses are evaluated, even f the first has failed to pass.
Answer: Not sure about efficiency but Select Case is useful for multiple ORs and loops for ANDs.
    Dim b(4) As Boolean, i As Integer
    Select Case matchtype
        Case "broad", "phrase", "exact", "targeting expression", _
             "targeting expression predefined"
            b(0) = True
    End Select

    With bulksheet
        Select Case .Cells(x, "B")
            Case "keyword", "product targeting": b(1) = True
        End Select
        b(2) = (.Cells(x, "D").Value = campaign)
        b(3) = (.Cells(x, "P").Value = "enabled")
        b(4) = (.Cells(x, "R").Value = "enabled")
    End With

    ' AND
    For i = 1 To UBound(b)
       b(0) = b(0) And b(i)
    Next

    Dim ar
    ar = Array("A", campaign, "F", adgroup, "I", keyword, _
               "N", "enabled", "J", targetingid, "K", matchtype)

    If b(0) Then
        For i = 0 To UBound(ar) Step 2
            uploadfile.Cells(uploadrowcounter, ar(i)).Value = ar(i + 1)
            'Debug.Print ar(i), ar(i + 1)
        Next
    End If

Comment: This is much better organized than OP's code. But this is very slow code. My reading of the question was that OP was also looking for efficiency and bedt practuces.
Answer: This is hundreds of times faster...

Dim v, w

v = bulksheet.Range("a" & x & ":r" & x)

If v(1, 2) = "keyword" Or v(1, 2) = "product targeting" Then
  If v(1, 4) = campaign Then
    If v(1, 16) = "enabled" Then
      If v(1, 18) = "enabled" Then
        Select Case matchtype
          Case "broad", "phrase", "exact", "targeting expression", "targeting expression predefined"
            With uploadfile.Range("a" & uploadrowcounter & ":n" & uploadrowcounter)
              w = .Value2
              w(1, 1) = campaign
              w(1, 6) = adgroup
              w(1, 9) = keyword
              w(1, 14) = "enabled"
              w(1, 10) = targetingid
              w(1, 11) = matchtype
              .Value2 = w
            End With
        End Select
      End If
    End If
  End If
End If

Research Short-circuiting Conditional Expressions in VBA.
Research Variant Arrays for Speed in VBA.
Comment: To the brave lad that just marked down this answer... explain yourself!


How to learn the points inside a square with its boundary?

Question: Is it possible to classify the points inside a square? i.e. if $a \le x \le b$ and $c \le y \le d$ then label is $+1$ otherwise $0$.
Is that possible using SVMs for example?
Comment: Do you have to use an SVM? It's possible that this could be easier with another approach.
Comment: no, I don't need to use SVMs but the data in the process tend to a square when time tends to infinity. thanks.
Comment: Please describe the kinds of data you are expecting: comments to the answers suggest to me that people might have different understandings of what data you have and what you are really trying to accomplish, so it really is important to edit this question to make it clearer.
Comment: whuber: you are right. I need to make the problem more precise. I'll probably just post a new question with a more precise problem statement.  The answers given here is still quite good and one can still learn from them. Thanks all !
Comment: Essentially the same problem is addressed in this answer. http://stats.stackexchange.com/questions/164048/can-a-random-forest-be-used-for-feature-selection-in-multiple-linear-regression/164068#164068
Answer: Your specification of the square as having sides parallel to the boundary makes the problem relatively straightforward - as long as you don't require it to be written as a single SVM, but can settle for something like it.
One very simple estimate of the boundary of the square is for those points which have $+1$ labels to simply take the min and max of $x$ and the min and max of $y$. (It will be too small, of course, but if there are lots of points, not my much.)

If you then exclude the points with "$0$" labels above the top and below the bottom of that square, you can use SVM or something similar to SVM on the left and the right half of the $x$'s (it's only a 1-D problem for each side! Easy.)
-- so on the right side, for example, you just need the smallest $x$ with a "$0$"-label above the largest "$1$"-label $x$), ...

(For your next approximation of the square, you could split the difference between the biggest $1$-x and the next biggest $0$-x:

You can then repeat the procedure for the left, top and bottom boundaries. This gives a much better estimate of the boundary than the initial one.)
Of course this won't be exactly square (indeed to this point the algorithm is really for a rectangle with sides parallel to the axes), but the 4 sets of green and pink lines (not all shown) give you boundaries inside which you want to fit the square.
So from there it's a matter of expanding the sides of the blue on the "narrow" direction of the almost-square rectangle and shrinking the "wide" direction, until it's square. Note that you don't shrink/expand the sides evenly; if you want to be SVM-ish, you'd do it so as to even up the amount of remaining "wiggle room" (distance between blue and green or pink, whichever is closer) they have (that is, you'd move the side with the biggest gap between green and pink first, until you reach the size of the next-smallest gap between blue and either green or pink, then change both of those simultaneously until you hit the next smallest gap, and so on).
(With a bit of thinking most of this step can be done very simply.)
So this does some initial processing ($\cal{O}(n)$) to find the inner and outer boxes and the blue rectangle - essentially four trivial "SVM"s, followed by a simple set of expansion/shrinkage calculations to find an actual square.
If there really is a square that perfectly separates the "$1$" and "$0$" cases, that should work quite well and give a nicely SVM-like solution. (If there's not perfect separation, you may need to actually adapt this further in order to minimize misclassification.)
Comment: Thanks but it seems that your method works when we do know the value of the boundaries. In my case, I don't know their value, all I know is that the incoming data will fill a square when time tends to infinity  and I don't know how to exactly decide about when a point is not in the square since any given point may end up converging to the square in infinite time. thanks.
Comment: There should be some points that you know are outside the square else why would you think to use SVM?
Comment: Where do you think my method uses the values of the boundaries? Of course you'll never know perfectly whether an unlabelled point is in the true square or not, except as $n$ goes to infinity. That's true of nearly any classification problem.
Answer: SVM is a linear classifier which means that it can only learn to decide which side of a straight line the points should go. To make a square you obviously need four straight lines. So the short answer is no a linear SVM can not learn a square.
However, you can apply a kernel function to your data to map it into a higher dimension. If you choose the right kernel, there could be a high dimensional line that corresponds roughly to a square in the lower dimensional space.
Think of it like this. Your points lie on a piece of paper and the SVM is a pair of scissors that gets to make one straight cut. You want to capture just the points in the square with that one cut. If the page is flat you can't do it. If you pinch the paper in the middle of the square so that part is raised. you could cut below the pinch and with a single cut select those points.
Comment: Why dont you just find the square instead of using SVM?
Comment: Thanks but what would be a good transformation that transforms a points in a square to points on the same side of high dimensional line ?
Comment: How ? the square appears only in infinite time. Thanks.
Comment: My point was to do what @Glen_b later suggested in his answer
Comment: Ok, thanks. Perhaps you can see my comment on @Glen_b suggestion.


How to rename package in grail

Question: I have installed grails support in STS. and I have a grails application inside that I got package com.mycompany.myapp in domain, controllers and tests. I want to rename them to mycompany.myapp, So that It should affect the functionality of application. Is there any way to do it in Grails.
Answer: You can use the normal Eclipse refactoring tooling ie ALT+SHIFT+V to move package.
If you're using any inheritance in your domain classes you'll need to upgrade the class name in the class column for these tables.
Comment: If it´s a Mac user "Cmd + shift + R" will do it :)

How to rename package in grail


How can I split the User name and password group in the register page?

Question: I want to split the User name and password group in the register page into separate fields but they are wrapped into "

Register
..."
The open "div" is set as a prefix on the account name field but I can not find the close div.
Comment: Found it. A suffix with a close div is added to the submit button.
Answer: You can use the Account field split module for this:

About
Currently the draggable field "Username and password" on user profile
mashes together:
Username
Current password
E-mail address
Change Password
Roles
Status
Notify user about new account (when admin create new account)

This module aims to split "Username and password" into standalone
fields for site builders who want to manage that fields separately.


Counting and then removing duplicates from email list

Question: I have a long list of email addresses (8000) sorted alphabetically but there are duplicates.
With python - how can I count the number of recurrences of a unique email (count duplicates) and while maintaining one instance of the email delete the recurring duplicate emails from the list.
example list:
email@example.com
firstname.lastname@example.com
email@example.com
firstname.lastname@example.com
firstname.lastname@example.com
email@example.com

results:
email@example.com (1)
email@example.com (3)
email@example.com (2)

I've searched online, but only find methods of removing duplicate numbers, dictionaries and tuples.
Answer: Use itertools.groupby() for alphabetical sorted order:-
 >>>l = list of emails
 >>>[(key, sum(1 for _ in group)) for key, group in groupby(sorted(l))]

[('email@example.com', 1), ('email@example.com', 3), ('firstname.lastname@example.com', 2)]

Use collections.Counter to count the items that are duplicate.
>>>from collections import Counter
>>>d = Counter(['firstname.lastname@example.com',
>>>'firstname.lastname@example.com',
>>>'email@example.com',
>>>'email@example.com',
>>>'firstname.lastname@example.com',
>>>'firstname.lastname@example.com'])
>>>d

Output:-
Counter({'email@example.com': 3, 'firstname.lastname@example.com': 2, 'email@example.com': 1})

It is similar to(or in simplest way)
d = {}
for i in l: # l = list or all emails.
    if i in d:
        d[i] += 1
    else:
        d[i] = 1

or use dict.get
    for i in l:
        d[i] = d.get(i, 0) + 1
Comment: `d[i] = d.get(i, 0) + 1` is a better idiom.
Answer: you can use collections.Counter:
>>> from collections import Counter
>>> my_email
['email@example.com', 'firstname.lastname@example.com', 'email@example.com', 'firstname.lastname@example.com', 'firstname.lastname@example.com', 'email@example.com\n']
>>> Counter(my_email)
Counter({'firstname.lastname@example.com': 3, 'email@example.com': 2, 'firstname.lastname@example.com': 1})

if you want in order:
>>> sorted(Counter(my_email).items())
[('firstname.lastname@example.com', 1), ('email@example.com', 3), ('email@example.com', 2)]

you can print like this:
>>> for x in sorted(Counter(my_email).items()):
...     print x[0],x[1]   # if you sung python 3 print(x[0],x[1])
...
email@example.com 1
firstname.lastname@example.com 3
firstname.lastname@example.com 2

Comment: Subsequent sort is required. However, 8000 entries are nothing before built-in sort.
Comment: If you're going to sort based on keys then the `key` call is useless, a dict always has unique keys.
Comment: yea right, its useless


OpenX: Moved to different Server

Question: I moved the installation to a different server. I updated the configfile in the var/ directory and the banners are served, but the admin interface is not working.
i get the error:

A fatal error occurred OpenX can't connect to the database. Because of
  this it isn't possible to use the administrator interface

i cleaned the cache directory in var but then i get
PHP Fatal error:  Call to undefined method MDB2_Error::quoteIdentifier() in /[path]/opx/lib/OA/Upgrade/VersionController.php on line 50
I dont know which version this is, but it looks like its at least 2 years old.
Is there any special cache in place im not aware of?
Any help on this would be much appreciated.
Comment: There is really nothing wrong with @alex's question. It is not unusual to have webservers and databases running on separate boxes.
Comment: Did you move the database too?
Comment: of course :D what a question.... the banners are served too so all is right. the user can connect to the db too.
Comment: in fact the database is running on a different server, but it was also moved form yet another server :). i thought alex meant i forgot about the database when i moved the server.
Comment: @Rufinus Basic cause of something like this.. Do you have the correct database configuration? Host, Username, Password and even possibly the correct port?
Comment: yes, as mentioned i can connect with the credentials in the config even the banners are getting delivered, the only thing not working is the admin backend.
Answer: Mental note,.. if you have the db on a different server then openx it does not matter if you set the host to the ip of the db server and the port.. as long if you not set protocol=protocol !!!
this is by far the most stupidest thing i have ever seen, there is no need for a protocol config, as php always uses the socket if you set "localhost".
Comment: Speaking of stupid things… I just killed 2 hours looking into this, only to find out that my (randomly generated) DB password contains a '%' and MDB2 does not seem to likes this. After changing to another password, everything worked.
Answer: It's not easy to tell exactly what's wrong here, but one can make a good guess:
As we can see from the error message, there is an object in your code that doesn't implement the method quoteIdentifier().
There are mainly two possible reasons for this: Either we're calling an older or newer version of the same Class instance which doesn't implement the method. Maybe because it's deprecated or who knows. Or the object simply isn't of the expected type.
Lo and behold, if we look for an MDB2 related class that DOES implement this method, it's the class MDB2. Not MDB2_Error! So now we know the reason for the error, it's time to speculate about the root cause.
Connecting to a database with MDB2 works roughly like this:
$mdb2 =& MDB2::connect('pgsql://usr:pw@localhost/dbnam');
if (PEAR::isError($mdb2)) {
    die($mdb2->getMessage());
}

There it is. We can see that $mdb2 can actually be of type MDB2_Error, in case connecting goes wrong for some reason. So that is the cause: Your code cannot connect to the DB for some reason. So the next obvious step should be checking if your db user has the correct rights and is using the correct password. I am 100% sure your admin backend doesn't use the right credentials.

OpenX: Moved to different Server


What is the probability that the Pfizer/BioNTech vaccine is not/less effective than the study suggests?

Question: The Pfizer/BioNTech vaccine has a reported efficacy of 90%. AFAIK, the phase III study has the following preliminary results (as of November 9):

43'000 people were given a shot, 50% received the vaccine, 50% a placebo
Of these 43'000 people, 94 got tested positive for Covid-19 during the study
Of these 94 people, fewer than nine were in the group that received the vaccine, the others were in the control group.
This means we have a (preliminary) efficacy of more than 90%.

Let's give these numbers some variable names (and let's fix some numbers to get rid of the "fewer than"):
\begin{aligned}[ll]
N &= 43'000\\N_{vac}&=21'500\\N_{cg}&=21'500\\C_{vac}&=9\\C_{cg} &= 85
\end{aligned}
Both the vaccinated group and the control group have 21'500 members. There are $C_{vac}=9$ Covid-19 diagnoses within the vaccinated group, and $C_{cg}=85$ in the control group.
I would like to use these numbers to calculate the probability $P_X$ that the vaccine has efficacy $X$ or higher.
Of course, $P_X$ should have its steepest part around $X=90\%$, because that is the most likely efficacy of the vaccine, according to the study. But still, we have the possibility that the study over-estimated the efficacy of the vaccine, because of random effects.
The higher $N$ is, the more "narrow" we expect the derivative of $P_X$ to be (the more participants in the study, the less uncertainty). For very small $N$, $P_X$ should be very close to $X$ itself, because we do not know much about the vaccine.
How can I calculate $P_X$?
Comment: Of 43000 people, 94 tested *positive* for Covid-19, presumably after reporting symptoms.  We do not know how many were tested negative, or how many had the virus without symptoms and so without a test.
Comment: @Henry of course. Fixed.
Answer: They used a Beta-Binomial Bayesian model to calculate the posterior efficacy (link to study plan as PDF).
First, letting $\pi_v$ and $\pi_c$ be the population probabilities that a vaccinated or a control subject contract Covid-19, respectively. The population vaccine efficacy is defined by
$$
\mathrm{VE}=1 - \frac{\pi_v}{\pi_c}
$$
The statisticians assume a prior distribution for the parameter
$$
\theta = \frac{1 - \mathrm{VE}}{2 - \mathrm{VE}}
$$
Substituting the definition of the efficacy, this can be rewritten as
$$
\theta = \frac{\pi_v}{\pi_v + \pi_c}
$$
So $\theta$ is the probability that a subject who contracted Covid-19 is from the vaccinated group and $1-\theta$ is the probability that the subject was in the control group.
The study plan states that they assumed a Beta($a_0 =0.700102, b_0=1$) prior for $\theta$ which results in a prior mean of $\mathrm{E}(\theta)=0.4118$ which corresponds to a prior mean of 30% efficacy, because $\mathrm{VE}=(1 - 2\theta)/(1-\theta)$.
Recall that the posterior is simply another Beta distribution with parameters $a_1 = a_0 + m_v$ and $b_1 = b_0 + m_c$ where $m_v$ and $m_c$ denote the number of subjects that fell ill in the vaccinated and control group, respectively. You can calculate all desired probabilities from this posterior distribution (and updated it when more data are available).
Let's illustrate it with the data given in your post. We have $m_v = 9$ and $m_c = 85$ so the posterior Beta distribution has parameters $a_1 = 0.700102 + 9 = 9.700102$ and $b_1 = 1 + 85 = 86$. We are interested in the probability that the vaccine has 90% efficacy or more which corresponds to a $\theta \leq 1/11$.
The calculations in R are as follows:
# Priors
a0 = 0.700102
b0 = 1

# Posterior
a1 = a0 + 9
b1 = b0 + 85

# Critical probability
p_crit <- 0.9
theta_crit <- (p_crit - 1)/(p_crit - 2)

# Posterior probability
pbeta(theta_crit, a1, b1)
[1] 0.3982548

# Mode
theta_mode <- (a1 - 1)/(a1 + b1 - 2)
(1 - 2*theta_mode)/(1 - theta_mode)
[1] 0.8976459

So the posterior probability that the efficacy is greater than 90% is $0.398$ which corresponds to the grey area in the plot. The mode of the posterior Beta distribution is at $0.093$ which translates to an efficacy of $0.898$, which corresponds nicely to the reported efficacy of 90%.
Here is the plot of the posterior density. The red vertical line denotes the $\theta$ below which the efficacy is $\geq$90% (depicted by the grey area):

A more detailled exposition can be found in this blog.
Comment: Thanks Frans. The study protocol (page 103) states that they centered the prior on an efficacy of 30% (this corresponds to the cited Beta distribution) which they consider pessimistic while still allowing for a substantial uncertainty (the prior 95% interval is 0.005 to 0.964). As to why they chose 30%, I'm not sure but I haven't studied the protocol in great detail to be honest.
Comment: +1 Always appreciate your answers! Any idea why they specifically chose $\alpha_0 = 0.700102$?
Comment: The post [How to describe Pfizer's beta(0.7, 1) prior on vaccine effect?](https://statmodeling.stat.columbia.edu/2020/11/13/pfizer-beta-prior-vaccine-effect/) discusses this choice of prior and notes that a beta(1, 1) prior would have resulted in a very similar posterior distribution.


Inject/embed/$sanitize HTML into AngularJS from JSON data

Question: I am faced with an issue that I cannot find a solution for.
So I am trying to create an application that will display tracks taken from soundcloud and display them on my page using the soundcloud embeded player. I will be using DjangoREST to create a JSON list of all the tracks I want displayed. The JSON will have an entry to store the embeded HTML and will be packaged up and sent to the AngularJS front end.
The problem I am facing is that I am unable to actually display the embeded HTML even after using ng-bind-html.
I created a small demo to demonstrate the issue I am facing.
app.js
(function(){
    var app = angular.module("tracklist", []);

    app.controller("TrackListController", function () {
        this.tracks = soundcloudtracks;
    });

    // Very basic JSON track coming in from DjangoREST
    var soundcloudtracks = [
        {
            title: 'Track1',
            artist: 'Artist1',
            html: '',
        },
        {
            title: 'Test2',
            artist: 'Artist2',
            html: '',
        },
    ]
})();

index.html
<!DOCTYPE html>

{{ track.title }} - {{ track.artist }}

From my understanding I need to $sanitize the incoming HTML but I don't know how to properly sanitize each element within an ng-repeat. Could anyone help me out? I am completely lost at this point.
Thanks for your time.
Answer: Ok so I believe I was able to resolve the issue. I just created a method to sanitize my html.
app.js
(function(){
    var app = angular.module("tracklist", ['ngSanitize']);

    app.controller("TrackListController", ['$scope', '$sce', function($scope, $sce) {
        this.tracks = soundcloudtracks;
        $scope.deliberatelyTrustDangerousSnippet = function(html) {
          return $sce.trustAsHtml(html);
        };
    }]);

    // Very basic JSON track coming in from DjangoREST
    var soundcloudtracks = [
        {
            title: 'Track1',
            artist: 'Artist1',
            html: '',
            url: 'http://soundcloud.com/forss/flickermood',
        },
        {
            title: 'Test2',
            artist: 'Artist2',
            html: '',
            url: 'http://soundcloud.com/forss/flickermood',
        },
    ]
})();

index.html
<!DOCTYPE html>

{{ track.title }} - {{ track.artist }}

Now everything is working as expected!


How do you create variables in actions.class.php so that they are accessible in layout.php?

Question: In Symfony 1.2, how do you create variables in actions.class.php so that they are accessible in layout.php?
Answer: I think, by default, you can't, since it should be against the MVC pattern.
You should better pass variable to your view, but without using global (or kind of).
Answer: This page has some information about it: http://trac.symfony-project.org/wiki/Symfony11LayoutUpgrade
It seems you can get the desired effect using this following code:
<code>$this->getResponse()->setSlot('title', 'insert your title here');
</code>
And then use this in the layout file:
<code><title><?php echo get_slot('title') ?></title>
</code>


Why are the labels for two different form elements so different? Can I make them the same?

Question: I created a webform that has one textfield and two radio button fields.
When displaying, the textfield label is themed correctly, but the radio button labels are not.
When I look at the tags and classes, the texfield label has a "label" tag with "control-label" class like this
Textfield label

but the radio labels have "span" tags with "fieldset-legend" class, inside "legend" tags, like this
<legend>
    Radio element question
  </legend>

Why are they different? Can I ake them the same, or is add a CSS style to make the span.fieldset-legend match the label.control-label the only way to make them the same?
I am using the Bootstrap 3 theme and I enabled the webform-bootstrap module.
Answer: The differences here come down to the differences in the two types of form elements.
From the MDN docs for the label element:

The HTML  element represents a caption for an item in a user interface

From the MDN docs for the legend element:

The HTML  element represents a caption for the content of its parent .

Looking at the example from the legend documentation, we see how the two types of elements, labels and legends, are semantically different.
<fieldset>
    <legend>Choose your favorite monster</legend>

    <input type="radio" id="kraken" name="monster">
    Kraken

    <input type="radio" id="sasquatch" name="monster">
    Sasquatch

    <input type="radio" id="mothman" name="monster">
    Mothman
</fieldset>

Each radio button has its own label element with text describing it. Meanwhile, the set of radio buttons is wrapped in a fieldset with a legend element to describe the group as a whole.
While you may be able to alter the markup for your radios, to replace the legend element with a label, you should not, especially if you're trying to build an accessible website (and you should be). This answer to Is it good practice to use  for non-input/non-interactive elements? provides a more detailed explanation for why you shouldn't use a label in a context like this.


Finding good minimalist base themes

Question: I am working on a Drupal project and teaching myself the system as I go along. I am trying to find a minimalist theme to use as a base for developing this site. I don't want a framework, because I don't have time to learn that too. I really just want a minimalist theme that looks good out of the box, but that can be easily modified in basic ways.
In my experience so far, most Drupal themes are either overly designed, or completely lacking in any formatting whatsoever. In the WordPress world, there is (for example) something like Thesis, which looks good out of the box but also has lots of potential for modification. Another example would be WooThemes' Canvas. Is there anything similar in the Drupal world?
Answer: Zen is all right but after using it a while I ran into problems since it's not built on the grid system. I found Omega pretty amazing as a grid-based starter theme for Drupal 7 with a responsive option. The steep learning curve was worth it, and it provides great tools and help.
Comment: Omega + Omega Tools does a lot of things for you. Whether or not it would take longer to learn than Zen depends more on your background approach and what you're trying to accomplish than on anything inherent to the frameworks. Good luck.
Comment: Thanks - I have seen Omega and it looks cool. But I'm on a tight timeline, and I have to do all the development and theming myself. I don't have time for two learning curves (Drupal and a theme framework).
Comment: For our new projects we use Omega... it's emphasis is on Responsive theme and so far we haven't hit any major snags with interoperability with custom modules
Answer: Personally, I find Corolla a very good theme to start with, and it is built on top of AdaptiveTheme,- a really good framework for creating your own subthemes.
Answer: As you are looking for a Drupal base theme, I suggest you to take a look at Nucleus base theme from themebrain.com.
Also on themebrain.com there are themes that match your requirement: TB Sirate or TB Simply (look good and can be easily modified in basic ways).
Answer: The Zen theme is a pretty good starting point for designing your own theme. Unfortunately I can't compare it to Thesis or WooThemes because I'm unfamiliar with wordpress. Here is a link: http://drupal.org/project/zen
Answer: If you are interested in all the modern buzzwords (html5, responsive ...) :) then pony might be of interest to you. Its not on drupal org yet, but is rather lightweight, has some design and accomodates some of the new ideas.
Answer: I would also recommend Zen, but if you want a theme with lots of features, then I would also look at Sasson. It contains a CSS SASS compiler built in, responsive support, and support for HTML. It's also very quick to get going with, and you don't need to use any of the extra features.
Answer: You have hit on a philosophical difference between Wordpress and Drupal. In Wordpress "Theme" means look-and-feel. In Drupal Theming is much more structural, and you have to add the look-and-feel using css and your own images.
I moved from Wordpress to Drupal 6 or 7 years ago, and found that I liked the Zen theme. I fought with it a little bit to make it look like a wordpress theme with header images, and drop-shadows, but that was mostly CSS and a little bit of page-tpl.php

Finding good minimalist base themes


Implicit function theorem - derivatives

Question: Let us have two function $n(\alpha)$ and $s(\alpha)$ and a set of two implicit equations $F_1(\alpha, n(\alpha), s(\alpha))=0$ and $F_2(\alpha, n(\alpha), s(\alpha))=0$. In this paper I've been reading they state that one can use the implicit function theorem to this set of implicit equations and gain
$
\frac{\partial n}{\partial \alpha}=-\frac{det A}{det B}
$
where
$A=\begin{bmatrix}
 \frac{\partial F_1}{\partial s} & \frac{\partial F_1}{\partial \alpha} \\
 \frac{\partial F_2}{\partial s} & \frac{\partial F_2}{\partial \alpha}
 \end{bmatrix}
$
$B = \begin{bmatrix}
 \frac{\partial F_1}{\partial s} & \frac{\partial F_1}{ \partial n} \\
 \frac{\partial F_2}{\partial s} & \frac{\partial F_2}{\partial n}
 \end{bmatrix}$
I cannot comprehend how they gained that partial derivative of n. Would be grateful for any advice.
Answer: Let's replace $F_1$ and $F_2$ with $F$ and $G$. Differentiating each implicit equation, and using $F_1(u, v, w)$ to denote the derivative of $F$ with respect to its first argument, etc.) we get
\begin{align}
\newcommand{\al}{\alpha}
0 &= F_1(\al, n(\al), s(\al)) + F_2(\al, n(\al), s(\al))n'(\al) + F_3(\al, n(\al), s(\al))s'(\al)\\
0 &= G_1(\al, n(\al), s(\al)) + G_2(\al, n(\al), s(\al))n'(\al) + G_3(\al, n(\al), s(\al))s'(\al)
\end{align}
where I've used $n'(\al)$ to denote the thing you've called
$$
\frac{\partial n}{\partial \alpha},
$$
but which should probably be
$$
\frac{dn}{d\al}
$$
because $n$ appears to be a function of a single variable. Rewriting those two equations a little, and getting rid of all the arguments, we have
\begin{align}
0 &= F_1  + F_2 n' + F_3 s'\\
0 &= G_1  + G_2 n' + G_3 s'
\end{align}
which we can rewrite in matrix form as
$$
\pmatrix{0\\0} =
\pmatrix{
F_1 & F_2 & F_3 \\
G_1 & G_2 & G_3
}
\pmatrix{1\\n'\\s'}
$$
Adding a row to make this $3 \times 3$, we get
$$
\pmatrix{0\\0\\1} =
\pmatrix{
F_1 & F_2 & F_3 \\
G_1 & G_2 & G_3 \\
1 & 0 & 0
}
\pmatrix{1\\n'\\s'}
$$
and calling the $3 \times 3$ matrix $M$, we can solve
$$
M^{-1} \pmatrix{0\\0\\1} =
\pmatrix{1\\n'\\s'}
$$
And we see that all we really need is the second entry of
$$
M^{-1}\pmatrix{0\\0\\1}.
$$
The authors have applied Cramer's rule to deduce that it is the ratio of determinants that they wrote down (I assume).
Reasonable questions are: "How did you know that adding [1 0 0] gave you an invertible matrix?" and "How did you decided to do that, anyhow?"
For the first: I didn't know that. But the authors don't seem to worry that $\det B$ might be zero, so I figure we're just doing some handwaving in some kind of generic case for the time being.
For the second: A ratio of determinants reminded me of Cramer's rule, so having written things in $3 \times 2$ matrix form, I just wanted to add the simplest possible thing to get a $3 \times 3$ form.
I'll be honest...I didn't actually go through Cramer's rule and check that this all works out. But I'll bet it does...
Comment: Thank you very much, that´s exactly what I needed :) ..and yes there should be $dn/d\alpha$

Implicit function theorem - derivatives


Selecionar texto entre parênteses(CSS)

Question: Gostaria de saber se existe uma forma de selecionar um texto que está entre parênteses utilizando apenas CSS.
Por exemplo.:

Sistemas de informação (ead)

Eu gostaria de selecionar o texto "ead" e colocar ele em letras maiúsculas.
Existe uma forma de fazer isso utilizando APENAS CSS?
Comment: Acredito que isso não é possível, você vai precisar usar javascript.
Comment: É o que eu imaginei a primeiro momento... mas resolvi compartilhar a dúvida com os especialistas aqui rs
Comment: Por hora, acredito que não tenha como. Mas o CSS vem trazendo funcionalidades mais específicas para textos. Como, por exemplo, o seletor de letras: `:nth-letter`, o seletor de palavras: `:nth-word`, etc. Dá uma olhada aqui: (TL-DR) [CSS-Tricks 2019 Wishlist](https://css-tricks.com/2019-css-wishlist/)
Comment: Obrigado pela recomendação. Vou dar uma lida.
Answer: Você pode utilizar o seguinte css:

.exemplo{
 text-transform: uppercase;
}

Sistemas de informação (ead)

JsFiddle
Comment: @LeandroCastro Se for viável, poste a parte onde é renderizado esse texto, tal como seu container, que dá pra fazer isso via JavaScript. Posso lhe oferecer uma resposta exemplificando, se lhe for útil! - Lembre-se de atualizar a pergunta, já que pede exclusivamente via CSS.
Comment: Sim... mas nesse caso específico, eu não consigo printar as tags "span" pois o texto é escrito na tela de forma dinâmica(trazido de uma api). Gostaria de um seletor que fosse especificamente para selecionar textos entre parênteses.
Comment: Agradeço a atenção. Mas com JS eu consigo fazer... Queria mesmo era descobrir se isso é possível com CSS...
Answer: No momento ainda não é possível, pois ainda não temos um seletor de ::last-word, ou ::first-word. Nem nos drafts dos Seletores Level 4 existe menção a esse tipo de seletor como vc pode ver aqui: https://drafts.csswg.org/selectors-4/
Se vc quiser tentar algo com JS aqui tem o plugin que pode te interessar. http://letteringjs.com/
E aqui um exemplo com jQuery. Ele basicamente coloca a última palavra dentro de um span e seta a classe

$(".lastWord").html(function(){
  var text= $(this).text().trim().split(" ");
  var last = text.pop();
  return text.join(" ") + (text.length > 0 ? "(" + last + ")" : last);
});
.red {
  color: red;
  font-weight: bold;
}

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

Fonte do código https://codepen.io/mel/pen/jLEKH
Comment: Obrigado pela resposta. Mas eu gostaria de descobrir se é possível fazer isso utilizando apenas CSS... Com JS eu consigo fazer... Queria era matar essa curiosidade rs
Comment: @LeandroCastro nesse caso infelizmente só com CSS não é possível. Com CSS vc consegue pegar a primeira letra `::first-letter` ou a primeira linha `::first-line`, mas não uma palavra, seja no início ou no final, e para piorar nem consta nada a respeito nos Drafts, então não espere por isso tão cedo... Se o texto fosse na mão vc poderia usar um simples `::after` para incluir o texto. Mas como vc falou que o texto vem de uma API, acho que o ::after não daria certo...

Selecionar texto entre parênteses(CSS)


Como funciona a propriedade inline-size?

Question: Eu estava dando uma fuçada no console do navegador ajustando um elemento, e percebi que o Google Chrome completou uma propriedade chamada inline-size. Não me lembro de ter visto essa propriedade antes, mas percebi que ela afeta o tamanho dos elementos que usam a mesma.
Pesquisei sobre ela, mas vi pouca explicação sobre a mesma.
Me surgiu algumas dúvidas:

Essa propriedade é nova?
Como ela funciona? Que problema ela resolve?
Quais são navegadores têm suporte?
Ela tem alguma relação com elementos que possuam o atributo display com os valores prefixados por inline-?
Comment: Relacionado: [O que são propriedades lógicas no CSS?](https://pt.stackoverflow.com/q/427573/69296)
Comment: Ela funciona de forma lógica
Answer: A propriedade do CSS inline-size define o tamanho horizontal e vertical de um elemento bloco. Ele é correspondente a cada propriedade width ou a height, dependendo do valor de writing-mode.
Espero ter ajudado.


What is expected value of a sample mean?

Question: Let $X_1,. . . , X_n$ be a random sample from a population with variance $σ^2$ and mean $μ$. Designate the corresponding sample mean by $\bar{X}$. Show that $\mathbb{E}(X_i\bar{X})=σ^2/n + µ^2, i = 1, . . . , n.$
Help please! Can't do anything.
Comment: Have you tried anything?
Comment: Yes. But I came to $σ^2+µ^2$.
Comment: Start by using the linearity of the expectation operator and assume the sample values $X_i$ are independently distributed.  Keep in mind that the sample mean $\overline{X}$ includes a factor $1/n$.
Answer: For some $i \in \{ 1, \dots, n\}$,
$$X_i\bar{X}=\dfrac{X_1X_i+X_2X_i+\cdots+X_{i-1}X_i+X_i^2+X_{i+1}X_i+\cdots+X_nX_i}{n}$$
Now for some $j \in \{1, \dots, n\}$, where $j \neq i$, we have
$$\mathbb{E}[X_jX_i]=\mathbb{E}[X_j]\mathbb{E}[X_i]=\mu^2$$ due to independence (random sampling). Furthermore, $\mathbb{E}[X_i^2] = \sigma^2+\mu^2$.
Hence,
$$\mathbb{E}[X_1X_i+X_2X_i+\cdots+X_{i-1}X_i+X_i^2+X_{i+1}X_i+\cdots+X_nX_i]=(n-1)\mu^2+\sigma^2+\mu^2$$
which simplifies to
$n\mu^2+\sigma^2$.
Now multiply by $\dfrac{1}{n}$.
Comment: @AndriyRussu If my answer was helpful, please click the checkmark next to my answer. This will encourage people to answer your future questions.


creating a custom entity which stores multiple bundles as per user input?

Question: I want to create an custom entity(Lets say payroll entity) which has the following fields
1. Basic salary
2. Earnings
3. Deductions
It is possible by Entities
But now I would like to add some new feature

Basic salary(field)
Earnings(Bundle) contains (bun1, bun2, bun3 fields)
Deduction(Bundle ded1,ded2 and ded3 fields )

If a user wants to set his employee's Earnings and other details he can manual sets it .For an example if a user needs to set his/her employee's salary like daily allowance, travel allowance, bonus etc)  he/she can do it from their own choice . And there should not be any restrictions for the no. of fields to add either bundles or fields . A user add custom bundles as well as custom fields.
Answer: Satyabrata,
Not sure i got the requirement correct. Have you considered using entity reference + inline entity form? You can attach bundles to the main bundle and can create them (sub bundles) from the main bundle using inline entity form .
Hope it helps.


Declare const in Qt and access from 2 different classes

Question: I develop in Qt5 and want some advice.
I want to declare const variable in one class and use this variable in other classes.
what is the best way to do that?
Now i get error in my code:
protocolcommands.cpp
const QString CNT_FIRMWARE_ACK = "ACK";
const QString CNT_FIRMWARE_NAK = "NAK";
const QString CNT_FIRMWARE_NYET = "NYET";
const QString CNT_FIRMWARE_STALL = "STALL";
const QString CNT_FIRMWARE_HEARTBEAT = "HEARTBEAT";

QString ProtocolCommands::parseCommand(QByteArray ba)
{

    QString s;
    if (ba[2] == 0x02)
    {
        s = "flow control";
        if (ba[3] == 0x01 && ba[4] == 0x01)
          return CNT_FIRMWARE_ACK;
        if (ba[3] == 0x01 && ba[4] == 0x02)
          return CNT_FIRMWARE_NAK;
        if (ba[3] == 0x01 && ba[4] == 0x03)
          return CNT_FIRMWARE_STALL;
        if (ba[3] == 0x01 && ba[4] == 0x04)
          return CNT_FIRMWARE_NYET;
    }
    else if (ba[2] == 0x03)
    {
        s = "data packet";
        qDebug() << ba.toHex();
        if (ba[3] == 0x1a && ba[4] == 0x02)
         return "getJsonStringFor_GetStimulatorOperaionType";

    }
    else if (ba[2] == 0x04)
    {
          return CNT_FIRMWARE_HEARTBEAT;
    }
   // return "";
}

engine.cpp:
void Engine::onSerialArrivedMsg(QByteArray msg)
{
ProtocolCommands pc;
qDebug() << "somthing has arrived : " << msg.toHex();
//if we here - this is new message from the firmware
//this function refer just to one message at a time

//first check if we are in the middle of flow:
if (mode)
{
     qDebug() << "mode = true";
     switch (curr_step_in_flow) {
     case 1:  //last command send to FW was [Set SinglePulse Parameters]
         if (pc.parseCommand(msg) == ProtocolCommands::CNT_FIRMWARE_ACK)    // compile eror
         {
            qDebug() << "ack recieved";
            curr_step_in_flow = 2;
         }
         else if (pc.parseCommand(msg) == CNT_FIRMWARE_HEARTBEAT ) // compile error
         {
             //heartbeat msg
             //send signal to the heartbeat thread
             emit fwHeartBeatArrived();
         }
         break;
     default:
         break;
     }

}
else
{
   if (pc.parseCommand(msg) == CNT_FIRMWARE_HEARTBEAT)  // compile eror
   {
       //heartbeat msg
       //send signal to the heartbeat thread
       emit fwHeartBeatArrived();
   }

}

}

Comment: What error do you have exactly? You also should return something instead of `// return "";` - your code is incorrect because the `control reaches end of non-void function`.
Answer:
I want to declare const variable in one class and use this variable in other classes.

Those strings aren't part of your ProtocolCommands class; they just happen to be declared in that compilatition unit.
If you want them as (static) members of the class, then declare them inside the declaration of the ProtocolCommands class in protocolcommands.h:
class ProtocolCommands {
public:
   static const QString CNT_FIRMWARE_ACK;
   // ...
};

And then initialize them in protocolcommands.cpp:
const QString ProtocolCommands::CNT_FIRMWARE_ACK = "ACK";

And then you can refer to it in any code that includes protocolcommands.h by the name ProtocolCommands::CNT_FIRMWARE_ACK.
Answer: I would do this with using an enum type instead of declaring my constants as strings. So, the ProtocolCommands class will look like:
class ProtocolCommands
{
public:
    enum Type {
        CNT_FIRMWARE_ACK,
        CNT_FIRMWARE_NAK,
        CNT_FIRMWARE_NYET,
        CNT_FIRMWARE_STALL,
        CNT_FIRMWARE_HEARTBEAT
    };

    ProtocolCommands::Type parseCommand(const QByteArray &ba);
    [..]
};

So, your ProtocolCommands::parseCommand() should return an integer value instead of a string. Thus your Engine::onSerialArrivedMsg(QByteArray msg) function will look like:
void Engine::onSerialArrivedMsg(QByteArray msg)
{
    ProtocolCommands pc;
    [..]
    switch (pc.parseCommand(msg)) {
    case ProtocolCommands::CNT_FIRMWARE_ACK:
    [..]
    case ProtocolCommands::CNT_FIRMWARE_NYET:
    [..]
    }
 }

The benefits of using this approach are:

It is faster, as you need to compare numbers and not strings,
The design is much simple and clearer as you don't need to deal with global or static variables.
Comment: Why are you insisting the author of the question to use enums? Maybe he really needs strings? However this makes sense, this does not answer the question on `How to declare const variable in one class and use in another.` Simply, your `enum`'s values are not a constant variables.
Comment: @VictorPolevoy, first of all, I don't insist anyone to follow my recommendations. Secondly - there is no engineering reasons to use strings instead of integers (at least author doesn't mention any), thirdly - enum values **are constants**.
Comment: Of course enum values are constants, but not a variables (or objects, for example) as author mentioned. Author wants to use variables. You may not see any reasons to use strings here, yes, but maybe the question is not related only to this code snippet you see in his question, maybe the author just need to know exactly `how to declare constant variables inside a class and use them in another?`.
Comment: @VictorPolevoy, he wants to know `how to declare constant variables inside a class and use them in another`? I have answered this question. I don't see a requirement to use only "string variables". In you comments you used word "maybe" 3 times. You could ask the OP and post your answer and prove that it is better than other's instead of guessing.
Comment: `I want to declare const variable in one class and use this variable in other classes. what is the best way to do that?` - this is a quote of what the author of the question wants to know, while you answer on `How to declare enum inside a class and use it?` or `What is the best way to have scalar constants inside a class?` or something like that. Can't you see the difference in these questions? I still don't agree with you when you say you did answer the question because your answer is more **recommendation-like** instead of solving the author's problem.
Comment: In which way my answer does not solve the problem? Besides it is much efficient than using global string constants. Thus I find you objections pointless.
Comment: It is much efficient, I agree, but author did not ask you for the efficiency, obviously, he asked about **how to implement it** but not a **best way of replacing it with something**. Just suppose the author have a `QRexExp` instead of `QString`, for example. Does your "solution" answers his question?
Answer: Define yours constants at ProtocolCommands.h file or include .cpp files as additional (bad-smells style). Then you can refer to them as constants like
pc.parseCommand(msg) == CNT_FIRMWARE_HEARTBEAT

This is because you include only header file, but header has no idea about constants you want to use.


Expressing ridge solutions as sum of vectors

Question: I'm having trouble following the derivation of the ridge solutions as a sum of vectors in formula 3.47 of The Elements of Statistical Learning on pg. 66. It shows the following:

$\mathbf{X}\hat{\beta}^{ridge} = \mathbf{X}(\mathbf{X}^T\mathbf{X} + \lambda\mathbf{I})^{-1}\mathbf{X}^T\mathbf{y}$
$\mathbf{X}\hat{\beta}^{ridge} = \mathbf{U}\mathbf{D}(\mathbf{D}^2 + \lambda\mathbf{I})^{-1}\mathbf{D}\mathbf{U}^T\mathbf{y}$
$\mathbf{X}\hat{\beta}^{ridge} = \sum{\mathbf{u_j}\frac{d_j^2}{d_j^2 + \lambda}\mathbf{u_j}^T\mathbf{y}}$
where $\mathbf{X} = \mathbf{UDV}^T$

I'm having trouble seeing how to get to line 2 after simplifying line 1 with
$\mathbf{X}\hat{\beta}^{ridge} = \mathbf{UDV}^T(\mathbf{VDU}^T\mathbf{UDV} + \lambda\mathbf{I})^{-1}\mathbf{VDU}^T\mathbf{y}$
and then:
$\mathbf{X}\hat{\beta}^{ridge} = \mathbf{UDV}^T(\mathbf{VD
^2V} + \lambda\mathbf{I})^{-1}\mathbf{VDU}^T\mathbf{y}$ because $\mathbf{U}^T \mathbf{U} = \mathbf{I}$
Also, is there a general theorem that helps yield line 3? I can't wrap my head around going from matrix products to vector sums.
It's been a decade since I've taken linear algebra, so if you have any good resources for dealing with this type of math, please let me know.
Answer: From,
$$X\hat\beta^{ridge} = UDV^T(VD^2V^T + \lambda I)^{-1} VDU^Ty$$
(note the transpose in one of the $V$ inside the inverse) you get
$$X\hat\beta^{ridge} = UDV^T[V(D^2 + \lambda I)V^T]^{-1} VDU^Ty$$
(notice that $V(\lambda I)V^T = \lambda I$ as $V$ is orthogonal). Taking the inverse in the second equation we have, since $V^{-1} = V^T$ by orthogonality, that:
$$X\hat\beta^{ridge} = UDV^TV(D^2 + \lambda I)^{-1}V^TVDU^Ty$$
whence, again using the orthogonality of $V$,  we get your second equation.
Your third equation follows immediately as both $D$ and $D^2 + \lambda I$ are diagonal.
Comment: A diagonal matrix $D$ times a general matrix $P$ is just the sum of the diagonal elements of $D$ times the row vectors of $P$. In turn, $PD$ would is the sum of the diagonal elements of $D$ times the column vectors of $P$. Just  write a simple example of low dimension, with matrices 3x3 for instance, and you will see at once how it goes.
Comment: Thanks! Sorry, I don't quite see how to manipulate the matrix multiplication into summations. If there's a good reference for turning matrix multiplication into summations, I'm happy to read it.


Panels Page Title CSS?

Question: I have created a Panels Page but can't find out how and where to put the class for the title?
Right now it uses the core Page Title CSS but I wan't every Panels Page Title to be unique.
Edit: I've noticed that this is the way for all my panels. I can't seem to be able to set a CSS Class to Pane Titles at all.
Answer: If you have set panel title like this

you can use the class "pane-title" to write the css.
Comment: Thanks! I noticed that I've already been doing some css styling using pane-title as class.
Answer: In Drupal 7 Panels, you can add unique class to your pages. Using page class you can add CSS to your Page Title
Comment: This method didn't do it for me. It changed the class for the Page Panel area but after this code
`My Example Panel Page` so I got no new class for the page where I wanted.

Panels Page Title CSS?


Cannot access the html DOM inside Vue3 app instance setup function

Question: I am using vue3 inside html file because what I was told to do... and this is happening

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

the result is like this.
outside

inside null

Could you please explain this to me? I was trying to look up the documentation but didn't know how to find with the proper keyword. maybe createApp creates separate context from the parent one so I cannot refer it inside it?
+) I tested vue3 part and it works fine. I can refer the data the returned by setup funciton inside html part.
Comment: yes. you were right. maybe some timing issue. so I moved it inside the onMounted hook and it works fine.
Comment: It works. I follwed the instruction from the official documents. https://vuejs.org/guide/quick-start.html#using-vue-from-cdn
Comment: ok. I will upload full code snippet example.
Comment: and you were right. I skipped the const {createApp} = Vue part in my example.
Comment: At a guess, I'd say you're hitting something of a timing issue where Vue is processing the template (your `` element) and has temporarily removed the current DOM elements. It might help to know what you're trying to do exactly because it doesn't look like the _Vue way_
Answer: move it inside onMounted hook.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

Answer: Setup occurs before the vue components create, you can refer to the code below.

setup(){
  Vue.onMounted(function() {
    const x = document.getElementById('here')
    console.log('inside', x)
   })
}


how can i populate array elements from an external file

Question: var a1=[[]];

jQuery.get('file.txt', function(data) {
  a1=data;
  console.log(a1);
});

//file.txt contains data as follows
[[0,'IN',2],[1,'142',3]]
now my question is   a1=data in above code is not an array like var a=[[0,'IN,2],[2,'142'3]];how can i populate array elements from a text file???
Comment: Or just use `$.getJSON`
Comment: it's not a json file simply a text file
Comment: If it's not JSON, you'll need to write your own parser..  To help, we'd have to know the exact format of the data.
Comment: If you can trust the source of the data, you can use `eval` to parse it as a Javascript array.  This is often considered a security risk, since it can potentially run any code within the string.  Writing a parser might be a better way if the format is simple.
Answer: Use JSON.parse. You don't need any external library to parse JSON.

The JSON.parse() method parses a string as JSON, optionally
  transforming the value produced by parsing.

jQuery.get('file.txt', function(data) {
  a1=JSON.parse(data);
  console.log(a1);
});

Comment: your text file has unescaped `single quote` characters
Comment: It should look like `[[0,\"IN\",2],[2,\"142\",3]]`
Comment: quotes are part of my requirement to treat it as string literal .i want to create an array like this var a=[[1,'IN',2],[2,'GB',3]];
Comment: with this statement a=data;
Comment: your data in file doesnt have a valid JSON. You must have it escaped properly. or there is a workaround if cannot edit the file, replace all single quotes with `\"`
Comment: With this code: `a=JSON.parse(data.replace(/'/g,'\"'))`


Best practice for accessing Sitecore Items via code

Question: Quite new to Sitecore and would like to understand the best way to access sitecore items. I've seen couple of ways:

Create Page ID field and get all items for given template and folder. Then do linq query on page ID.
Store all Page ID (Sitecore Item ID) on Constants file. Use this to query Sitecore using GetItem(itemID) API.

Could someone please suggest what's the best practice. Either way, I can see that there will be huge Constants file containing either custom Page ID or Sitecore Item ID.
My worry is do we really need to manage this Constants file or is there an elegant way to query CMS contents for given Page.
Thanks.
Answer: Approach 1 seems a bit odd. I don't really see why you would get a collection of items first when you already have the ID, but maybe I've misunderstood what you're saying.
I think a combination of 2 things you mention is best.
Constants classes are good for "landmark" items that will always definitely be there, so its fine for the GUID to be in code.
Some of these landmark items can be "configuraton items" that have fields containing the IDs of other items (These fields might have names like "Templates allowed in search"). This approach allows some flexibility for change by Sitecore users as the site evolves.
If you're concerned about the management of a constants file, I have to wonder how many items you need to access by ID. Sitecore items have properties like Parent and Children. You can also find items by template type etc.
This approach works well for me. I certainly don't think there is a more elegant way of getting strongly typed references to Sitecore items.
Comment: Why not CustomItemGenerator? That's a terrific way to get references to Sitecore items. And you can use the settings for the Home/Start Item in the web.config for getting the top-most item. All you need is a solid site structure that you enforce throughout development.
Comment: Didn't know about this one. Look's interesting. https://marketplace.sitecore.net/en/Modules/Custom_Item_Generator.aspx
Comment: Yeah - I linked to it in my answer too
Answer: Personally, I prefer not to use constants files. What happens if your client or one of your developers deletes one of those items and creates a new one? One of the fundamental principles of Sitecore is that items can be added and removed by users who are not necessarily "technical" personnel.
Sitecore provides "Insert Options" so that you can specify what types of items can be added to each folder, and also grants the ability to protect certain items from deletion, via Roles and User Permissions. What does this mean conceptually? It means that Sitecore is set up such that the system architects/developers can create a structure that is not to be violated, while the content editors can add or remove content within that structure. In other words, Sitecore is designed to provide a framework in which the items can change but the location of each type of item is pre-determined.
As such, I suggest that you use the Custom Item Generator module available in the Sitecore Marketplace (free). CIG generates C# class representations (models) of your templates, and makes all fields into properties (I don't want to get too off-topic, but this is an awesome feature of CIG, especially when working with newer developers). You can add your own methods to your CIG classes for getting children of a particular type. For example, on a site in which the Profile Page is a direct child of the Homepage the following method could be added to the CIG HomepageItem.instance.cs file's HomepageItem partial class:
...
public partial class HomepageItem
{
    public ProfilePageItem GetProfilePage()
    {
        //note that .IsOfType(...) is pseudo-code and not a real method, but I do
        //   suggest that you define an extension for it
        return InnerItem.Children.FirstOrDefault(i => i.IsOfType(ProfilePageItem.TemplateId));
    }
}

Be sure that you are assigning Insert Options to restrict the types of items that can be added as children to each item you make (add them on the Standard Values and not on the individual content items). I also suggest that you make a separate Template that inherits from Common/Folder for every folder that you use in the content tree. This way you can use CIG for your entire structure, via:
...in your Globals Item's CIG class...
public partial class GlobalsItem
{
    public SlidesFolderItem GetSlidesFolder()
    {
        return InnerItem.Children.FirstOrDefault(i => i.IsOfType(SlidesFolderItem.TemplateId));
    }
}

...in your Slides Folder Item's CIG class...
public partial class SlidesFolderItem
{
    public IEnumerable<SlideItem> GetSlides()
    {
        return InnerItem.Children.Where(i => i.IsOfType(SlideItem.TemplateId));
    }
}

and then you can get your Slide items via:
...
var slidesFolder = globals.GetSlidesFolder();
var slides = slidesFolder != null ? slidesFolder.GetSlides() : null;

Remember that CIG, Insert Options, and templates for each type of folder will enable you to create an iron-clad structure for your site that will not break if content editors make unexpected changes like replacing items.

Let me know if you have any questions on this. Good luck, and Happy Coding! :)
Comment: Code generation tools are useful if your developers are the same people who are responsible for IA and object definition. In my case they aren't, and attempts to use such tools have left us in a mess. That said, I appreciate my circumstances might not be the norm.


Wait until file exists before continuing with program

Question: I have a Delphi application plugin that shows a modal form. In the separate form's code, it calls another exe file to process some files, then closes. The second part of the plugin manipulates the created files from the exe.
My problem is, the program is continuing before the external files are actually created. Is there a way to pause my Delphi plugin and loop or wait until the FileExists returns true before continuing?
Pseudocode:
Launch form (ShowModal)
Form runs exe, manipulates external files
Close Form
Form released
if ExternalFiles exist, do stuff.

Because the external files are being manipulated outside of my plugin, I cannot tell when they are finished and have been created.
Answer: Presumably the files exist by the time the launched exe exits.  You can use CreateProcess() to launch the exe, then use WaitForSingleObject() or related function to detect when that exe exits.  Then you can use the files it created as needed.
Comment: Excellent, a solution that avoids polling and Sleep!
Comment: @ikathegreat - how are you launching the executable? ShellExecute? CreateProcess?
Comment: If you use `ShellExecuteEx()`, make sure the `SEE_MASK_NOCLOSEPROCESS` flag is specified so you get back a process `HANDLE` to wait on. `CreateProcess()` always returns such a `HANDLE`.
Answer: use the function "filexists" in a timer that checks every second after you start.
an other way is to use a
while not fileexists('c:\temp\somfile.txt') do begin
  sleep(1000);
end;

But I don't really like it because it locks up your application.


Find the following probability and PDF

Question: An electric current I that fluctuates may be considered a random variable evenly distributed in the interval (9,11) amps. If the current goes through a resistance of 2 ohm, the power is $P=2I^2$
Which is the probability of the current to belong to the interval (9,10)? This is the first question.
I don't know how to find it although i want to say 50 porcent for some reason, maybe because it says that is evenly distributed.
Explain why P may be considered a random variable.
This is because I is a random variable.
Find an expression for the PDF of P.
This i don't have any idea of how to do it.
Any hints are welcome. Thanks
Comment: If you don't have any idea what to do, start by writing out the information you are given in mathematical terms. E.g. what does it mean for $I$ to be "evenly distributed in the interval (9,11) amps"? You want a PDF, so blindly write down whatever PDFs you are given. Sometimes, this is enough to figure out the solution, so its a good idea to try this first.
Answer: In general if $9\le a<b\le 11$, the probability that $I$ belongs to $(a,b)$ is $\frac{b-a}{11-9}$. This is what "evenly distributed in $(9,11)$" means. (Some people use the word "uniformly" in place of "evenly".)
For the PDF of $P$, here are two different approaches.

Write down the PDF of $I$. Then use the change of variables formula with the transformation $\phi(x) = 2x^2$ to obtain the PDF of $P$.
Alternatively, find the CDF of $P$ first, and then take the derivative to obtain the PDF.

Find the following probability and PDF


Como tiro esse Scroll da tela e deixo responsiva?

Question: Pessoal como faço para tirar esse Scroll que aparece quando abro essa página em telas menores?
Gostaria de deixá-la responsiva tbem e com o card de login no meio da página com margin top e bottom mais sem criar scroll(barra de rolagem), se alguém poder me ajudar agradeço.

                @using (Html.BeginForm("Login", "Acesso", FormMethod.Post))
                {

                            ANÁLISE CRIMINAL

                        @if (!string.IsNullOrWhiteSpace(ViewBag.errorMessage))
                        {

@ViewBag.errorMessage

                        }

                            Usuário

                                    perm_identity

                                <input type="text" class="form-control" id="Usuario" name="Usuario">

                            Senha

                                    lock_outline

                                <input type="password" class="form-control" id="Senha" name="Senha">

                        <button type="submit" class="btn pmd-ripple-effect btn-primary btn-block">Login</button>

                }

            © @DateTime.Now.Year - Secretaria de Estado de Segurança Pública - SSP/SMT - Subsecretaria de Modernização Tecnológica.

            Versão: @ViewBag.versao

Comment: Coloca overrflow:hidden no body. Ou diminui o tamanho da imagem
Comment: Você pode também definir o tamanho datela de acordo com o viewport.
Answer: Adicione isso aos seus styles :
.container {
    max-height:100% !important;
    overflow:hidden;
}


Does $\mathbb{Cov} \left(f(X),Y\right) = 0 \; \forall \; f(.)$ imply independence of $X$ and $Y$?

Question: Does $\mathbb{Cov} \left(f(X),Y\right) = 0 \; \forall \; f(.)$ imply independence of $X$ and $Y$?
I am only familiar with the following definition of independence between $X$ and $Y$.
$$
f_{x,y}(x,y) = f_x(x)f_y(y)
$$
Comment: You need $\mathbb{Cov} \left(f(X),g(Y)\right) = 0  ~\text{for all (measurable)} ~f(\cdot), g(\cdot)$, not just $\mathbb{Cov} \left(f(X),Y\right) = 0 \; \forall \; f(\cdot)$
Answer: Let's begin with the intuition.  The slope of the ordinary least squares regression of $Y$ against $h(X)$, for any function $h$, is proportional to the covariance of $h(X)$ and $Y$.  The assumption is that all regressions are all zero (not just the linear ones).  If you imagine $(X,Y)$ represented by a point cloud (really, a probability density cloud), then no matter how you slice it vertically and reorder the slices (which carries out the mapping $h$), the regression remains zero.  This implies the conditional expectations of $Y$ (which are the regression function) are all constant.  We could screw around with the conditional distributions while keeping the expectations constant, thereby ruining any chance of independence.  We therefore should expect that the conclusion does not always hold.
There are simple counterexamples.  Consider a sample space of nine abstract elements $$\Omega = \{\omega_{i,j}\mid -1 \le i,j,\le 1\}$$ and a discrete measure with probability determined by
$$\mathbb{P}(\omega_{0,0})=0;\ \mathbb{P}(\omega_{0,j})=1/5\,(j=\pm 1);\ \mathbb{P}(\omega_{i,j}=1/10)\text{ otherwise.}$$
Define $$X(\omega_{i,j})=j,\ Y(\omega_{i,j})=i.$$
We could display these probabilities as an array
$$\pmatrix{1&2&1\\1&0&1\\1&2&1}$$
(with all entries multiplied by $1/10$) indexed in both directions by the values $-1,0,1$.
The marginal probabilities are $$f_X(-1)=f_X(1)=3/10;\, f_X(0)=4/10$$ and $$f_Y(-1)=f_Y(1)=4/10;\, f_Y(0)=2/10,$$ as computed by the column sums and row sums of the array, respectively.  Since $$f_X(0)f_Y(0)=(4/10)(2/10)\ne 0=\mathbb{P}(\omega_{0,0})=f_{XY}(0,0),$$ these variables are not independent.
This was constructed to make the conditional distribution of $Y$ when $X=0$ different from the other conditional distributions for $X=\pm 1$.  You can see this by comparing the middle column of the matrix to the other columns.  The symmetry in the $Y$ coordinates and in all the conditional probabilities immediately shows all conditional expectations are zero, whence all covariances are zero, no matter how the associated values of $X$ might be reassigned to the columns.
For those who might remain unconvinced, the counterexample may be demonstrated through direct computation--there are only $27$ functions that have to be considered and for each of them the covariance is zero.


If I assign a value to a variable inside a method, does it persist beyond the scope of that method?

Question: Sorry if this is a repeat, i've tried looking for the answer to my question but could not come across the answer I'm after.
I'm very new at Java (literally started yesterday) and I am trying to understand why if I declare a variable in my class and then assign a value to it in a void method, the value associated with that variable persists beyond the method's scope. My (very) limited understanding of methods is that they have their own scope and I thought the only way to access any variable changes that had been made within a method was to return them at the end of the method. Is this not the case?
Comment: @Mr.Arjun I thought thats what StackExchange was for? To get helpful and kind answers on a question. Not to get referred to more technical reading?
Comment: the local variable (inside the method) doesn't exist (anymore) after execution of the method, but that doesn't go for the class/instance variable.
Comment: Kindly use reference books and bit practice will help
Comment: @vcromy It's not being rude or kind to anybody. But it's just saving someone's productive time on something trivial. Kindly have a look at StackExchange's help section. https://stackoverflow.com/help/how-to-ask
Answer: The answer to this is a bit more complex.
First start to distinguish a method from a function.
A method operates on an object instantiated by calling the constructor of the class (e.g. MyClass obj = new MyClass();). From this point, your object has a state expressed by it's member variables (all variables that are not declared static in your class).
Methods (as part of the object) may change this state (unless the corresponding variables are declared final).
To be able to to so, a method inherits the scope of the class, but the variables are bound to the instance of the object, on which the method is called.
So for instance:
public class MyClass {
    private int a = 0;
    public void aplusplus() {a++;}
}

MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.aplusplus();  // the a of obj1 is now 1
obj2.aplusplus();  // the a of obj2 is now 1
obj1.aplusplus();  // the a of obj1 is now 2

But beware! There is also a concept called hiding.
If you declare a local variable within the body of a method, it hides the class member variable. Accessing the variable by name results in accessing the local variable, instead of the member variable. This is particuallry interesting when implementing setter methods for private members, where usually the argument of the method (which is a local variable) is named exactly as the member variable. To still access the member variable, you can use this.variablename. For instance:
public class MyClass {
    private int a = 0;
    public void aplusplus() {a++;}
    public void setA(int a) {this.a = a;}
}

Answer: You say in your question that you have declared a variable in your class. This means that any value the variable gets set to, (during method invocations), will persist across method invocations. The variable is part of this object, and as such, is referred to as an instance variable.
If you declare variables inside method definitions, they are inside the scope of the method. They are part of this.yourMethod(). These variables are said to be local to the method. You can only use these variables inside the method. The this object does not know they exist.
Answer: Each method in a class will inherit any attribute (variable) or any method that directly belongs to that class. Say
public class Bicycle {

    public int gear;
    public int speed;

    // the Bicycle class has
    // two  methods

    public void setGear(int newValue) {
        gear = newValue;
    }

    public void speedUp(int increment) {
        speed += increment;
    }
}

Let's get the setGear method
public void setGear(int newValue) {
    gear = newValue;
}

As you can see, I can access the 'gear' attribute because it belongs to the Bicycle class. The parameter '(int newValue)' belongs to this method exclusively, meaning I can only access this variable inside this method, like this:
public void setGear(int newValue) {
    newValue = gear;
    //this wouldn't make much sense logic wise, but it is
    //valid code since I can use newValue only inside the setGear method

    speedUp(10);
    //the method 'speedUp' belongs to the bicycle class, so I can use
    //it inside another method belonging to the same class
}

Alternatively, I can use the this keyword to say that I am referring class attributes, like this:
public void setGear(int gear) {
    this.gear = gear;
    //I am telling the method that the class attribute 'gear' will
    //receive my parameter value 'gear'
    //this is useful when my parameter variable name has the same
    //name as my class attribute
}

Edit: forgot to give credit to the oficial oracle docs https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html
Comment: All answers here we're great but the depth and simplicity of this one did it for me. Thanks! :)