Logical Operators, || or OR?

Question: I remember reading a while back in regards to logical operators that in the case of OR, using || was better than or (or vice versa).
I just had to use this in my project when it came back to me, but I can't remember which operator was recommended or if it was even true.
Which is better and why?
Answer: There is no "better" but the more common one is ||. They have different precedence and || would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;

Comment: and `$e = true || $x = 'foo'` will not define `$x` because of short-circuiting, not because of higher precedence.
Comment: It is also worth noting that these *always* return a boolean value, unlike many other languages where they return the last value checked. So in PHP (27 || 0) returns *true*, not *27*.
Comment: @TextGeek, actually, you are right that `or` returns boolean as well. Just its precedence is so low that it sometimes _looks_ like it does something else. :) `print 27 or 0` would print `27` because `or` happens _after_ `print 27`. BTW, `echo` is not fooled – `echo 27 or 0` would output `1`.
Comment: @TextGeek, "these"? `27 or 0` returns `27` for me.
Comment: @Jānis Elmeris -- you are correct, I should have referred only to the "||" case.
Comment: @nurchi -- I started checking various languages, then found [https://en.wikipedia.org/wiki/Short-circuit_evaluation] has a nice list. The languages listed as returning "last value" are Javascript, Julia, Lasso, Lisp, Lua, Scheme, Perl, Ruby, POSIX shell,
Python. shell languages are a little weird, but I tried "return 5 || 10" from a zsh function and got 5.
Comment: @TextGeek, out of curiosity, can you name a few examples of such languages? In all the languages that I know (27 | 0) performs a bitwise-or operation and the result will be 27, but in C/C++, for example, (27 || 0) will return 1 (or true), C# (or Java) will not allow such operation because the || operator can only be applied to boolean operands and neither 27 nor 0 are such.
Answer: They are used for different purposes and in fact have different operator precedences.  The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.
For example, the following is a Boolean condition:
if ($foo == $bar && $baz != $quxx) {

This differs from control flow:
doSomething() or die();

Comment: `doSomething()` is evaluated as a boolean. If it returns a value PHP considers truthy (`true`, a non-empty string, etc.), it will not call `die()`.
Comment: `die()` function will be called if `doSomething()` will return `false` or `null`? What if `doSomething()` returns `true` or nothing?
Answer: The difference between respectively || and OR and && and AND is operator precedence :
$bool = FALSE || TRUE;

interpreted as ($bool = (FALSE || TRUE))
value of $bool is TRUE

$bool = FALSE OR TRUE;

interpreted as (($bool = FALSE) OR TRUE)
value of $bool is FALSE

$bool = TRUE && FALSE;

interpreted as ($bool = (TRUE && FALSE))
value of $bool is FALSE

$bool = TRUE AND FALSE;

interpreted as (($bool = TRUE) AND FALSE)
value of $bool is TRUE
Comment: I tested in PHP-7 `$var = false || 'pin';` and the result (`var_dump($var);`) is: **bool(true)**
Comment: @csr-nontol that's because 'pin' evaluates to true. the result of operators || and OR is always boolean, and their operands are converted to boolean before evaluation.
Answer: Source: http://wallstreetdeveloper.com/php-logical-operators/
Here is sample code for working with logical operators:

    <title>Logical</title>

    <?php
        $a = 10;
        $b = 20;
        if ($a>$b)
        {
            echo " A is Greater";
        }
        elseif ($a<$b)
        {
            echo " A is lesser";
        }
        else
        {
             echo "A and B are equal";
        }
    ?>
    <?php
        $c = 30;
        $d = 40;
        //if (($a<$c) AND ($b<$d))
        if (($a<$c) && ($b<$d))
        {
            echo "A and B are larger";
        }
        if (isset($d))
            $d = 100;
        echo $d;
        unset($d);
    ?>
    <?php
        $var1 = 2;
        switch($var1)
        {
            case 1:  echo "var1 is 1";
                     break;
            case 2:  echo "var1 is 2";
                     break;
            case 3:  echo "var1 is 3";
                     break;
            default: echo "var1 is unknown";
        }
    ?>

Comment: The link is broken.
Answer: I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...
Let's say the code looks like this:
$positions = $this->positions() || [];

You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.
If you need to get value of $this->positions() or empty array, you have to use:
$positions = $this->positions() or [];

EDIT:
The above example doesn't work as intended but the truth is that || and or is not the same... Try this:
<?php

function returnEmpty()
{
  //return "string";
  //return [1];
  return null;
}

$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];

var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";

This is the result:
bool(false)
NULL
array(0) {
}

So, actually the third option ?: is the correct solution when you want to set returned value or empty array.
$positions = $this->positions() ?: [];

Tested with PHP 7.2.1
Comment: `$positions = $this->positions() ?? [];` is likely what you want.
Comment: it's incorrect answer, the second example works exactly as first one
Comment: @WayFarer well, it's not correct (there is an issue) but you're wrong too (|| and OR is not the same) - see my edit
Comment: right, operators || and 'or' have different priority, so, your second example works as: (($second = returnEmpty()) or []); So, the answer to original question would be || is better, always use it, until you really understand why do you want to use 'or'
Answer: I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.
EDIT: As others have pointed out there is indeed a difference between the two.
Answer: There is nothing bad or better, It just depends on the precedence of operators. Since || has higher precedence than or, so || is mostly used.
Answer: Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B in Pascal).
Explanations:
function A(){
    ...Do something..
    return true;
}

function B(){
    ...Do something..
    return true;
}

if ( A() OR B() ) { .....

In this example the function B() will never be executed. Since the function A() returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.
However with ( A() || B() ), the second part is always evaluated regardless of the value of the first.
For optimized programming, you should always use OR which is faster (except for the case when the first part returns false and second part actually needs to be evaluated).
Comment: This is not 'The Best Answer !!'. Please scroll back up and take the most up voted answer for a good explanation. With the `||`, `B` will not be called. Both operators do exactly the same, except that the precedence is differs.
Comment: "you should always use OR which is faster" Hmm, i wonder if this is true... so let's check that: https://3v4l.org/5QSAA/vld#tabs https://3v4l.org/PdjJP/vld#tabs The number of opcodes is the same. So it doesn't matter performance wise.

Logical Operators, || or OR?


How should I attach a chin-up bar to floor joists?

Question: I want to mount a chin up bar to engineered I-beam floor joists.  Am I safe to mount it directly up into it with lag bolts?  If the spacing isn't correct and I span some joists with 2x4s, should I run it in between the joists parallel to the bottom of them (with screws going through the 1x2 bottom of the joist)?  Or should I sit the 2x4s on top of the bottom I part and screw through the vertical joist piece?
The max load is around 200 lbs.
Here's a quick diagram based on @bib's response.  On the left is how I believe he is telling me to go, on the right was my plan based on his response.  The bar itself mounts up.  The I is the joist(s), red is 2x4, blue is screws/bolts and green is the chin-up bar...

Photograph of the completed installation:
Comment: Could you send a pic of the final setup? I have the same issue with 1 by 2 joists instead of 2 by 8s in the basement. Thank you
Comment: **Great diagram and photograph.**  Also, this matches the [recommendation of one of the manufacturers I've seen](https://web.archive.org/web/20190130063345/https://www.weyerhaeuser.com/blog/supporting-exercise-equipment-with-tji-joists/) I plan to use this setup to suspend a dehumidifier.
Answer: If you use several lag bolt of sufficient size, you probably would be OK, but that is not a preferred method.
The load will be concentrated on the threads of the lag bold and the wooden fibers holding the threads. Bolts and screws are much stronger when the load pulls perpendicular to the axis of the fastener instead of parallel to it.  This then relies on the shear strength of the fastener. Basically to pull such bolt(s) out, you need enough load to cut the bolt(s) in half, which is much higher than the load needed to rip through the wood holding the threads.
If you use a 2x4 spanning mount, the same rules apply.  Attaching them to the bottom of the joist is again depending on the strength of the thread in wood, not the strength of the bolt itself. Putting them over the bottom plate of the joist and lag bolting them sideways uses the shear strength and is a much stronger setup.
A 2x4 laid flat (with its 3 1/2" side running horizontal) is not its stronger configuration. It is much stronger and less prone to flex if you set it on edge (with its 1 1/2" edge horizontal). But it is hard to drill a decent size bolt hole through the 1 1/2" edge, and it weakens the piece. You probably need to lay it flat.  If the span is wide and if your attachment point are not close to the joist face, consider stacking two pieces on their flat sides.
If you use that approach, you shouldn't just screw lag bolts up into the 2x4s.  Instead, drill through them completely and use a conventional bolt and nut with oversize washers on the tops of the 2x4s.  This spreads the load over a much larger area (several inches instead of fractions of an inch).
Comment: Thanks for the detailed response.  Please see diagram above if I understand you correctly.
Comment: @Mark I actually preferred your 2x4 spanning approach and the diagram on the right is the one I would recommend. Just double up the 2x4 and drill through with a bolt, nut and washer, no lag bolts, except horizontally through the joists.


Convergence in probability and almost-sure convergence

Question: I have the following sequence of independent r.v.
$$\mathbb{P}(\{X=n\})=\big(\frac{1}{n^2}\big), \mathbb{P}(\{X=0\})=\big(1-\frac{1}{n^2}\big)$$ and also, $S_n = \sum_{i=1}^{n} X_i$.
I am denoting with $H_n = \sum_{i=1}^n \frac{1}{i}$ and $K_n = \sum_{i=1}^n \frac{1}{i^2}.$
I am trying to find if the sequence $\frac{S_n}{n}$ converges to a constant $c_1$ in probability and whether $\frac{S_n}{nH_n}$ converges to a constant $c_2$ but almost surely. Since the random variables are independent, their Covariances are $0$ and I know that, denoting with $\mu =\lim_{n\to\infty} \frac{E(S_n)}{n}, \frac{S_n}{n} \to \mu$ both in probability and almost surely. Since $\mu = \frac{H_n}{n}$ and I know that $\lim_{n\to\infty} \frac{H_n}{\log n} = 1$ I can say that $\mu = 0$.
So, my guess is that $c_1=0$ and here is my proof:
\begin{align}
P(|S_n|>n\epsilon) \leq \frac{E(S_n^2)}{n^2\epsilon^2} &= \frac{Var(S_n)-E(S_n)^2}{n^2\epsilon^2} \\ &= \frac{n-K_n+H^2_n}{n^2\epsilon^2} \to_{n\to\infty} 0
\end{align}
Now, since if a rv converges in probability to two different limits these are equal almost-surely I say that $c_1=0$ a.s.(although it asks for a constant, so I am not sure if stating this is correct).
For the second part, I also think that $c_2$ is $0$ but I do not know how to justify it theoretically and I showed that:
\begin{align}
P(|S_n|>nH_n\epsilon) \leq \frac{E(S_n^2)}{n^2\epsilon^2} &= \frac{Var(S_n)-E(S_n)^2}{n^2H_n^2\epsilon^2} \\ &= \frac{n-K_n+H^2_n}{n^2H_n^2\epsilon^2}
\end{align}
And $\sum_{n\geq 1}P(|S_n|>nH_n\epsilon) \leq \sum_{n\geq 1}( \frac{1}{nH_n^2\epsilon^2} - \frac{K_n}{n^2H_n^2\epsilon^2} + \frac{1}{n^2H_n^2\epsilon^2})$
The second and the third term are $O(1/n^2)$ and their summation is $<\infty$, the firt term should be upper bounded by $\sum_{n\geq 1} \frac{1}{n\log^2n}< \infty$ and by the Borel-Cantelli lemma $c_2=0$. Is this argument correct?
Also, can I justify $c_2=0$ this way?
\begin{align}
P(|S_n-n c_2 H_n|>n H_n\epsilon) &\leq \frac{E(S_n^2)-n c_2 H_n E(S_n)+n^2c_2^2H_n^2}{n^2H^2_n\epsilon^2}\end{align}
And $\sum_{n\geq 1}\frac{E(S_n^2)}{n^2H^2_n\epsilon^2}<\infty$
but the other two terms are $-\frac{c_2}{n\epsilon^2},\frac{c_2^2}{\epsilon}$ and the only way for it to be $<\infty$ is if $c_2=0$ or $c_2$ grows at least as $1/n$ (and thus, not a constant)?
Answer: You are making things too complicated. Note that $\sum P\{X_n \neq 0\} =\sum \frac 1 {n^{2}} < \infty $. By Borel Cantelli Lemma $X_n=0$ for all $n$ sufficiently large, with probability 1. This implies that $X_n \to 0$ almost surely which implies $\frac {S_n} n$ and $\frac {S_n} {nH_n}$ both tend to 0 almost surely. Even independence of $X_n$'s is not required for this!.
Comment: I understand your reasoning and of course is simpler, but the exercise had steps that I tried to follow...beside the complexity, do you see something wrong in my justifications?


Better way to change string "abc..z" to "bcd..a"?

Question: I created this code that looks at a string token and formats it so that every character is moved along by one. The characters are all lowercase and from a to z.
So if my input is
abcz
Output is
bcda
Right now I added all the alphabets to an arraylist, and the code determines the index of each character and adds one to it. If it finds z, it prints a so that index of the arraylist is not out of range.
List<String> letters = new ArrayList<String>();
        String alp = "abcdefghijklmnopqrstuvwxyz";
        for (int i = 0; i<26; i++)
        {
            letters.add(Character.toString(alp.charAt(i)));
        }

        String token = sc.next();
        for (int i = 0; i<token.length(); i++)
        {
            if (letters.get(letters.indexOf(Character.toString(token.charAt(i)))).equals("z"))
            {
                System.out.print("a");
            }
            else
            {
            System.out.print(letters.get(letters.indexOf(Character.toString(token.charAt(i)))+1));
            }
        }

Comment: So what is your question? What kind of improvement are you looking for: less code, better performance, better coding style? Did you experience any problems with your implementation? What is the context, what do you need this function for?
Comment: http://stackoverflow.com/questions/4698290/promoting-letters-in-a-string-to-the-next-letter-in-java
Answer: A simple loop with a bit of modular arithmetic will do, why bother with so many objects?
for(int i = 0; i < token.length(); ++i) {
    System.out.print(('a' + (token.charAt(i) + 1 - 'a')%('z' - 'a' + 1)));
}

We increase the offset from 'a' by one, and take the remainder modulo 26 to get an offset in the range from 0 to 25.
Comment: Troo dat, but 26 is shorter.
Comment: But @vladr's solution allows more flexibility, for instance if he wants to advance it to a rot13 or similar more "advanced" encryption.
Answer: Apache commons-lang library has the StringUtils.replaceChars() utility method that can do this for you:
StringUtils.replaceChars(input, "abcdefghijklmnopqrstuvwxyz", "bcdefghijklmnopqrstuvwxyza");

Although with such large parameters, it looks a little on the ugly side.
Nevertheless, it is just one line, and IMHO the best kind of code is someone else's code (meaning, if there's a library out there that does it, be inclined to use it).


lennox furnace not working pilot light on but burner doesn't start

Question: lennox furnace, model # G20Q2E-75-C1, serial #6392H32332, pilot light lights, blower motor turns on, burner doesn't burn
Comment: Is the thermostat on?  Is the thermostat getting power (or the batteries good)?  Is the thermostat calling for heat?
Comment: Can you hear the main gas valve open (probably a click, clank, or ping) a bit after the pilot has been lit? Can you hear gas flowing?
Comment: Does this model have an electronic pilot, or do you manually light the pilot (always burning)?
Answer: Have you followed the Troubleshooting flow chart from the user manual?

Click for larger view
You'll probably want to start with this bit...

Specifically, if the unit hasn't started in a bit (over the summer), I'd try cleaning the area of the burner nearest the pilot.
Answer: Sounds like a limit switch is preventing burner ignition.
Look for code flash on led light on control board.
Comment: What makes you suspect a limit switch? How would you determine if a limit switch was not working properly?
Answer: Jump it, if it allows you, and check for continuity and check for 24V.


What does the "dpkg --configure -a" command do?

Question: Why when an installation fails, should I run dpkg --configure -a, to fix it, also, why can't sudo apt do this?
Answer: apt, aptitude, synaptic etc. are frontends to the same tool: dpkg. dpkg is very low-level, and apt isn't particularly smart. So if package configuration was interrupted, apt tells you to descend to the lower level to fix it. Note that apt may not be aware of the packages which caused the problem (they may be manually installed local packages, and they may be a hundred packages and not one) and keeping it simple, it tells you to use the tool that is aware of them. Mitch has already posted what this command does.
Answer: From the manpage:
--configure package...|-a|--pending
          Reconfigure an unpacked package. If -a  or  --pending  is  given
          instead  of  package, all unpacked but unconfigured packages are
          configured.

          Configuring consists of the following steps:

          1. Unpack the conffiles, and at the same time back  up  the  old
          conffiles, so that they can be restored if something goes wrong.

          2. Run postinst script, if provided by the package.


SQL to equivalent pandas - Merge on columns where column is null

Question: I opened up this new question because I'm not sure the user's request and wording matched each other: pandas left join where right is null on multiple columns
What is the equivalent pandas code to this SQL? Contextually we're finding entries from a column in table_y that aren't in table_x with respect to several columns.
SELECT
   table_x.column,
   table_x.column2,
   table_x.column3,
   table_y.column,
   table_y.column2,
   table_y.column3,
FROM table_x
LEFT JOIN table_y
   ON table_x.column = table_y.column
   ON table_x.column2 = table_y.column2
WHERE
   table_y.column2 is NULL

Is this it?
columns_join = ['column', 'column2']
data_y = data_y.set_index(columns_join)
data_x = data_x.set_index(columns_join)

data_diff = pandas.concat([data_x, data_y]).drop_duplicates(keep=False) # any row not in both

# Select the diff representative from each dataset - in case datasets are too large
x1 = data_x[data_x.index.isin(data_diff.index)]
x2 = data_y[data_y.index.isin(data_diff.index)]

# Perform an outer join with the joined indices from each set,
# then remove the entries only contributed from table_x
data_compare = x1.merge(x2, how = 'outer', indicator=True, left_index=True, right_index=True)

data_compare_final = (
    data_compare
    .query('_merge == left_join')
    .drop('_merge', axis=1)
)

I don't think that's equivalent because we only removed entries from table_x that aren't in the join based on multiple columns. I think we have to continue and compare the column against table_y.
data_compare = data_compare.reset_index().set_index('column2')
data_y = data_y.reset_index().set_index('column2')
mask_column2 = data_y.index.isin(data_compare.index)
result = data_y[~mask_column2]

Comment: Kindly provide sample dataframe with expected output
Comment: There are some weird edge cases with this. I'll be able to answer my own question later this afternoon.
Answer: Without test data it is a bit difficult to be sure that this helps but you can try:
# Only if columns to join on in the right dataframe have the same name as columns in left
table_y[['col_join_1', 'col_join_2']] = table_y[['column', 'column2']] # Else this is not needed

# Merge left (LEFT JOIN)
table_merged = table_x.merge(
    table_y,
    how='left',
    left_on=['column', 'column2'],
    right_on=['col_join_1', 'col_join_2'],
    suffixes=['_x', '_y']
)

# Filter dataframe
table_merged = table_merged.loc[
    table_merged.column2_y.isna(),
    ['column_x', 'column2_x', 'column3_x', 'column_y', 'column2_y', 'column3_y']
]

Answer: I found an equivalent that amounts to setting the index to the join column(s), union'ing the tables, dropping the duplicates, and performing a cross join between the contributions to the union. From there, one can select
left_only for this equivalent SQL
SELECT
   table_x.*,
   table_y.*
FROM table_x
LEFT JOIN table_y
   ON table_x.column = table_y.column
   ON table_x.column2 = table_y.column2
WHERE
   table_y.column2 is NULL

right_only for this equivalent SQL
SELECT
   table_x.*,
   table_y.*
FROM table_y
LEFT JOIN table_x
   ON table_y.column = table_x.column
   ON table_y.column2 = table_x.column2
WHERE
   table_x.column2 is NULL

def create_dataframe_joined_diffs(dataframe_prod, dataframe_new, columns_join):
    """
    Set the indices to the columns_key
    Concat the dataframes and remove duplicates
    Select the diff representative from each dataset
    Reset the indices and perform an outer join

    Pseudo-SQL:

    SELECT
        UNIQUE(*)
    FROM dataframe_prod
    OUTER JOIN dataframe_new
        ON columns_join
    """
    data_new = dataframe_new.set_index(columns_join)
    data_prod = dataframe_prod.set_index(columns_join)

    # Get any row not in both (may be removing too many)
    data_diff = pandas.concat([data_prod, data_new]).drop_duplicates(keep=False) # any row not in both
    # Select the diff representative from each dataset
    x1 = data_prod[data_prod.index.isin(data_diff.index)]
    x2 = data_new[data_new.index.isin(data_diff.index)]

    # Perform an outer join and keep the joined indices from each set
    # Sort the columns to make them easier to compare
    data_compare = x1.merge(x2, how = 'outer', indicator=True, left_index=True, right_index=True).sort_index(axis=1)

    return data_compare

mask_left = dataframe_compare['_merge'] == 'left_only'
mask_right = dataframe_compare['_merge'] == 'right_only'

Comment: If someone comes up with a simpler way, I'll happily accept their answer.


How to keep button disabled even if user refreshes the page? Javascript

Question: I have this little app that generates numbers between 1 and 90. I do it as I'm practicing with my early JS skills.
It's written in italian so for better understanding, well the title doesn't matter that much, it just says "wanna try your luck?" bla-bla.
Then I set a timeout that disables the "Genera Numeri" button for 1 hour after it's clicked (I set it to 3 seconds for the post), and a message pops up ("You can use it once every hour") but if you refresh the page, of course, you can click it again.
I was wondering, how can I make it that even if I refresh, the countdown would be still going?
I read another similar question where they were talking about Mongo (which I have no clue what it is, I suppose back end (?) ), and they mentioned the use of cookies to do that, which in my inexperienced eyes, could make sense.
Anyways, HERE the Javascript
let button = document.querySelector('.button')
let clear = document.querySelector('.clear')
let message = document.querySelector('.message')
let first = document.querySelector('.first')
let second = document.querySelector('.second')
let third = document.querySelector('.third')
let fourth = document.querySelector('.fourth')
let fifth = document.querySelector('.fifth')
let sixth = document.querySelector('.sixth')

button.addEventListener('click', ()=> {
  first.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  second.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  third.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  fourth.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  fifth.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  sixth.innerText = Math.floor(Math.random() * (90 - 1) + 1)

  message.classList.add('show')

  button.disabled = true

  setTimeout(function(){
    button.disabled = false
    message.classList.remove('show')
  }, 1000 * 3)

})

clear.addEventListener('click', ()=> {
  first.innerText = ''
  second.innerText = ''
  third.innerText = ''
  fourth.innerText = ''
  fifth.innerText = ''
  sixth.innerText = ''
})

And HERE the snippet

let button = document.querySelector('.button')
let clear = document.querySelector('.clear')
let message = document.querySelector('.message')
let first = document.querySelector('.first')
let second = document.querySelector('.second')
let third = document.querySelector('.third')
let fourth = document.querySelector('.fourth')
let fifth = document.querySelector('.fifth')
let sixth = document.querySelector('.sixth')

button.addEventListener('click', ()=> {
  first.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  second.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  third.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  fourth.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  fifth.innerText = Math.floor(Math.random() * (90 - 1) + 1)
  sixth.innerText = Math.floor(Math.random() * (90 - 1) + 1)

  message.classList.add('show')

  button.disabled = true

  setTimeout(function(){
    button.disabled = false
    message.classList.remove('show')
  }, 1000 * 3)

})

clear.addEventListener('click', ()=> {
  first.innerText = ''
  second.innerText = ''
  third.innerText = ''
  fourth.innerText = ''
  fifth.innerText = ''
  sixth.innerText = ''
})
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-image: url('conf.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  height: 100vh;
  background-position-x: right;
}

.overlay {
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,.3);
}

.container {
  width: 95vw;
  height: 420px;
  margin: auto;
  display: flex;
  flex-direction: column;
  border: 1px solid black;
  justify-content: space-around;
  align-items: center;
  text-align: center;
  font-family: helvetica;
  position: absolute;
  top: 40vh;
  left: 50vw;
  transform: translate(-50%, -50%);
  background: rgba(0,0,0,.75);
  color: white;
  border-radius: 15px;
  box-shadow: 0 0 15px black;
  padding-bottom: 1em;
}

.title {
  height: 50%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  text-align: center;

  letter-spacing: .5px;
}

h1 {
  font-family: verdana;
  border-bottom: 1px solid white;
}

.tenta {
  font-size: 1.25em;
}

.numbers {
  display: flex;
  width: 100%;
  justify-content: space-around;
}

.number {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 1px solid white;
  text-align: center;
  vertical-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-family: tahoma;
  font-size: 1.2em;
  background: black;
}

.button {
  padding: .5em 1.5em;
  font-size: 1.1em;
  border: none;
  background: white;
  border-radius: 5px;
  box-shadow: 0 0 10px black;
  transition: .2s linear;
  outline: none;
  background: rgb(0,255,117)
}

.button:active {
  transform: scale(.95);
}

.clear {
  padding: .2em .5em;
  position: absolute;
  bottom: 20px;
  right: 20px;
  border: none;
  background: white;
  border-radius: 5px;
  box-shadow: 0 0 10px black;
  transition: .2s linear;
  outline: none;
}

.clear:active {
  transform: scale(.95);
}

p {
  color: white;
  text-align: center;
  position: relative;
  top: calc(450px + 20vw);
  font-family: helvetica;
  font-size: 1.1em;
  margin: auto;
  background: rgba(0,0,0,.45);
  padding: .5em 1em;
  display: none;
}

p.show {
  display: block;
}

Number Generator

Non sai quali numeri giocare?

Tenta la fortuna con l'algoritmo di
 Number Generator!

      <button class="button">Genera Numeri</button>
      <button class="clear">Refresh</button>

Puoi usare Number Generator una volta ogni ora

Comment: Create a cookie (https://www.w3schools.com/js/js_cookies.asp) or use local storage (https://developer.mozilla.org/en-US/docs/Web/API/Storage)
Answer: I didn't read all your code but from the explanation it seems like you have wrong approach in general if you want to restrict the user from clicking the button. I think you are aware of the client and server side computation.
So, first of all. Surely you can restrict button clicks on client side and even in a consistent way (saving it after refresh) but you should keep in mind that an advanced internet user will be able to hack it easily because you have just some standart options to achieve it. One of them is using cookies: When user clicks a button save a cookie with name butttonClicked or smth with value true and a lifetime of 1 hour. Its easy googlable how to do it. On page load always check if the cookies is set and attach attribute disabled to button. but cookies are visible and user can delete it himself.
To really restrict it you should make some checks on the server side so that even if user was able to send a request somehow, no matter the button was disabled or no on the front end, you should stop performing an action and send back an error message.
Comment: I agree with your approach. Restrains that are based 100% on client side information can easily be hacked, local storage and cookies are easily manipulated by a user with basic knowledge. I would also try to handle it on the server side.
Comment: Thank you very much! It's quite complex for me, for now
Answer: One way to do this would be using the browser's built-in capability to store data for a particular domain by utilizing the local storage. In general it can be used to store any kind of data but in your case it should hold the time your button gets 'reactivated'.
Let me outline what needs to be done:

at page load, start a timer which continuously checks the time stored in the local storage in a short interval of e.g. 1 second.

if there is no time stored yet, store the current time

if there is a time stored and it's in the future, disable the button

if there is a time stored and it's in the past, enable the button

If the user presses the button, update the value in the local storage and disable the button.

Here's an example. If you click on the button, it will disable it for 3 seconds:

        <button id="button">click me</button>

Comment: Thank you very much! I will try to implement it In my code and I'll write an additional comment for how's going


Expected value of a random variable so that

Question: I was just shown this website so I really have no clue how things work. Let me know if I do something wrong please. Also, please bare with me because English is not my first language and I'm really bad at Math.
Me and my friend who showed me this website are doing this online course for seniors, and have no base knowledge of most advanced math .. so please bare with me.
Here's one of my first assignment exercises :

Consider a random variable X so that :
  $\operatorname{E}[(X-1)^2]=10$ and $\operatorname{E}[(X-2)^2]=5$
Please solve :
1 - The expected value of X:  $\operatorname{E}[X]$
2 - The variance of X: $\operatorname{V}[X]$

In regards to this, could you please help with some tips of what subject to study (the subject, a book, a website?)
Thanks in advance,
Paulo
Comment: Hint: What is $E[(X-1)^2-(X-2)^2]$?
Answer: Expectation is linear, so $E[(X-1)^2] = E[X^2] - 2 E[X] + 1=10$ and $E[(X-2)^2] = E[X^2 - 4 X +4] = E[X^2] - 4 E[X] +4=5$.
From these two equations, you can solve for $E[X],E[X^2]$. Then, note $var(X) = E[X^2] - (E[X])^2$.
Comment: Hello Batman, Thanks for your answer. I went to read about expectation being linear so I could really solve that as a linear equation or in this case a system of equations. So thats where I'm confused. Theres only one variable and 2 equations with diferent results, which makes it unsolvable.. I'm pretty sure i'm looking at this the wrong way. Or maybe I'm just supposed to make it simpler so it looks like the VAR formula, but in that case why are there 2 ? Is this conditional? Does the "and" means X, given X? (which also doesn't make sense). Could you help with the basic approach? Thanks again
Comment: Let $a = E[X]$, $b=E[X^2]$. Now, solve for $a$ and $b$. In general, $E[X^2] \neq (E[X])^2$.
Comment: Thank you, that was awesome. It's been many years and I am sure rusty but you've made it simple and made me look further into several subjects (like properties of expected values and approaching these)


Element exceeding column width

Question: I am new to bootstrap and I tried to create a form and put a back button next to it. Now the problem I am facing is that parent column is col-lg-4 col-lg-offset-4 but a nested column into the mentioned column exceeds its limit and is moving out of col-lg-4 col-lg-offset-4. I tried to figure it out but couldn't find a logical explanation to it. I am also posting code and images of the problem I am facing.

@section('body')

Edit Record

                    <button class="btn btn-info">Back</button>

                 <form class="well">
                    <input type="text" name="title" class="form-control" value="{{$rec->title}}">

                    <input type="text" name="title" class="form-control" value="{{$rec->body}}">

                        <button class="btn btn-info">Submit</button>

                 </form>

@endsection

col-lg-4 col-lg-offset-4

This is how it is exceeding the limit

Please someone explain how and why is this happening?
Comment: can you add the html please? or codesnippet
Comment: @JoshAdams plz check out, I have posted the code.
Answer: You can't have columns nested directly under other columns, you have to use nested rows and columns must be the only elements under rows, so this:

            [...]

needs to become like this:

            [...]

Also, remember that when you create a new nested row/cols it will still be divided in twelve parts but the size will be that of the container element. In your case the
 will be 11/12 of
 so you have to adjust because 11+3 = 14
Example:
Not sure if this looks exactly how you want it to look but it's a working starting point... feel free to edit it however you need:

Edit Record

                    <button class="btn btn-info">Back</button>

            <form class="well">

                        <input type="text" name="title" class="form-control" value="{{$rec->title}}">

                        <input type="text" name="title" class="form-control" value="{{$rec->body}}">

                        <button class="btn btn-info">Submit</button>

            </form>

Comment: I've added a working example to my reply above, feel free to use it as a starting point ;-)
Comment: Even if I take `` the button still falls out of the container element i.e `` Why is that?
Comment: As said, you also need to nest rows and columns the right way. Whenever you need a new set of columns it must be enclosed in a row. I don't know if you have corrected the code above but you have columns nested inside other columns and you can't do it.
Rows can only contain columns, columns can contain whatever you want (except for other columns as direct children), including other rows which in turn will contain other columns.
Comment: I've detailed my answer more, hope it helps.
Comment: I have upvoted you but am waiting for some other answers. If your answer is found to be correct will accept it as an answer.
Comment: Thanks a lot. Appreciate the help.

Element exceeding column width


I bought a house and the ceiling fan light in one of the bedrooms has three lights 2 regular and then one is candelabra. Is this safe and why?

Question: Ceiling fan light has 2 regular light fixtures and one candelabra fixture. Is this normal and safe?
Comment: Can you get us photos of the situation please?
Comment: Is one a nite light.
Comment: what does this mean? ... `2 regular light fixtures and one candelabra fixture`
Comment: Are you talking about the light *bulbs*, or the actual lamp *sockets* in the ceiling fan?
Comment: 2 regular fitures in the fan itself and then one candelabra fixture in the fan also 3 total mix and match no nightlight
Answer: All those types of lightbulb socket are safe for normal voltage lightbulbs, so no need to be concerned about the safety of it on that basis. If there are any signs it wasn't originally built that way, you have not shared them with us, so if that is the reason you are concerned about safety, you'd have to provide some explanation and preferably also pictures.
It's not terribly normal, but that may be because it was intended to be wired differently than it is (i.e. the nightlight function mentioned in comments, which you say is not a nightlight.)
An additional possibility without the benefit of pictures to see - there might be a candelabra-base reducing adapter stuck in a regular base socket. I'd be particularly suspecting this if this is "3 lights, spaced 120 degrees apart, all identical otherwise"


how to create a color pdf from excel using (Catia) vba

Question: Hej, I am new in coding. I am trying my best but I am stuck. I have searched internet and stackoverflow but haven't find answer.
I am writing code in Catia V5 VBA and I want to export excel to pdf. Excel has some pictures in color and I want that pdf is also in color. But I always end up with pdf in Black & white. This is my basic code:
Sub CATMain()
Set xlApp = CreateObject("Excel.Application")
Set mydoc = xlApp.Workbooks.Open("D:\Excel_1.xls")
Set mySheet = mydoc.Sheets.Item(1)

mySheet.ExportAsFixedFormat Type:=xlTypePDF, _
    fileName:="D:\Excel_1.pdf", _
    Quality:=xlQualityStandard, _
End Sub

I have looked for other parameters of "ExportAsFixedFormat" method, but there isn't any about color.
In despair I have also tried:
xlApp.ActiveWorkbook.SaveAs "D:\Excel_1.pdf"

But I get error saying: "Adobe Acribat could not open 'Excel_1.pdf' because it is either not a supported file type or because the file has been damaged"
Workbook.SaveAs method has "FileFormat" parameter but there isn't pdf in list of suportet file formats.
do you know what method should I use to get colored pdf?
thanks in advance
Comment: It's  strange because when I'm trying your code with mySheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="D:\Excel_1.pdf", Quality:=xlQualityStandard
the pdf in output is colored. I presume when I read your question that you run your macro from Catia. Can you test your code from Excel (Excel > Visual Basic), and say to me if the pdf is still not colored ?
Comment: Delete also the " , _" after xlQualityStandard if you are no other parameters after this.
Comment: Thank you for your response. I have figured out what was problem, and it wasn't in code (beside unintentional ",_" part:)). I had to remove Page Setup/Sheet/Print check mark from Black and white. I was so focused on code that i didn't look to page set up options in excel.
Answer: If someone have same problem as I did, just add this code before exporting to pdf:
mySheet.PageSetup.BlackAndWhite = False

this will set sheet to print in color.
so, code will look like this:
Sub CATMain()

Set xlApp = CreateObject("Excel.Application")
Set mydoc = xlApp.Workbooks.Open("D:\Excel_1.xls")
Set mySheet = mydoc.Sheets.Item(1)

mySheet.PageSetup.BlackAndWhite = False

mySheet.ExportAsFixedFormat Type:=xlTypePDF, _
fileName:="D:\Excel_1.pdf", _
Quality:=xlQualityStandard

End Sub


how to append float numbers to a list in python

Question: I am trying to compare one image with all images of another file , get the difference percentage and print file name of the least difference percentage ....  if i try to append the output differences to a list ... i get an error saying " float values cannot be iterated"....  this is what i have done so far ....
from itertools import izip
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
from PIL import Image
import math
res = 0
def take_and_save_picture(im_save):
  '''Take a picture and save it

  Args:
    im_save: filepath where the image should be stored
  '''
  camera_port = 0
  ramp_frames = 30
  cap = cv2.VideoCapture(camera_port)
  def get_image():
   retval, im = cap.read()
   return im

  for i in xrange(ramp_frames):
   temp = get_image()

  print("Taking image...")
  # Take the actual image we want to keep
  camera_capture = get_image()

  #im_save_tmp = im_save + '.jpg'
  im_save_tmp = im_save

  # A nice feature of the imwrite method is that it will automatically choose the
  # correct format based on the file extension you provide. Convenient!
  cv2.imwrite(im_save_tmp, camera_capture)

  # You'll want to release the camera, otherwise you won't be able to create a new
  # capture object until your script exits
  # del(cap)

  img1 = cv2.imread(im_save_tmp, 0)

  edges = cv2.Canny(img1, 100, 200)
  cv2.imwrite(im_save, edges)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

def re(path1,path2):

    #path1 = raw_input("Enter the path1:")
    #path2 = raw_input("Enter the path2:")
 i2= Image.open(path2)
 listing = os.listdir(path1)
 for file in listing:
   i1 = Image.open(path1 + file)
   assert i1.mode == i2.mode, "Different kinds of images."
   assert i1.size == i2.size, "Different sizes."

   pairs = izip(i1.getdata(), i2.getdata())
   if len(i1.getbands()) == 1:
    # for gray-scale jpegs
     dif = sum(abs(p1-p2) for p1,p2 in pairs)
   else:
     dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))

   ncomponents = i1.size[0] * i1.size[1] * 3
   res = (dif / 255.0 * 100) / ncomponents
   print "Difference (percentage):", res

def main():
  capture_img = "/Users/Me/Documents/python programs/New/pro.png"
  #img_to_compare = "/Users/Me/Documents/python programs/compare/img2.jpg"
  take_and_save_picture(capture_img)
  path1 = "/Users/Me/Documents/python programs/New/numbers1/"
  path2 = "/Users/Me/Documents/python programs/New/pro.png"
  re(path1,path2)

if __name__ == '__main__':
  main()

the output is the difference
Difference (percentage): 2.52484809028
Difference (percentage): 2.64822048611
Difference (percentage): 2.64822048611
Difference (percentage): 3.55436197917

the values that i get in "res" have to be stored in a list and the minimum value should be found and printed.... please give me some code ... totally new to python ... thank you ...
Comment: There's far too much irrelevant code here. Please show the specific bit you are having problems with.
Comment: @DanielRoseman ... i dont have a problem with anything in this code ... i just need to know how to add float numbers to a list/ array in python because it keeps saying that float cannot be iterated
Answer: You're code must be like this:
#######
list_dif = []

def re(path1,path2):
    #path1 = raw_input("Enter the path1:")
    #path2 = raw_input("Enter the path2:")
    i2= Image.open(path2)
    listing = os.listdir(path1)
    for file in listing:
        i1 = Image.open(path1 + file)
        assert i1.mode == i2.mode, "Different kinds of images."
        assert i1.size == i2.size, "Different sizes."

        pairs = izip(i1.getdata(), i2.getdata())
        if len(i1.getbands()) == 1:
            # for gray-scale jpegs
            dif = sum(abs(p1-p2) for p1,p2 in pairs)
        else:
            dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))

        ncomponents = i1.size[0] * i1.size[1] * 3

        #######
        for n in range(ncomponents):
            res = (dif / 255.0 * 100) / (ncomponents + 1)
            list_dif.append(res)

        print "Difference (percentage):", list_dif

Comment: thank you very much .. it works but it goes into an endless loop ... i think i can fix that ...
Answer: Something like this?
def re(path1,path2):
    #path1 = raw_input("Enter the path1:")
    #path2 = raw_input("Enter the path2:")
    i2= Image.open(path2)
    listing = os.listdir(path1)
    res = []
    for file in listing:
        i1 = Image.open(path1 + file)
        assert i1.mode == i2.mode, "Different kinds of images."
        assert i1.size == i2.size, "Different sizes."

        pairs = izip(i1.getdata(), i2.getdata())
        if len(i1.getbands()) == 1:
            # for gray-scale jpegs
            dif = sum(abs(p1-p2) for p1,p2 in pairs)
        else:
            dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))

        ncomponents = i1.size[0] * i1.size[1] * 3
        res.append((dif / 255.0 * 100) / ncomponents)
        print "Difference (percentage):", res
    minimum = min(res)  # Find minimum value in res
    print(minimum)

Comment: @Primoz it wasn't me!


Wireless not working on Dell XPS 17 after installing 12.04

Question: I (linux newbie) have a Dell XPS 17 and tried to install Ubuntu 12.04. After installation all WLAN accesspoints near are detected. But I can not connect (but I am able to connect with other computers as well as with Dell XPS 17 under windows). Outputs:
iwconfig
  lo        no wireless extensions.

  wlan0     IEEE 802.11bg  ESSID:"LerchenPoint"
      Mode:Managed  Frequency:2.412 GHz  Access Point: 58:6D:8F:A0:2D:58
      Bit Rate=1 Mb/s   Tx-Power=14 dBm
      Retry  long limit:7   RTS thr:off   Fragment thr:off
      Power Management:off
      Link Quality=70/70  Signal level=-37 dBm
      Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
      Tx excessive retries:0  Invalid misc:19   Missed beacon:0

  eth0      no wireless extensions.

sudo lshw -class network
*-network
   description: Wireless interface
   product: Centrino Wireless-N 1000
   vendor: Intel Corporation
   physical id: 0
   bus info: pci@0000:04:00.0
   logical name: wlan0
   version: 00
   serial: 00:26:c7:99:98:28
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
   configuration: broadcast=yes driver=iwlwifi driverversion=3.2.0-24-generic firmware=220.127.116.11 build 35138 latency=0 link=no multicast=yes wireless=IEEE 802.11bg
   resources: irq:50 memory:f0400000-f0401fff
*-network
   description: Ethernet interface
   product: RTL8111/8168B PCI Express Gigabit Ethernet controller
   vendor: Realtek Semiconductor Co., Ltd.
   physical id: 0
   bus info: pci@0000:0a:00.0
   logical name: eth0
   version: 06
   serial: f0:4d:a2:56:e3:94
   size: 1Gbit/s
   capacity: 1Gbit/s
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp
   mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
   configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl_nic/rtl8168e-2.fw ip=192.168.0.123 latency=0 link=yes multicast=yes port=MII speed=1Gbit/s
   resources: irq:47 ioport:6000(size=256) memory:f0a04000-f0a04fff memory:f0a00000-f0a03fff

dmesg | grep iwl
[   10.157531] iwlwifi 0000:04:00.0: PCI INT A -> GSI 17 (level, low) -> IRQ 17
[   10.157561] iwlwifi 0000:04:00.0: setting latency timer to 64
[   10.157598] iwlwifi 0000:04:00.0: pci_resource_len = 0x00002000
[   10.157599] iwlwifi 0000:04:00.0: pci_resource_base = ffffc90011090000
[   10.157601] iwlwifi 0000:04:00.0: HW Revision ID = 0x0
[   10.157731] iwlwifi 0000:04:00.0: irq 50 for MSI/MSI-X
[   10.157834] iwlwifi 0000:04:00.0: Detected Intel(R) Centrino(R) Wireless-N 1000 BGN, REV=0x6C
[   10.157976] iwlwifi 0000:04:00.0: L1 Enabled; Disabling L0S
[   10.179772] iwlwifi 0000:04:00.0: device EEPROM VER=0x15d, CALIB=0x6
[   10.179775] iwlwifi 0000:04:00.0: Device SKU: 0X50
[   10.179777] iwlwifi 0000:04:00.0: Valid Tx ant: 0X1, Valid Rx ant: 0X3
[   10.179796] iwlwifi 0000:04:00.0: Tunable channels: 13 802.11bg, 0 802.11a channels
[   10.574728] iwlwifi 0000:04:00.0: loaded firmware version 18.104.22.168 build 35138
[   10.726409] ieee80211 phy0: Selected rate control algorithm 'iwl-agn-rs'
[   19.714132] iwlwifi 0000:04:00.0: L1 Enabled; Disabling L0S
[   19.777862] iwlwifi 0000:04:00.0: L1 Enabled; Disabling L0S
[ 2251.603089] iwlwifi 0000:04:00.0: PCI INT A disabled
[ 2266.578350] iwlwifi 0000:04:00.0: PCI INT A -> GSI 17 (level, low) -> IRQ 17
[ 2266.578399] iwlwifi 0000:04:00.0: setting latency timer to 64
[ 2266.578435] iwlwifi 0000:04:00.0: pci_resource_len = 0x00002000
[ 2266.578437] iwlwifi 0000:04:00.0: pci_resource_base = ffffc90011090000
[ 2266.578439] iwlwifi 0000:04:00.0: HW Revision ID = 0x0
[ 2266.578704] iwlwifi 0000:04:00.0: irq 50 for MSI/MSI-X
[ 2266.578808] iwlwifi 0000:04:00.0: Detected Intel(R) Centrino(R) Wireless-N 1000 BGN, REV=0x6C
[ 2266.578916] iwlwifi 0000:04:00.0: L1 Enabled; Disabling L0S
[ 2266.600709] iwlwifi 0000:04:00.0: device EEPROM VER=0x15d, CALIB=0x6
[ 2266.600712] iwlwifi 0000:04:00.0: Device SKU: 0X50
[ 2266.600713] iwlwifi 0000:04:00.0: Valid Tx ant: 0X1, Valid Rx ant: 0X3
[ 2266.600727] iwlwifi 0000:04:00.0: Tunable channels: 13 802.11bg, 0 802.11a channels
[ 2266.605978] iwlwifi 0000:04:00.0: loaded firmware version 18.104.22.168 build 35138
[ 2266.606331] ieee80211 phy0: Selected rate control algorithm 'iwl-agn-rs'
[ 2266.614179] iwlwifi 0000:04:00.0: L1 Enabled; Disabling L0S
[ 2266.681541] iwlwifi 0000:04:00.0: L1 Enabled; Disabling L0S

Solutions I tried:
rfkill list all
0: dell-wifi: Wireless LAN
Soft blocked: no
Hard blocked: no
2: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no

echo "options iwlwifi 11n_disable=1" | sudo tee /etc/modprobe.d/iwlwifi.conf
options iwlwifi 11n_disable=1
sudo modprobe -rfv iwlwifi
  WARNING: All config files need .conf: /etc/modprobe.d/blacklist, it will be
  ignored in a future release.
  rmmod /lib/modules/3.2.0-24-generic/kernel/drivers/net/wireless/iwlwifi/iwlwifi.ko
  rmmod /lib/modules/3.2.0-24-generic/kernel/net/mac80211/mac80211.ko
  rmmod /lib/modules/3.2.0-24-generic/kernel/net/wireless/cfg80211.ko
sudo modprobe iwlwifi
  WARNING: All config files need .conf: /etc/modprobe.d/blacklist, it will be
  ignored in a future release.

replacing iwlwifi-1000-5.ucode (current driver) against iwlwifi-1000-3.ucode
sudo jockey-gtk:
(jockey-gtk:2493): Gtk-CRITICAL **: gtk_icon_set_render_icon_pixbuf: assertion icon_set != NULL' failed (jockey-gtk:2493): Gtk-CRITICAL **:   gtk_icon_set_render_icon_pixbuf: assertion icon_set != NULL' failed

nothing is listet in "Additional drivers" (german: "Zusätzliche Treiber").
gksudo gedit /etc/modprobe.d/blacklist.conf
add "blacklist acer_wmi"
Any help would be appreciated very much.
Thanks!!
Comment: Run "sudo jockey-gtk" in terminal and check if there any restricted WIFI driver listed. If yes then install and reboot the machine. If it's not there then need to further investigate the issue.
Comment: sudo jockey-gtk: (jockey-gtk:2493): Gtk-CRITICAL **: gtk_icon_set_render_icon_pixbuf: assertion `icon_set != NULL' failed

(jockey-gtk:2493): Gtk-CRITICAL **: gtk_icon_set_render_icon_pixbuf: assertion `icon_set != NULL' failed
  nothing is listet in "Additional drivers" (german: "Zusätzliche Treiber".
Comment: Did not you get any gui? Otherwise run it from Unity dash.
Comment: I got the gui. But nothing was listed. It looks the same if I start it from the Unity dash (german: Systemeinstellungen)
Answer: I've got a Dell XPS 17 (l702x) with an n-1000 I'd like to get working under Ubuntu 12.04 (once I install it). So, lending heavily from this post:
The fix seems to involve downgrading the n-1000's firmware.
Please downgrade the firmware with iwlwifi-1000-ucode-220.127.116.11.tgz (for ease, save it to your desktop). You can right-click it and select 'Extract' or issue the following at a terminal prompt:
tar xzvf ~/Desktop/iwlwifi-1000-ucode-184.108.40.206.tgz

Again, in the terminal, back up the current firmware:
sudo mv /lib/firmware/iwlwifi-1000-5.ucode /lib/firmware/iwlwifi-1000-5.bak

Now copy over the downloaded firmware:
cd Desktop/iwlwifi-1000-ucode-126.96.36.199/
cp iwlwifi-1000-3.ucode iwlwifi-1000-5.ucode
sudo cp iwlwifi-1000-5.ucode /lib/firmware
sudo modprobe -r iwlagn
sudo modprobe iwlagn

Now let's see what happened under the hood:
dmesg | tail -n20

This has been tested and confirmed in the original post, and is said to be a permanent fix (i.e. is still working after a reboot).
best of luck!
Answer: Before you do all that, check your BIOS settings.
I have the same machine and, every once in a while, it will report that wireless is disabled by hardware switch.
It happens only when I suspend the machine while plugged into an ethernet wired connection and then wake it up expecting to use wireless only.
The wireless "button" above the keyboard will not turn it back on, so I have to go into BIOS to re-enable it. Save, reboot, enable wireless in Network Connections and everything's back to normal.


Help with hot/neutral outlet - false reading?

Question: I recently bought an older house and on one of the circuits every outlet (7 outlets spread out over two rooms) gives a "hot/neutral reverse" reading when I use a circuit tester. I looked at each outlet and each one has the correct wiring colors (black to brass, white to silver, and copper to green). Then I measured the voltages using a DMM, and I get the following results (on every outlet): hot to neutral: 120V, hot to ground: 0V (!) and neutral to ground: 120V (!). Then lastly I used a non-contact voltage reader and on every outlet it lights up on BOTH the ground and the hot wires, but not on the neutral wires. Why would the ground wires be live?
Update: thanks for all your responses so far. I used a circuit analyzer and found some more details 1) analyzer also says it's a hot neutral reverse 2) ground to neutral shows 33.5 volts rms 3) ground to hot shows 121V RMS 4) ELL (estimated line load) is weirdly high, 20 amps when there's nothing plugged into any of the outlets (no fans or anything similar on the circuit either). 5) voltage drop is higher than it should be, highest reading was 11% drop for 20 amps 6) impedance is high too, hot reading impedance was 0.67 ohms.
I scheduled an appointment with a professional electrician since the knowledge from my college circuits course and some googling is feeling tapped out. I'll update this post with whatever the pro finds.
Comment: How is the cable terminated in the panel? Does the circuit actually work and power things?
Comment: Can you post photos of the inside of the panel?
Comment: @Harper, yes the circuit works fine and powers things. I haven't checked the panel yet but I'll go take a look and follow up with a picture.
Comment: Are there other outlets in these rooms? The reverse could be in a daisy-chained outlet that you didn't inspect.
Comment: @Mattman944 that's what I was hoping for, but I looked at every outlet and each one had the correct colors.
Comment: Keep in mind "outlet" can also be light switch/lamp, and that is one easy place to mess up.
Comment: I actually had a reverse in a pull chain light in a closet... took me forever to find it.
Answer: Find the breaker for those outlets and check that the  neutral live and ground are correctly connected in the panel.
Then find every other device on that breaker and check the wiring there.
the bad connection could be behind a light switch or in a ceiling box.
Answer: I was also thinking you were checking outlets downstream from one that was incorrectly wired, just as @Mattman944 had suggested.
I would definitely try to identify where the power is coming into the room from the panel i.e. the "home run" and ensure the hot is coming off the appropriate breaker (size & type for the room) and the neutral is tied to ground bar (if this if the main panel), and all those colors are in fact correct.
How old of a house are we talking? Is this all copper Romex, or old 2-conductor knob&tube?
Answer: First lets ignore the non-contact voltage readings. The most common reason for reading "hot to neutral: 120V, hot to ground: 0V (!) and neutral to ground: 120V". Would be a broken ground, and since you live in an older dwelling this may be an addition or repair and whom ever installed it has not run the ground back to the panel. Your neutral to ground reading is probably a reference voltage being read through a remote piece of equipment like a motor. Or more plainly a difference of potential between the neutral connected to the panel bus and the ground which is not.
As everyone else has already stated. Check the polarity all the way back to the panel and run through the circuit to see if you can find the broken ground.
I have in my lifetime, seen houses wired with the white conductor attached to the breaker and the black connected to the neutral bus. Rare but not impossible.
Good luck


Internally sorting a class that inherits from a vector of pointers to a user defined object (C++)

Question: So I defined a class on C++ that inherits from a vector of pointers:
class SuperBinList : public std::vector<SuperBin*>{

public:
  SuperBinList();
  SuperBinList(const std::vector<SuperBin*>& superBinList);
  virtual ~SuperBinList();

  SuperBinList& operator += (SuperBin* superBin);
  SuperBinList& operator += (const SuperBinList& superBin);

  void sortByZbi(const double sys);
  void sortBySoverB() const;

};

The SuperBin class itself is defined as:
class SuperBin{

public:
  SuperBin(const VI index, const double nSig, const double nBkg, const VS mPerpLabel, const VS rIsrLabel, const VS visLabel);
  virtual ~SuperBin();

  VI getIndex();
  double getNsig();
  double getNbkg();
  double getSoverB();
  double getBinZbi(const double sys);

  VS getMperpLabel();
  VS getRisrLabel();
  VS getVisLabel();

  SuperBin* tryMerge(SuperBin* superBin, double sys);

private:

  VI index_;
  double nSig_;
  double nBkg_;
  double sOverB_;
  VS mPerpLabel_;
  VS rIsrLabel_;
  VS visLabel_;

};

Now the problem I'm having is that I want the SuperBinList class to be able to sort itself in descending order in terms of any of the (double type) members of the SuperBin class (such as sOverB). For this I tried the following method using a lambda function:
void SuperBinList::sortBySoverB() const{

  std::sort(this->begin(), this->end(), [](const SuperBin* lhs, const SuperBin* rhs){
      return lhs->getSoverB() < rhs->getSoverB();});
}

The top error I'm getting is:
error: passing 'const SuperBin' as 'this' argument discards qualifiers [-fpermissive]
       return lhs->getSoverB() < rhs->getSoverB();});

Which, as I understood from similar threads, has to do with the const specifiers. However, I'm still not sure what it is that I am doing wrong. Any help would be greatly appreciated. Please pardon my ignorance as I am a physics PhD and not a computer scientist.
Comment: In other words, remove the `const` from `void sortBySoverB() const;` - it doesn't make logical sense to have it there
Comment: `this` points to a const object in `sortBySoverB`. Therefore `this->begin()` returns a const iterator, i.e. one that cannot be used to modify the values in the vector. `std::sort` requires a iterator that can be used to write the elements though... Also of course non-`const` member functions cannot be called using a pointer to `const`. Even if the vector is `const`, the elements are still pointers to non-`const` and depending in this scenario you need to make the the lambda parameters to be pointers to non-const (or better make `getSoverB()` `const`).
Answer: You have your SuperBinList::sortBySoverB() function defined as const, which means it is not allowed to modify SuperBinList, and
this will have the type const SuperBinList *, rather than SuperBinList *
Similarly, your lambda is define with const pointers const SuperBin* lhs, meaning you can only call const functions.
Change your function definitions to void SuperBinList::sortBySoverB() {} and double getSoverB() const {}, and it should compile. (Generally member functions should be marked const if they are read-only operations like getters).


Why don't bookshelves come with wall mounting screws included?

Question: I was assembling an IKEA bookshelf, and one of the most important steps to ensure safety is the installation of the L-bracket to secure the bookshelf to the wall. All the parts, including the bracket and the screw for attachment onto the shelf, are included (see below). To my disappointment, however, the long mounting screw for attachment to the wall is evidently missing. So now, I find myself unable to complete the project due to the missing mounting screws.
I don't think this is a special case for the bookshelf or for IKEA. Why don't furniture manufacturers include wall mounting screws in the package for convenience?

Source: https://www.ikea.com/us/en/assembly_instructions/billy-height-extension-unit__AA-982217-8_pub.pdf
Comment: Many of them DO come with such screws, though rarely ones suitable for all possible situations...
Comment: @MikeBrockington The last IKEA piece I bought did come with one pair of screws, and 3 different kinds of wall anchors (for wood, drywall, and concrete).  Mind you I didn't use any of them because the furniture in question is a 3' high clothes dresser - nearly impossible to tip over unless you're *really* trying to.  It even has warnings to open only one drawer at a time to avoid tipping - I could open all 3 drawers while they're loaded with lead bricks and that thing still wouldn't tip, methinks they might be a tad over-cautious about this sort of thing.
Comment: @DarrelHoffman They might be "over-cautious" because they settled a $46 million lawsuit resulting from a tipped-over Ikea dresser (probably not loaded with bricks) crushing a child to death.
Comment: @DarrelHoffman There were actually [2 child deaths from Ikea dressers](https://www.ikea.com/us/en/customer-service/product-support/recalls/following-an-additional-child-fatality-ikea-recalls-29-million-malm-and-other-models-of-chests-pub4128a7af), one from a 30" tall dresser and one from a 48" tall dresser.
Comment: I have a screws box which has a variety of screws and other fixings for use in situations like this - a few drywall, plastic rawlplugs for concrete in various sizes etc - a good addition if you plan to do projects as safety is paramount.
Comment: @shoover Sure, I have many posessions that would pose no real danger to anyone l except that I _do_ have small children around.
Comment: @DarrelHoffman It depends on the use case. For example if a care home installs some IKEA furniture, it has a legal duty to ensure that the residents (who may be mentally disturbed, have dementia, etc) can not injure themselves by literally climbing up the walls. Does a 300-lb person opening the drawers and climbing up them like stair steps count as "really trying to tip the furniture over?" Not necessarily, if whoever injured themselves doing it has no legal mental competence to "deliberately" do anything!
Comment: @DanC I'm willing to bet that dresser was one of the taller ones.  It makes perfect sense for a 6' tall dresser/shelf to be mounted to the wall, but not a short one like this.  I think if you tried to climb up the drawers like steps, the first thing that would happen is your foot would knock the bottom right out of the drawer (it's just a thin piece of particle board attached with staples), and mounting it to the wall wouldn't stop that from happening.  (Lead bricks would probably do the same of course - mine just has clothes in it.)
Comment: They often do. What did IKEA say when you asked?
Comment: I have used bookcases for 54 years and have never mounted one to the wall. I have even stood some up back-to-back perpendicular to the wall because I needed to fit more books into the room. Disclaimer: Other than myself in the early years, there have been no small children with access to my bookcases in all that time.
Comment: @DarrelHoffman multiple BrandX bookshelves I've bought over the last 16 years all came with a bracket and a long wood screw, along with IIRC screw into a wooden stud instructions.
Answer: From the linked assembly instructions:

Screw(s) and plug(s) for the wall are not included. Assess the
suitability of the wall to ensure that it will withstand the forces
generated. Use screw(s) and plug(s) suitable for your walls and the
intended load. If you are uncertain, seek professional advice. Read
and follow each step of the instruction carefully

If they included default hardware, customers would use it without thinking even in cases where it was not appropriate for their wall construction, presumably leading to a potential liability for Ikea. By not including any hardware for wall attachment, they put the liability on someone else to get the right kind of hardware for however the customer's wall is built.
This is some speculation about Ikea's reasons based on their instructions. I imagine the situation is similar for other furniture retailers.
Comment: Ikea also recently [came out of a $46M lawsuit](https://www.dezeen.com/2020/01/13/ikea-settlement-recalled-malm-dresser/) and [recall](https://www.ikea.com/us/en/customer-service/product-support/recalls/following-an-additional-child-fatality-ikea-recalls-29-million-malm-and-other-models-of-chests-pub4128a7af) that prompted the addition of these wall-mount brackets to all of their dressers and drawers. Given that these were not part of the original furniture design and had to be added in afterwards we can also guess that Ikea did the minimum necessary to comply with whatever the courts ordered.
Comment: Agreed, but it's also heavily a cost saving measure.  Plenty of other wall-mounted products (ie: VESA mounts, etc) will come with hardware suitable for a number of common wall constructions and directions for each.  Adding the extra hardware is just a cost.  Liability is just a cost.  Not including these *ostensibly* for liability reasons is really just another way of cutting costs and making things simpler for the manufacturer.
Comment: @Fattie It's not just the fasteners - it's the liability(ie: design and sign phase). I'd actually be curious to see if new (post-lawsuit) Ikea designs contain wall fasteners and whether all the back catalog just got brackets thrown in as as backpatch.  Ikea is also the one-mouse-button of the DIY world, and wall fasteners need at least a stud finder, and maybe a masonry bit and hammer drill...and maybe that's just too scary for an Ikea instruction booklet with no words...designed for people who own no tools.
Comment: Guys, I'm sure it's NOT a cost saving measure.  It would be an unmeasurably low cost to have the line add in a couple of screws or fasteners.
Comment: Though, if I understand the way these brackets work correctly, not much strength is needed - they keep the piece of furniture from ever being in a position where its weight could lever the anchors out of the wall ....
Comment: @J... Im not too sure that its going to change all that much - I just put together a tonne of Billy bookcases with Oxberg doors (both purchased in 2020), and both the bookcases and doors came with wall restraint fixtures separately - however, I also in the same batch put together a bunch of Billy bookcases and Besta storage cabinets purchased around 2014, and they also all came with wall restraint fixtures (L-brackets for the Billy, through-back restraints for the Besta).  Some Ikea furniture has always had them included.
Comment: There is a rather large section in the instructions giving you a bracket to attach to the furniture, but there is still no fastener to attach to the surface, because this is different depending on whether it is dry-wall, wood, or concrete. You can't possibly have all the parts for all scenarios, and you actually need to know what you are doing to make it safe.
Comment: @J... Your point about cost is a good one which I should have mentioned. I suppose there are many coniderations invisible to the consumer which would factor in to Ikea's decision to include mounting screws for some products but not others.
Comment: @J... yes, that's exactly right.  TBC I believe some folks were suggesting it is literally the cost of adding a screw to the packet; the cost of literallyf adding a screw to the packet is absolutely tiny, barely measurable.
Comment: @Fattie I guess the point is that the cost of adding a screw to a box has very little to do with the cost of the screw itself.
Comment: @J... They have updated all their instructions and it is very prominent if the furniture needs to be anchored. I've installed 4-5 shelves that are either designed as wall mounted or requires anchoring, and none of them includes the screw itself.
Answer: While they are 100% sure what type and size of fastener is required for assembling the product, they have no control over the type of wall/support you are installing/fastening the product to (concrete, masonry, wood..etc). It may have recommendation in the instruction sheet, with the type and size indicated for varies types of support medium, and indicating whether they are included in the package or not. But, usually the furnished parts are list on the inventory sheet enclosed with the package. From that, you can tell if a part is to be provided but missing.
Answer: The obvious answer is that they sometimes don't include them by default because not everybody needs them, so omitting them would reduce cost (and waste).
The premise of "why don't they come with wall mounting screws included?" isn't true; sometimes they do.  If they don't, you can ask IKEA for wall mounting screws, which they will provide for free.
Answer: Ikea, and other providers, have no clue as to what wall their bookcases (and other furniture) might be destined for. Several different constructions come to mind, each needing a different screw/fixing for the bracket. They could furnish all kinds of fixings, but then some customers would use an inappropriate one, and there could be legals involved. Much better to leave that to the customer!
Imagine the situation where a bookcase was placed needing one bracket into a wooden doorframe, the other into plasterboard, or brick. Potential for all kinds of diy mistakes!


How to tape over channel left by old tape

Question: My drywall tape was coming off the wall in my bathroom so I pulled the loose stuff out. It left this channel behind. I'm not sure if I should put a coat of mud on first to smooth it out, or maybe sand it first, and then tape? Should I fill the little crack first?
Thank you
Answer: Do yourself a favor and run a taping knife over the edges of the compound that remain. ( like this: Knife> /__ direction>>>  )That will knock off loose bits and particles that will get in your compound and drive you nuts.
If you are using paper tape, apply compound, then the tape then more compound.
My preference would be applying mesh tape to the cracks, then mud over the entire width from the old tape. Let that dry and fill in any cracks and low spots, Lightly sand, then prime and paint.
Since it's a bathroom, I would paint another coat in the entire room to protect from moisture. Having an exhaust fan and using it will help with having to repeat this job.


The G-Man walking around in HL2

Question: I've noticed the G-Man walking around in various areas in HL2 and the episodes...always just outside of the normal camera range unless if you really look at him.
I realize that this is just a bit of cinematic flair and Valve is playing around here a bit, but I'm curious...is there any way to interact with him?  Shoot or kill him even?
I'm currently about halfway through Episode 2 and just noticed him walking on a far-off catwalk.  I didn't have access to a weapon at that point but it kind of made me wonder.
Comment: He is also found in Half-Life 1. I believe he is present in all Half-Life games.
Answer: No, he is never close enough to harm. He is immune to being shot, even if you reach him via noclip or other means.
Source (including list of locations)

The G-Man walking around in HL2


To preselect or not preselect checkboxes

Question: Lets say you want to customize and buy a new car online. You get to choose from a list of options for the interior. (Radio, Nav System, Leather or Cloth seats, powered windows, doors, locks, etc..)
The car maker always preselects the cheapest options for you.
For the consumers, is it better to preselect the cheapest options, or leave the checkboxes unchecked and let the customers decide for themselves what they want.
Answer: In general, starting with the basic options selected by default and allowing the upgrades to be selected is a better option.
If you choose to check the cheapest option by default, you have a smoother checkout process as well as avoid the situation where someone feels that you are trying to rip them off by selecting a more expensive option by default.
The Apple or Dell store handle this very well, where the upgrade is shown with the additional price.

However this should only be done where there is really a base option rather than a common preference.  It would be a poor choice to by default select the car colour as white even though that may be the cheapest option.  But it would be fair to choose cloth seats by default over leather seats.
Comment: Totally agree. The only caveat I will add, is in a scenario where a pre-selected choice may represent some cultural problems with regards to bias. For example, if the choices are "female" or "male" (and obviously radio buttons), would you pre-select one or the other, or none? What about when they're **required**? You can see how this can quickly lead to trouble in these sensitive times... what would you suggest for my "example"?
Answer: Consider each question on a case-by-case basis.
This isn't as cut and dried as it first appears. In some cases, the options will obviously have a "base" selection ('cheapest' for example), and that can be pre-selected with no issue. Making your users' life easier is your ultimate goal in all situations. But we also don't want to introduce unintended errors, or worse, have them leave because they have been offended by some cultural bias that wasn't considered.
Pre-selection is nice most of the time... but...
Consider, when there is no obvious starting choice, when all options are equally valid. What if they all cost the same, or are a choice between opinions? What if they are gender selections, and pre-selecting may be considered offensive to one or the other sex? In these cases, you run the risk of the user not making a conscious choice, and selecting something that wasn't intended... by default.
Also, in some case (such as on a survey or similar), there absolutely is no best answer. Pre-selecting a value (not to mention which one? "No opinion"?) runs the risk of skewing your results. Some users will not "take it serious" and just blow through with the defaults.
In reality, it isn't the form that should be one way or the other, but each question should be considered on its own merits and handled in the most appropriate way.
Answer: When it comes to buying expensive items, I would imagine most people to be very conscious of the overall price of the item. It would be in the retailer's best interest to convey to the client the "good price" they offer, while still outlining the various additional upgrades/options (with associated cost-implications). In short, don't pre-select expensive add-ons, unless the item is marketed as "everything (all add-ons) included".


Google Home Certification not linking My app

Question: I Have working on dev app for google home certification its working fine and got the approval and released for production but when in production i am not able to do a account linking with my app. when i checked with certification team they mentioned sending scope null in response but as per document scope is an optional parameter.
Any Idea why it is not linking?
Comment: Hi! Welcome to StackOverlow, we only accept programming-related questions here.
Answer: The scope parameter defines additional data sent to you by Google during account linking. While it is optional, you need to verify that what you use/expect is also listed in the Scopes section in AoG Console. You can access it via Develop > Account Linking > Configure your client (optional) > Scopes


Change the color of summary row of grid in extjs

Question:
I want to change the font as well as background color of the summary row of the grid.I have tried getting the summary row as :

var summaryRow = grid.view.el.down('tr.x-grid-row-summary');

Based on summaryRow I can set the style.But I am getting the value of summaryRow as null.Can anyone please point me to correct direction or am I missing something? Any help is appreciated.Thanks
Comment: What about grid.getView().getFeature(0)
Comment: It works fine now.Thanks!! Here is the code :
var summaryRow = grid.getView().getFeature(0);             summaryRow.view.el.setStyle(aStyleObject);
Comment: Try grid.down('Ext.grid.feature.Summary') or grid.down('feature.Summary'). Summary is not a widget but a feature, therefore I am not sure about its xtype query.
Comment: Still it is giving null
Answer: The documented way to do this would be the Summary Renderer, the best method for the summary renderer would be the tdCls or tdAttr properties:
                    text: 'Allocation %',
                    xtype: 'numbercolumn',
                    format: '00.00%',
                    dataIndex: 'allocationAmount',
                    summaryType: 'sum',
                    summaryRenderer: function (value, summaryData, dataIndex, rowIndex, colIndex, store, view) {

                        if (value > 100)
                        {
                            summaryData.tdCls = 'text-warning-high'
                        } else if (value === 100)
                        {
                            summaryData.tdCls = 'text-successful';
                        } else {
                            summaryData.tdCls = 'text-warning-low';
                        }
                        return Ext.String.format('Total: {0}%', value);
                    },

You can also use the tdAttr version like this:
 summaryRenderer: function (value, summaryData, dataIndex, rowIndex, colIndex, store, view) {
                        if (value > 100)
                        {
                            summaryData.tdAttr = 'style="color: #ff0000"';
                        } else if (value === 100)
                        {
                            summaryData.tdAttr = 'style="color: green;"';
                        } else {
                            summaryData.tdAttr = 'style="color: yellow;"';
                        }
                        return Ext.String.format('Total: {0}%', value);
                    },

Note the first one would be using css classes, so you need to define the appropriate css classes in your css file :D
Comment: Dear @Jake I've been implemented this adustment but somehow it's not coloring! Why it's could be?
Comment: Here is code snippet of column;
`{xtype: 'currdebitcol', text: translations.dAmount, summaryType: 'sum', summaryRenderer: function (value, summaryData, dataIndex, rowIndex, colIndex, store, view) { if (value > 100) { summaryData.tdAttr = 'style="color: red;"'; } else if (value === 100) { summaryData.tdAttr = 'style="color: green;"'; } else { summaryData.tdAttr = 'style="color: yellow;"'; } return Ext.String.format('{0}', value); } },`
Answer: var summaryRow = grid.getView().getFeature(0);
styleObj = {
     'background-color': '#c5c5c5'
 };
summaryRow.view.el.setStyle(styleObj);

Answer: You can use summaryRenderer function present in grid column to show the row in specific style.
Ext.create('Ext.grid.Panel', {
    width: 200,
    height: 140,
    renderTo: document.body,
    features: [{
        ftype: 'summary'
    }],
    store: {
        model: 'TestResult',
        data: [{
            student: 'Student 1',
            mark: 84
        },{
            student: 'Student 2',
            mark: 72
        },{
            student: 'Student 3',
            mark: 96
        },{
            student: 'Student 4',
            mark: 68
        }]
    },
    columns: [{
        dataIndex: 'student',
        text: 'Name',
        summaryType: 'count',
        summaryRenderer: function(value, summaryData, dataIndex) {
            return ""+value+"";
        }
    }, {
        dataIndex: 'mark',
        text: 'Mark',
        summaryType: 'average'
    }]
});

Answer: Or we can use CSS in specific page.


How do I get the different parts of a Flask request's url?

Question: I want to detect if the request came from the localhost:5000 or foo.herokuapp.com host and what path was requested.  How do I get this information about a Flask request?
Answer: You can examine the url through several Request fields:

Imagine your application is listening on the following application root:
http://www.example.com/myapplication

And a user requests the following URI:
http://www.example.com/myapplication/foo/page.html?x=y

In this case the values of the above mentioned attributes would be the following:
    path             /foo/page.html
    full_path        /foo/page.html?x=y
    script_root      /myapplication
    base_url         http://www.example.com/myapplication/foo/page.html
    url              http://www.example.com/myapplication/foo/page.html?x=y
    url_root         http://www.example.com/myapplication/

You can easily extract the host part with the appropriate splits.
An example of using this:
from flask import request

@app.route('/')
def index():
    return request.base_url

Comment: new to Flask, i didn't know where request object come from and how it works, here it is: http://flask.pocoo.org/docs/0.12/reqcontext/
Comment: url_root returns `http://www.example.com/` not `http://www.example.com/myapplication/`

base_url returns `http://www.example.com/myapplication/`
Comment: my app route is like @app.route('/index//') how can i guest path from request without variables. I expect **/index** in result. Which flask function to use?
Answer: another example:
request:
curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:
request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

Comment: For people who want to use `request.full_path`, suggest to use `request.environ['RAW_URI']` instead. Because, when the actual full query path is `/alert/dingding/test`, `request.full_path` returns `/alert/dingding/test?`, an extra question mark will be added to the result, which might not be desirable.
Comment: what is the different flask "host_url" "root_url" "url_root"?
Comment: **request.remote_addr** for 127.0.0.1
Comment: request.query_string
Answer: you should try:
request.url

It suppose to work always, even on localhost (just did it).
Comment: what is the different flask "host_url" "root_url" "url_root"?
Answer: If you are using Python, I would suggest by exploring the request object:
dir(request)
Since the object support the method dict:
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

Comment: what is the different flask "host_url" "root_url" "url_root"?
Answer: if user requests the following URI:
http://www.example.com/myapplication/foo/page.html?x=y

and the user wants y
you can use
request.args.get("x")


How can I call a rust function from R that returns Vec>?

Question: I have implemented a function for sampling from M different normal distributions N times in Rust because my R code was too slow. It is also parallelized. Here is the pure Rust code:
    use rand_distr::{Normal, Distribution};
    use rayon::prelude::*;

    fn rust_rprednorm(n: i32, means: Vec<f64>, sds: Vec<f64>) -> Vec<Vec<f64>> {

        let mut preds = vec![vec![0.0; n as usize]; means.len()];

        preds.par_iter_mut().enumerate().for_each(|(i, e)| {
            let mut rng = rand::thread_rng();
            (0..n).into_iter().for_each(|j| {
                let normal = Normal::new(means[i], sds[i]).unwrap();
                e[j as usize] = normal.sample(&mut rng);
            })
        });

        preds
    }

Which I am trying to call from R using the rextendr library. The code is inside a utils.R file I import using source():
code <- r"(
    use rand_distr::{Normal, Distribution};
    use rayon::prelude::*;

    #[extendr]
    fn rust_rprednorm(n: i32, means: Vec<f64>, sds: Vec<f64>) -> Vec<Vec<f64>> {

        let mut preds = vec![vec![0.0; n as usize]; means.len()];

        preds.par_iter_mut().enumerate().for_each(|(i, e)| {
            let mut rng = rand::thread_rng();
            (0..n).into_iter().for_each(|j| {
                let normal = Normal::new(means[i], sds[i]).unwrap();
                e[j as usize] = normal.sample(&mut rng);
            })
        });

        preds
    }
)"

rust_source(code = code, dependencies = list(`rand` = "0.8.5", `rand_distr` ="0.4.3", `rayon` = "1.6.1"))

The error is:
Error in `invoke_cargo()`:
! Rust code could not be compiled successfully. Aborting.
✖ error[E0277]: the trait bound `Robj: From<Vec<Vec<f64>>>` is not satisfied
 --> src\lib.rs:6:5
  |
6 |     #[extendr]
  |     ^^^^^^^^^^ the trait `From<Vec<Vec<f64>>>` is not implemented for `Robj`
  |
  = help: the following other types implement trait `From<T>`:
            <Robj as From<&'a [T]>>
            <Robj as From<&Altrep>>
            <Robj as From<&Primitive>>
            <Robj as From<&Robj>>
            <Robj as From<&Vec<T>>>
            <Robj as From<&extendr_api::Complexes>>
            <Robj as From<&extendr_api::Doubles>>
            <Robj as From<&extendr_api::Environment>>
          and 71 others
  = note: this error originates in the attribute macro `extendr` (in Nightly builds, run with -Z macro-backtrace for more info)
✖ error: aborting due to previous error
Traceback:

1. source("inla_predictive_distribution_utils.R")
2. withVisible(eval(ei, envir))
3. eval(ei, envir)
4. eval(ei, envir)
5. rust_source(code = code, dependencies = list(rand = "0.8.5",
 .     rand_distr = "0.4.3", rayon = "1.6.1"))
6. invoke_cargo(toolchain = toolchain, specific_target = specific_target,
 .     dir = dir, profile = profile, quiet = quiet, use_rtools = use_rtools)
7. check_cargo_output(compilation_result, message_buffer, tty_has_colors(),
 .     quiet)
8. ui_throw("Rust code could not be compiled successfully. Aborting.",
 .     error_messages, call = call, glue_open = "{<{", glue_close = "}>}")
9. withr::with_options(list(warning.length = message_limit_bytes),
 .     rlang::abort(message, class = "rextendr_error", call = call))
10. force(code)
11. rlang::abort(message, class = "rextendr_error", call = call)
12. signal_abort(cnd, .file)

I figured a nested vector would be supported since a regular vector is, but it appears not, do I need to implement this trait for Robj, or is there another way to go about it? I am also not sure if this is the recommended way to call Rust code from R.
Comment: You wouldn't be able to implement Robj for Vec anyway.
Comment: The error lists some impls, just take a `& mut [f64]` for means and sds, as you don't seem to ever add or remove elements from them.
Comment: @IvanC Thanks for your help. I tried changing the parameter types to &mut [f64], but to no avail. I think the issue is the return type needs to be something that Robj has a From trait for. My end goal is to have a dataframe/matrix where a row represents a distribution and columns are the n sample from it, but I figured there may not beconversions from polars/ndarray or some similar library to R's matrix/data.frame/data.table. Hence why I went with nested vectors as I figured they would be implemented
Answer: You cannot return something like Vec<Vec<T>> because R does not really understand such things. I suspect that your best options are

Some sort of a 2d matrix if the output is rectangular

There is an Rmatrix type just for that
There is limited support for ndarray, which is also translated into R matrix

A List containing Vec<T> elements if the output is a jagged array
Answer: As noted by Ilia, you cannot return a Vec<Vec<f64>> to R. As your code creates a matrix, you can use extendr_api::wrapper::matrix::RMatrix:
code <- r"(
    use rand_distr::{Normal, Distribution};
    use rayon::prelude::*;

    #[extendr]
    fn rust_rprednorm(n: i32, means: Vec<f64>, sds: Vec<f64>) -> RArray<f64, [usize; 2]> {
        let mut preds = vec![vec![0.0; n as usize]; means.len()];

        preds.par_iter_mut().enumerate().for_each(|(i, e)| {
            let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
            (0..n).into_iter().for_each(|j| {
                let normal: Normal<f64> = Normal::new(means[i], sds[i]).unwrap();
                e[j as usize] = normal.sample(&mut rng);
            })
        });
        let matrix = RArray::new_matrix(means.len() as usize, n as usize, |r, c| preds[r][c]);
        matrix
    }
)"
rextendr::rust_source(code = code, dependencies = list(`rand` = "0.8.5", `rand_distr` ="0.4.3", `rayon` = "1.6.1"))

This can be then called as follows:
rust_rprednorm(n = 6, means = c(1,2,3), sds = c(4,5,6))
#           [,1]       [,2]      [,3]      [,4]      [,5]        [,6]
# [1,]  5.068423  3.2048321 -2.669690  0.191781 -2.666059 -11.9706997
# [2,] -1.470927  0.4335488  3.394352  0.242292 -2.040637   3.1623452
# [3,]  6.802815 -3.2444519  7.862181 10.063047  9.297888   0.7607057


Daylight saving hours in Golang

Question: I have been designing a UI for a scheduling interface, where a user can set timers a number of hours into the future. I want to be able to handle daylight saving if possible, I thought it would be quite simple. Whilst checking out time.Time in the golang packages I ran into the following inconsistency, if that is what it is.
package main

import (
   "fmt"
   "time"
)

    func main(){
        const timeFormat = "2 Jan, 2006 3:04pm (MST)"
        test , err := time.Parse( timeFormat, "25 Oct, 2015 1:59am (BST)" )
        fmt.Println( test , test.UTC() , err)
        dur , _ := time.ParseDuration( "1m" )
        test = test.Add( dur )
        fmt.Println( test , test.UTC())

        fmt.Println( "--------------------"  )

        test , err = time.Parse( timeFormat, "25 Oct, 2015 2:01am (BST)" )
        fmt.Println( test , test.UTC() , err)
        test = test.Add( dur )
        fmt.Println( test , test.UTC())

        test = test.Sub( dur )
        fmt.Println( test , test.UTC())
     }

I know that 2am on the 25 Oct 2015 in BST will should cause the clock to go back to 1am GMT (UTC). If I increment 1:59am BST by one minute the time does indeed switch to GMT.
2015-10-25 01:59:00 +0100 BST 2015-10-25 00:59:00 +0000 UTC <nil>
2015-10-25 01:00:00 +0000 GMT 2015-10-25 01:00:00 +0000 UTC
--------------------
2015-10-25 02:01:00 +0000 BST 2015-10-25 02:01:00 +0000 UTC <nil>
2015-10-25 02:02:00 +0000 BST 2015-10-25 02:02:00 +0000 UTC

However if I parse a time after 2am in BST I would expect it to switch to GMT just as incrementing the time over the transition would have. In case the transitional code was called by the Add routine I add a minute again but this also does not revert the time to GMT.
I would have expected one of the following to occur
a) for BST to always remain GMT+1
b) to any time where BST is "invalid" to automatically change to the correct GMT time (invalid BST is between 2am after the last Sunday in October and 2am after the last Sunday in March the following year)
c) an error to be thrown if a date is created within those dates with BST (and perhaps other daylight saving hours in other countries).
Otherwise I'll have to check if a user enters a date in BST whether that date lies outside BST and adjust or force users to UTC times, which kind of defeats the object of having daylight saving functions built into the library.
Whilst researching I spotted this https://www.youtube.com/watch?v=-5wpm-gesOY
and have decided it is definitely not as simple as I had at first assumed...
Any insight or a better way to handle daylight saving times would be appreciated.
Using go version 1.0.2 on Debian Wheezy
Edited: retried using go version 1.3.3
and got this output
2015-10-25 01:59:00 +0100 BST 2015-10-25 00:59:00 +0000 UTC <nil>
2015-10-25 01:00:00 +0000 GMT 2015-10-25 01:00:00 +0000 UTC
--------------------
2015-10-25 01:00:00 +0000 GMT 2015-10-25 01:00:00 +0000 UTC <nil>
2015-10-25 01:01:00 +0000 GMT 2015-10-25 01:01:00 +0000 UTC

So appears to work as I expected in later versions...
Have also found this question
Daylight saving time and time zone best practices
So will be giving it a thorough read.
Thanks.
Comment: First, use a current version (go1.4.2) of Go: [Getting Started](http://golang.org/doc/install).
Comment: I'd say using a more recent version of Go is the only answer, since times and calendars are a pretty hard problem in general, and we should prefer to use standard library functions over writing our own.
Comment: `test.Sub( dur )` isn't legal, you probably meant `test.Add(-dur)`. A working [playground](http://play.golang.org/) link is helpful when including Go code. (Side note, use `dur := time.Minute` or `dur := 60 * time.Second`, etc rather than `time.ParseDuration` with constants).
Comment: your right. the test.Sub call got yoinked in my cutting and pasting wasn't supposed to be there...Thanks
Comment: thanks guys just checked with go 1.3.3 (also installed on my system  but debian still set up to use 1.0.2 by default) - as per my edit. Will be trying 1.4 and purge al the old versions. Thanks again.
Answer: Go, like everybody else but Microsoft, uses the IANA Time Zone Database which has regular updates that are included in the current Go release.
You used go1.0.3 which was released in March 2012 (Release History). The British time zone data for 2015 was added later.
ALWAYS use a current version of Go for time zone calculations.
Comment: Go uses data in the IANA format, but the bundled version that is (possibly) found at runtime is the last choice after trying environment and standard locations in the OS.

Daylight saving hours in Golang


REST Api - Created resource redirect

Question: I'm building REST API, and when resource is created normally I return HTTP 201 Created along with Location header to specify where that resource is located. But from some reason http client is not redirecting.
I'm using Postman for this. Does anyone have idea on this problem?
Answer: In short, a Location header is not sufficient to trigger a client redirect.  It must be used in conjunction with a 3xx HTTP status code.
References:

https://en.m.wikipedia.org/wiki/HTTP_location
Redirecting with a 201 created
Comment: But It should do that
Comment: According to the [HTTP spec](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html), a 201 should not do this.  I would recommend a 303 like in the answer of the question linked in the answer above.
Comment: Its not that 201 is doing this, Location header should force redirec
Comment: Here is HTTP 1.1 Spec about 201 201 Created

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate.
Comment: Correct.  It says a Location header should be included to indicate the location of the new resource.  It does not say that the client should redirect, though.  The 3xx response specs, on the other hand, do have something to say about redirection.  See this explanation of the location header on [wikipedia](https://en.m.wikipedia.org/wiki/HTTP_location).
Answer: This is one of those things where the expectation does not meet what actually happens, and the first thing people think is "well that doesn't work properly", as has been suggested in other comments.
The Location is just a random header, and clients, such as Postman or curl or anything else need to be instructed to follow them. Most won't do this by default, as that is an unreasonable default.
YouTube for example returns a body for some responses and a Location tag too. One example would be video uploads. They respond to your original meta-data for the video is sent with a POST, and they shove a Location URL which is the endpoint to upload the video too. If clients just randomly redirected to that you'd be having a bad time.
You can use Paw to make a "sequence", which I believe will let you take values from headers to reuse. This is also possible with Runscope Ghostinspector.

REST Api - Created resource redirect