counter in loop /list/ count same vale if they are one after another (python)

Question: The idea of the program is to count life time of some structures (count same structures which are one after another) but i have problem with implementing counter or enumerate function, I don't want to count number of all. I've tried do this many ways. Now I am stuck.
struct=[1, 2, 2, 2, 3, 3, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1,] #input list of structures
list1=[] #list of lifetimes for struct 1

for i in range (0, len(struct)-1):
    a=struct[i-1]
    b=struct[i]
    c=struct[i+1]
    if a!=1 and b==1 and c!=1: # if it is one separated record
        list1.append(1)
    if a!=1 and b==1 and c==1: # for first record in sequence
        list1.append('f')
    if a==1 and b==1 and c==1: # for middle record in sequence
        list1.append('m')
    if a==1 and b==1 and c!=1: # for last record in sequence
        list1.append('l')

print (list1)

it gives me:     [1, 1, 'f', 'm', 'm', 'l', 'f', 'l']
could you give me any advise how to implement counter  ?
 for example ['f', 'm', 'm', 'l] (firs/middle/middle/last) is given from [1, 1, 1, 1] from the list of structure so it's 4 records
to get [1, 1, 4, 2]
Sorry, for my non programming language, I am beginner in this field.
I've search any similar questions but couldn't find.
Comment: Why are you appending letters to your list if you want only numbers in the output?
Comment: What are we counting?  None of this makes any sense.
Comment: Should all lines after `for i in range (0, len(struct)-1):` and before `print (list1)` be indented?
Comment: Why are you appending, 'f', 'm', and 'l'? How are you expecting appending just 1, 'f', 'm', and 'l' to a list to give you a list that has a 2 and a 4 in it? And what is the meaning of [1, 1, 4, 2] with respect to this list anyway?
Comment: bad copy paste, they are all in for loop, if i clearly understand you
Comment: a was appending letters to find if I can print out at least the duration of life time. because when i was utilizing counter i was gettin number of all present structures
Comment: I want to count the numer of 1 (structure1) but only in case when the are one after another)
my mistake, maybe my explanations are not so clear.
Comment: Can you please edit your question to explain why [1, 1, 4, 2] is your desired output from this list?
Comment: if we have [f, m, m, l] it gives us 4 records, [f,l] - 2 records
Comment: @jgritty He wants a list of group lengths for each group of consecutive `1`s in the list.
Comment: @augurar Exactly, that's what she want
Comment: Please don't use `struct` as namespace, this is a shadow name of Python builtin module
Comment: Ok, did't know. As a chemist I am using it as a basic word. Thank you for all advises! And being patient for my faux pas'es
Answer: Is it something like this, you're looking for?
inlist = [1, 2, 2, 2, 3, 3, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1,]
#         1                 1        1--2--3--4     1--2
def lifetime(num):
    output = []
    count = 0
    for x in inlist:
        if x == num:
            count += 1
        else:
            if count != 0:
                output.append(count)
                count = 0
    if count != 0:
        output.append(count)

    print output

lifetime(1)
lifetime(2)
lifetime(3)

Output:
[1, 1, 4, 2]
[3, 1, 1]
[2, 1]

Comment: as @augurar said I need list of group lengths for each group of consecutive 1s in the list
Comment: YES! Thank you! Sorry for bothering in such a trivial case!
Answer: You can use itertools.groupby() to group the list by value, then return the counts for each group with a given value:
from itertools import groupby

def ilen(iterable):
    """ Return the length of an iterable """
    return sum(1 for _ in iterable)

def lifetime(num, lst):
    """ Return a list of counts for each group of num in lst """
    return [ilen(g) for k, g in groupby(lst) if k==1]

Example:
>>> inlist = [1, 2, 2, 2, 3, 3, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1,]
>>> lifetime(1, inlist)
[1, 1, 4, 2]


How to get the smallest number in a Table with Lua

Question: I'm not great at programming and new to Lua. Can someone help explain the logic of what I should be doing as simply as possible, please? I have a Table populated with values and need to return the min number, in this case -9. I know I need to use the math.min, but am not sure how to use it correctly. This is a simplified version of the code I'm working with but trying to figure out the basics so I can hopefully do the rest myself. Any help is appreciated. Thank you.
e.g.:
local test_1 = {2, 7, -9, 0, 27, 36, 16}

function min()
    print(math.min(test_1))
end

min()

Answer: kikito's solution is limited. It will fail for big tables with many thousand elements as Lua cannot unpack too many values.
Here's the straight forward solution. Traverse over the table and remember the smallest value.
local min = math.huge
for i = 1, #test_1  do
  min = min < test_1[i] and min or test_1[i]
end
print(min)

A bit slower due to function calls
for i,v in ipairs(test_1) do
  min = math.min(min, v)
end
print(min)

Also possible but slow, sort the table ascending. your first element is the minimum.
table.sort(test_1)
print(test_1[1])

Comment: In big tables, you can call math.min on *slices* given by table.unpack, which accepts start and end indices.
Comment: @lhf thx I always forget about that. is there any performance gain vs plain iteration? I want something in return for more complex code :)
Comment: I don't know. I haven't done any benchmarks
Answer: print(math.min(unpack({2,7,-9,27,36,16})))

Explanation:
math.min accepts variadic arguments - if you give it n arguments it will give you the smallest one:
print(math.min(3,2,1))        -- prints 1
print(math.min(3,2,1,0,-1,-2) -- prints -2

In Lua you can have "freestanding coma-separated lists of expressions". Perhaps the easiest way to see them in action is when assigning multiple values to multiple variables:
local x,y,z = 1,2,3 -- 1,2,3 is a comma-separated list of values
print(x) -- prints 1

When passing parameters to a function, the parameters you pass are one of those lists of expressions.
An array-like table like {2, 7, -9, 0, 27, 36, 16} is not the same thing. Instead, it is a list of a single expression of type table. You could make a list of tables by separating them with commas. For example:
local arr1, arr2, arr3 = {2, 7, -9, 0, 27, 36, 16}, {0,1}, {5,6,7}

The unpack function (in some versions of Lua it's inside table.unpack instead) transforms an array-like table into a list of values.
local x,y,z = unpack({1,2,3})
print(x) -- 1

Combining these three things you end up with the 1-liner that I gave you at the beginning:
print(math.min(unpack({2,7,-9,27,36,16})))

EDIT: @Piglet's comment is correct. There is a limit to the number of arguments a function can accept, so my unpack-based solution will fail if the passed table has too many elements. It seems the max number of arguments depends on how you compile Lua, but in general it seems safe to assume that it will work fine for "less than 50". If your table can have more than 50 items, go with his for-based solution instead.


What is a good language to learn with PHP?

Question: I am in high school and I will be studying computer science in college. I am taking on a national website design challenge and I accepted to be the rear-end developer on the team. I have been intensely studying PHP for the past two weeks, and although it can get messy sometimes, I like this particular field of computer science.
What is a good language to learn that goes, somewhat, hand-in-hand with PHP or is useful to know with PHP? I want to start narrowing down my languages to master, as I suddenly realized you can't just pick up "Sam's Learn BlahBlah in 24 Hours" and suddenly master a language.
Stack overflow might close this question, but I do not see how, as this is not an ambiguous question and can be supplied an answer using facts, evidence and logical explanations, which deems it quite objective.
Thanks
Comment: We won't close it for the ambiguity, we'll close it because it's opinion-based. See http://stackoverflow.com/help/dont-ask
Comment: HTML and CSS. These are the absolute fundamentals of web design and development. Without at least HTML knowledge, you've probably no use for PHP.
Answer: As mentioned in the comments by Shane, HTML and CSS are definitely languages you have to know in order to be able to advance further with PHP, next to that there is JavaScript in which you can make asynchronous requests (load more content automatically when scrolling down etc)
These techniques however are not that easy to just learn and use in every situation tho (ajax / async scripting) but general javascript is quite fun and can make your page interactive.
Now if your backend software isn't limited to PHP you could choose to use either Python using the Django framework or Ruby using the Ruby on Rails framework for webdevelopment.
These are languages that aren't solely based on websites nor are specifically optimized for them but they do fine although it's better to have a framework ontop of them as I mentioned above (links)
PHP is probably, except for Python the easiest language to learn and the most loosely written - as in no strict typing on variables required etc.
Comment: If I were to choose Django as a framework, would you suggest I learn to build web apps with the framework first? Or without the framework? Career wise, would I be using frameworks (like Zend, Django, Ruby on Rails, etc..) in the future?
Comment: I would first focus on which languages are most commonly used to build websites with if that is what you want, if you are unsure of what you want then I would first do alot of raw programming (purely python - no frameworks) to get a feel for the language and to see if you like it's 'style' if you wish.

Career wise you will come across situations where framework knowledge is required but also where raw knowledge is enough.

Studying raw first gives you the edge as you can understand the inner workings of the framework and build functions yourself.
Comment: In my opinion, the frameworks have a very steep learning curve. There are about a hundred new concepts and technologies being thrown at you and it can get quite intimidating (if you try and understand it). I'd suggest starting with PHP as it is more clear what is happening and will help you understand what fundamentally happens each step of the way between a client and a server (or at least, more so than Django or Rails). That being said PHP is neither modern nor cool and can definitely be pretty ugly.
Comment: Agree, frameworks also have the downside of being out of date for a week or so after a security leak has been found in certain software etc but this however is not thing you have to account for when taking a job as a zend framework programmer or something like that ;)
Comment: http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/  Interesting article I found. But I appreciate the answers. I will continue programming in PHP, HTML and CSS, and venture out into some raw python coding, maybe some javascript, and see how I like it. So far so good. Thanks a lot! @Crazysheep


Why isn't my home.js displaying anything in the browser?

Question: I am enrolled in a full stack web development course and currently learning react on the side to build a project for a portfolio in hopes of getting into a front end web developer position.
Found this 2 year old tutorial in which I thought was a decent start to learn: https://www.youtube.com/watch?v=QwarZBtFoFA&t=700s.
I've tried and noticed the following:

The HTML doesn't show up in the browser inspect
locahost:3000 (nothing)
localhost:3000/Home (nothing)
I've followed the tutorial (rewatching if i missed any steps)
compared my code to the tutorials' repository code
started from scratch twice (for Home.js/App.js)
changed  to <Route path="/" exact component={} />
the only thing I'm getting the following error on browser (nothing on VSC):

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot
AND
No routes matched location "/Home"
I've updated and checked the version for react and says 10.2.4, haven't been able to find out whether it's version React 18 or less. How do I implement the createRoot to the existing documents I have?
T.I.A
pages/Home.js
import React from 'react';
import { Link } from 'react-router-dom';

function Home() {
    return (

Heavy Hitters Gym

WHERE YOU GET FIT

                <Link to="/Menu">
                    <button> JOIN NOW </button>
                </Link>

    );
}

export default Home;

src/App.js
import React from 'react';
import Home from './pages/Home';
import './App.css';
import Navbar from './components/Navbar';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

function App() {
  return (

      <Router>
        <Navbar />
        <Routes>
          <Route path="/" exact component={Home} />
        </Routes>
      </Router>

  );
}

export default App;

src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

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

Comment: Honestly, given you are in a course figuring this out, I'd suggest finding a different tutorial that is **not** 2 years old
Comment: As a professional react developer I highly suggest you do NOT learn through that tutorial. React has had a lot of IMPORTANT upgrades and changes in the past few years, especially with routes and security. Because of this, any tutorial before 18 will not be very useful, even small things such as how all old tutorials start such as create-react-app are no longer supported and if you take those old skills to a react developer interview, you will not bode well
Comment: _"How do I implement the createRoot"_... did you try visiting the link provided in the warning message?
Answer: About the first error message, React is complaining about you using ReactDOM.render() in the index.ts file and is asking you to use ReactDOM.createRoot(), because the ReactDOM.render() is outdated.
In the src/index.js file replace to:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

About the second error message, the "/Home" path really does not exist in your code, so this error is expected when you try to access this path.
The real problem is that inside the file src/App.js you are passing Home in the "component" prop
...
<Route path="/" exact component={Home} />
...

But the "component" prop actually expects the whole JSX Element. So you can fix it by replacing the code to this:
...
<Route path="/" exact component={<Home/>} />
...


I need to store an array of integers for configuration of a custom module - which of these is right?

Question: This is a list that is permanently recorded that should be able to change at a later time, either adding or removing items from the array at a user's discretion.
First method:
<code>variable_set('module_listOfIntegers', serialize($arrayOfInts));
</code>
Second method:
<code>$serialized = serialize($arrayOfInts);

$num_updated = db_update('module_config')
->fields(array(
  'listOfIntegers' => $serialized,
))
->condition('config_name', 'config_name, '==')
->execute();
</code>
And the final method could be creating a 2nd table with a single column where each row just holds the integer.  That seems a bit excessive for a simple array, though.
Comment: Both, depending on size of data and how frequently you need to read it. Do you have any practical problem that you face, with either of these approaches?
Answer: For saving module config settings, I use variable_set() in conjunction with the system_settings_form() function. Just also note that it and its companion variable_get() do the serialize/unserialize for you, so, there is no need for you to be doing it.
Comment: Ah!  Alrighty.  That's probably just the easiest way to go, then.  Thank you, sir.


Is it possible to integrate a greatest integer function?

Question: Is there an indefinite integral for this function ?
$$\int [x] dx$$
I know how to integrate it if it was something like this
$$\int_b ^a [x] dx$$
Comment: The downvote (with no comment) surprised me.
Comment: The function you want would be piecewise linear, so not in closed form, but you could write down a piecewise-defined expression for it.
Comment: If a function is not continuous, can it have an antiderivative?  :P
Answer: Let $\{t\}=t-[t]$ be the fractional part of $t$. Since $\{t\}$ has period $1$ and its integral over one period is
$$
\int_x^{x+1}\{t\}\,\mathrm{d}t=\frac12\tag{1}
$$
we see that
$$
\int_0^x\{t\}\,\mathrm{d}t=\frac12\{x\}^2+\frac12[x]\tag{2}
$$
because $\frac12[x]$ is the integral over the complete periods and $\frac12\{x\}^2$ is the integral over the remaining part of the last period.
Thus,
$$
\int\{t\}\,\mathrm{d}t=\frac12\{t\}^2+\frac12[t]+C\tag{3}
$$
and
$$
\begin{align}
\int[t]\,\mathrm{d}t
&=\int\left(x-\{x\}\right)\,\mathrm{d}x\\
&=\frac12x^2-\frac12\{x\}^2-\frac12[x]+C\\[3pt]
&=[x]x-\frac12[x]^2-\frac12[x]+C\tag{4}
\end{align}
$$
Here is a plot of $\color{#3F3D9A}{[x]}$ and $\color{#9A3D71}{(4)}$:

Note that for each $k\in\mathbb{Z}$, on $(k,k+1)$, the slope of $(4)$ is $k$. Since $[x]$ is not continuous at the integers, the left and right derivatives of $(4)$ do not match at the integers.
Comment: I think that's a clever but deceptive answer for a beginning calculus student. The OP  knows how to compute the corresponding definite integral and is asking about the indefinite. Is the function you wrote down differentiable at the integers? Perhaps you should add a picture and a discussion.
Comment: @EthanBolker: Since there was no context provided in the question, it was not clear this was a beginning calculus student. This is why it is important to [provide context](http://meta.math.stackexchange.com/a/9960). In any case, I have added more explanation and an illustration.
Comment: @EthanBolker: The question asks if $\lfloor x\rfloor$ has an indefinite integral, which is slightly different than asking if it has an antiderivative. The answer I gave is an indefinite integral, although it is not differentiable everywhere.
Comment: @robjohn could you give me a bit help to this similar problem if possible :) https://math.stackexchange.com/questions/4080995/integrate-int-x1-dx


Diagonalization of matrix using change of variables

Question: In linear algebra, we know that a system of equations $AX=b$ can be easily solved if $A$ is found to be of diagonal nature. If however $A$ is not diagonal but can be changed into a diagonal form by using the change of variables how can it be shown that the original system $AX=b$ and the new system $DY=z$ has indeed the same set of solutions?
Here, $X=Py$ and $Y=P^{-1}X$. Also $b=Pz$. So, $P^{-1}APY=z$ or $DY=z$
For example, if $AX=b$ is consistent in nature, then the transformed system $DY=z$ is also found to be consistent in nature. Likewise, if the original system is inconsistent, then $DY=z$ is also found to be inconsistent.
My Question is this : Is there any validity or proof for these assumptions ?
Thanks in advance guys! If this is a very basic question consider closing it but do post the link to the relevant solution.
Answer: In the square case, everything comes down to eigenvalues. In this case, suppose $A$ is similar to $D$ and $D$ is diagonal. Then:

$AX=b$ is consistent for all $b$ if and only if ...
$A$ is invertible if and only if ...
None of $A$'s eigenvalues are zero if and only if ...
None of the diagonal entries of $D$ are zero if and only if ...
The system $DY=z$ is consistent for all $z$.

When the systems are consistent, you get the correspondence of the solutions by undoing the change of variable: if $z=P^{-1}b$ and $DY=z$ then $A(PY)=b$.
In the case where $A$ is $m \times n$ with $m>n$, you can do the same thing by considering the least squares problem, because any solution to the original problem is also a solution to the least squares problem.
I'm not sure how I would handle the case $m<n$.
Comment: Can you please tell me what do you mean by saying $A$ is similar to $D$ ?


A function that can make caller return

Question: I am writing some BASH script and I want it have some error handling mechanism:
function f()
{
  command1 || { echo "command1 failed"; return 1; }
  command2 || { echo "command2 failed"; return 1; }
  command3 || { echo "command3 failed"; return 1; }
  command4 || { echo "command4 failed"; return 1; }
}

I want to make this repetitive structure more readable by defining some function:
function print_and_return()
{
  echo "$@"
  # some way to exit the caller function
}

so that I can write function f as
function f()
{
  command1 || print_and_return "command1 failed"
  command2 || print_and_return "command2 failed"
  command3 || print_and_return "command3 failed"
  command4 || print_and_return "command4 failed"
}

What's the best way to achieve this?  Thanks.
Comment: What's wrong with what you have? It works as-is.
Comment: @CodeGnome, it is not very readable.
Answer: The Problem
You want to:

Pretty up your code a bit.
DRY up the code a little.
Stop execution the first time a command fails.

One Possible Solution
You can refactor your code. For example:
print_and_return() {
  echo "command failed: $@" >&2
  return 1
}

commands=("cmd1" "cmd2" "cmd3" "cmd4")

for cmd in "${commands[@]}"; do
    { $cmd || print_and_return "$cmd"; } || break
done

Comment: This is generally a better approach than `set -e`, but the code is flawed. [You can't store a command in a variable](http://mywiki.wooledge.org/BashFAQ/050). Arrays are a good way to store commands, but not collections of commands. You're also applying word-splitting and pathname expansion to the unquoted use of `$cmd`, which is extremely likely to not do what you expect. At best, if the quoting problem wasn't there, you could run commands with no args this way. Otherwise a different solution is needed.
Answer: Maybe you can use set -e, though you have to be careful since it exits the shell:
function f()
{
    (
    set -e
    command1
    command2
    command3
    command4
    )
}

As long as the commands diagnose any problems, this function will stop when the first command fails.
Test version:
function f()
{
    (
    set -e
    true
    echo true
    true
    echo true
    false
    echo false
    true
    echo true
    )
}

echo calling function
f
echo still here

Output:
calling function
true
true
still here

NB: When I used the sequence:
echo calling function
if f
then echo still here - f passed
else echo still here - f failed
fi

Then the function behaved differently under bash 3.2.48 on Mac OS X 10.7.4:
calling function
true
true
false
true
still here - f passed

So, inventive, but not wholly reliable.
Comment: Worth noting is that `set -e` and the `ERR` trap are generally [not to be encouraged](http://mywiki.wooledge.org/BashFAQ/105). They're quirky and unreliable (except for the reliable monthly question they generate on the mailing lists).
Comment: @ormaaj: I'm a little surprised that my answer was accepted.  Your x-ref is interesting. The `set -e` mechanism works reliably in Bourne and Korn shells. If `bash` hasn't yet made up its mind how `set -e` is supposed to work, that is disappointing (the article cites differences between 4.0 and 4.1, etc).  As for `let` returning any status other than zero on success; that is a bug, IMNSHO.  It should return 0 when the expression is evaluated successfully, and non-zero on failure, triggering `set -e` action.
Comment: I think `let` works correctly. The FAQ just points out the post-increment being possibly confusing, and more importantly contrasting with `((expr))` being a "compound command" which made it an exception to the rule... in old Bashes. But yeah I'm sure it's possible to use `set -e` if you know exactly how it behaves. I've seen [clever usages](https://mailman.research.att.com/pipermail/ast-users/2012q1/003463.html). More often it's just indicative of taking a bad approach. This question is just a hard problem to solve generally - eventually it'll turn into "how to do function objects in Bash?"
Answer: Similiar to CodeGnome's solution, but without using arrays (which might not be present in every shell):
function callthem()
{
    for cmd; do # short form for "for cmd in "$@"; do"
        "$cmd" || { echo "$cmd failed." >&2; return 1; }
    done
}

function f()
{
    callthem command1 command2 command3 command4
    # or maybe even
    callthem command{1,2,3,4}
}

A function that can make caller return


Epsilon-Delta continuity definition for straight lines parallel to axes

Question: I am taking a course on real analysis online and I encountered the $\epsilon-\delta$ definition for a function to be continuous.
But I wonder if I can apply it to functions which are straight lines parallel to axes. Because if say $f(x)=2$ then $\epsilon$ will be never greater than zero, because the codomain is restricted to a single value. But in $\epsilon-\delta$ definition we check for $\epsilon>0$. So does the $\epsilon-\delta$ definition to check continuity of a function applies here?
Comment: But how? I am unable to understand. My crude understanding is for all Epsilon greater than 0 as f(x) becomes epsilon close to L there should be some delta > 0 so that x becomes delta close to x0. But here in straight line case epsilon is zero. So how do I apply the definition?
Comment: Of course the definition is correct to check the continuity of constant funcitons.
Comment: For constant funciton, say $f(x)=2$, use the definition of continuity to check its continuity at fixed point $x_0$, for any $\epsilon >0$, there exists $\delta >0$, for any $x$ such that $|x-x_0|<\delta$, we have $|f(x)-f(x_0)|=0< \epsilon$. So $f$ is continuous at $x_0$.
Comment: By the way: functions are not the same as graphs.  If $f(x) =2$ for all $x$ then the *graph* is a straight line parallel to the $x$-axis.  The corresponding property of the function is *constant*.  So your question could be better worded as "$\epsilon$-$\delta$ continuity definition for constant functions."
Answer: You have to keep in mind what $\epsilon$ is requiring the function to do.  Take a constant function $f(x) = 2$ as you asked.
The $\epsilon-\delta$ definition demands that, for any $\epsilon > 0$ we can find a $\delta >0$ so that if $x$ is within $\delta$ of $a$, $f(x)$ is within $\epsilon$ of $f(a)$  But in the case of our constant function, $f(x)=2$ and $f(a) = 2$, so $f(x)$ is within $\epsilon$ of $f(a)$ for any $\epsilon$.  Therefore any $\delta$ will do.
I think your question comes from thinking of $\epsilon$ as something that comes from the function; $\epsilon$ does not care about $f$!
Answer: Yes. It surely does. The $\epsilon$ band doesn't have to be a subset of the codomain. You can choose the value of $\epsilon > 0$ yourself. The task is to find a suitable $\delta$.


About $S$-semipermutable Hall $\pi$-subgroups and $\pi$-complements

Question: Two subgroup $A, B \le G$ are said to permute if $AB = BA$. A subgroup $H \le G$ is called $S$-semipermutable in $G$ if $H$ permutes with every Sylow $q$-subgroup of $G$ for primes $q$ not dividing $|H|$.
Theorem: Let $H$ be an $S$-semipermutable $\pi$-subgroup of $G$. Then $H^G$ contains a nilpotent $\pi$-complement, and all $\pi$-complements in $H^G$ are conjugate. Also, if $\pi$ consists of a single prime, then $H^G$ is solvable.
Corollary: If a Hall $\pi$-subgroup of $G$ is $S$-semipermutable, then $G$ contains a $\pi$-complement.
Proof: Write $M = H^G$. Then $M$ contains a $\pi$-complement $K$ by the above Theorem, and all $\pi$-complements of $M$ are conjugate. The Frattini argument thus applies, and we have $G = M N_G(K)$, so $|G : N_G(K)| = |M : N_G(K)|$ is a $\pi$-number, and so it suffices to find a $\pi$-complement in $N_G(K)$. This exists, however, since $N_G(K)$ is $\pi$-separable. To see this, observ that $K \subseteq N_M(K) \subseteq N_G(K)$ is a normal series in $N_G(K)$. Since $|K|$ is a $\pi$'-number, $|N_M(K) : K|$ is a $\pi$-number and $|N_G(K) : N_M(K)|= |G : M|$ is a $\pi'$-number, the result follows. $\square$
1) For the application of the Frattini argument, first $G$ acts on the $\pi$-complements $K$, and because by definition $H^G$ is generated by the conjugates of $H$, each conjugate of some $\pi$-complement $K$ is also in $M = H^G$. But why is the operation of $M$ on these conjugates transitive (which is necessary for the application of the Frattini argument), I guess because they are already conjugate in $M$, but this is not said in the Theoerm?
2) Why if $N_G(K)$ is $\pi$-separable, it implies that is has a $\pi$-complement in it. And why in the proof is $|N_M(K) : K|$ a $\pi$-number?
3) Where do we need that $M$ is a Hall $\pi$-subgroup?
Answer: I think you are assuming that all of the groups involved are finite, but it would be helpful if you said so, so that people do not waste time thinking about the case when $G$ is infinite.
I am not sure what your problem is with Question 1 - you seem to have answered it yourself. It is stated in both the theorem and in the proof of the corollary that all $\pi$-complements are conjugate in $M$.
For 2, you are presumably expected to know the result that a finite $\pi$-separable group has a $\pi$-complement. The proof is a straightforward induction, using the Schur-Zassenhaus Theorem. $|N_M(K):K|$ is a $\pi$-number because $K$ is a $\pi$-complement in $M$.
For 3, you use the fact that $H$ is a Hall $\pi$-subgroup to infer that $|G:M|$ is a $\pi$-number at the end of the proof.
Comment: Ok, thank you! But one last point, why in the last step we have $|N_G(K) : N_M(K)| = |G : M|$?
Comment: it holds because $G = HK$ iff $[H : H\cap K] = [G : K]$ with $G = MN_G(K)$ and $N_M(K) = M \cap N_G(K)$.


Validar e alterar senha de usuário com PHP

Question: Estou tentado fazer com que o código verificasse se as senhas são idênticas e caso fossem, salvasse no BD, mas não sei o que está errado que independente de ser idêntica ou não ele sempre salva.
 if (isset($_POST['salvar-senha'])) {

    $usr_id            = $_SESSION['usr_id'];
    $senha_atual       = md5(strip_tags($_POST['senha_atual']));
    $senha_nova        = md5(strip_tags($_POST['senha_nova']));
    $confirme_senha    = md5(strip_tags($_POST['confirme_senha']));

    $sql = mysql_query("SELECT usr_password FROM users WHERE usr_login = '$usr_id' ");
    $row = mysql_fetch_array($sql);
    $senha_banco = $row['usr_password'];

    if($senha_atual == "" && $senha_nova == "" && $confirme_senha == "") {
        echo "
            ";
    } else {
        if (($senha_atual != $senha_banco) && ($senha_nova != $confirme_senha) ) {
            echo "
            ";
        } else {
            if ($result=mysql_query("UPDATE users SET usr_password = '$confirme_senha' WHERE usr_id = '$usr_id' ")) {
                echo "
            ";
            }
        }
    }
}

Answer: Tem um erro de lógica aqui:
if (($senha_atual != $senha_banco) && ($senha_nova != $confirme_senha) )

Isso só é verdadeiro se a pessoa errar as duas coisas, ou seja, senha atual errada + senha nova e confirmação não coincidem. Em qualquer outra situação (exceto tudo em branco), a senha é gravada.
Você corrige isso considerando erro qualquer uma das duas situações (não ambas), portanto usando um OU em vez de E:
if (($senha_atual != $senha_banco) || ($senha_nova != $confirme_senha))

Você também pode pensar ao contrário: só é pra salvar se a senha atual estiver correta E as novas coincidem:
if (($senha_atual === $senha_banco) && ($senha_nova === $confirme_senha)) {
    // salva

Senão, dê uma mensagem de erro genérica (não ajude quem está tentando burlar o sistema)
} else {
    // erro: senha atual incorreta ou as novas não coincidem
}

Fora isso, o JavaScript embutido ali poderia ser substituído por redirects do próprio PHP, gravando as mensagens de erro na sessão.
Comment: Rapaz, fiz isso e agora só dá que as senhas não coincidem. Até se eu colocar as 3 iguais.
Comment: Tem certeza de que o md5 da senha atual bate com o que está no banco? Tentou imprimir os valores para confirmar?
Comment: Sim, tanto a senha atual bate com a do banco, como a nova senha e a confirmação também.
Answer: Verfique sua lógica, parece estar usando o operador lógico && (E) com a intenção da funcionalidade || (OU)
apenas troque os operadores no primeiro e segundo if
uma observação sem ser grosseiro: a frase correta é "as senhas não coincidem."
Comment: Leonardo, eu nem havia reparado nesse erro, obrigado. E a propósito, o erro no PHP agora é outro, até se as 3 senhas estiverem idênticas ele diz que elas não coincidem.


Forming probability distributions of type $W=X+Y$.

Question:
I am able to do part a) easily. My only problem here is finding the prob. distribution for $w=x+y$. If I could get that, I can solve c) also. Also, will it be the same case for $w=x-y$? Theres a similar question asking to find for $x-y$, but I'm guessing its the same case, so if I just know $x+y$, should be ok. So I just need answer for part (b).
Answer: You can probably see that the possible values of $X+Y$ are $0,2,4,6,8,10$.
Call $X+Y$ by some name, like $W$. We want to find $\Pr(W=w)$ for $w=0,2,4,\dots,10$.
Unfortunately we have to do them one at a time.
What is $\Pr(W=0)$? This happens only if $X=0$ and $Y=0$. By independence, the probability of this is $(0.3)(0.4)=0.12$.
One down, quite a few to go.
What is the probability that $W=2$? This can happen in two ways, $X=0$, $Y=2$ or $X=2$, $Y=0$. So the probability is $(0.3)(0.2)+(0.4)(0.2)$.
Continue. Note that for $W=4$ there will be three different ways, for $6$ there will be also three  ways, but then things get easier.
It will be easy to make a numerical slip or two. Note that $6$ numbers we get should add up to $1$. That gives a check on your calculations.
Answer: Only to expand on the previous answer, the probability distribution of the sum of two independent discrete random variables (like this) is actually the discrete convolution of the two probability mass functions. When writing the formula out:
$$\Pr(X+Y=w) = \sum_{k=-\infty}^{\infty} \Pr(X=w-k) \times \Pr(Y=k)$$
And for your other question about distribution for $X-Y$, the resultant mass function is the (discrete) cross-correlation:
$$\Pr(X-Y=w) = \sum_{k=-\infty}^{\infty} \Pr(X=w+k) \times \Pr(Y=k)$$


Test for equality of quadratic extensions

Question: Please verrify for correctness. And I don't know where the assumption of having characteristic $\not = 2$ is used, please comment.
Lemma:
Let $F$ be a field with characteristic $\not = 2$, $a, b \in F$, and $\sqrt{a},\sqrt{b} \not \in F$. Then $$F(\sqrt{a}) = F(\sqrt{b}) \iff \sqrt{a b} \in F.$$
Proof:
$``\leftarrow"$ Use $\sqrt{b} = \sqrt{a} \sqrt{ab}\frac{1}{a}.$
$``\rightarrow"$ $\text{Gal}(F(\sqrt{a})/F) \overset{\sim}{\rightarrow} \mathbb{Z}/2\mathbb{Z}.$ We have that $\text{Gal}(F(\sqrt{a})/F) = \{\text{Id}, \sigma \}$, with $\sigma$ the conjugation. We have the basis $\{1, \sqrt{a}\}$ for $F(\sqrt{a})/F$, hence $F(\sqrt{a}) = \{x+y\sqrt{a}\; |x,y \in F \}$, with the conjugation acting as $x+y\sqrt{a} \overset{\sigma}{\mapsto}x -y\sqrt{a}$. Hence we have that $\sigma(z) = z \iff z \in F$.
So we have $\sigma(\sqrt{a}) = - \sqrt{a}$.
Now by taking a similar route, and using the assumption, we can also have $\{1, \sqrt{b} \}$ as a basis for $F(\sqrt{a})$, and we would also have that $\sigma$ acts like $x+y\sqrt{b} \overset{\sigma}{\mapsto} x - y\sqrt{b}$.
So we have $\sigma(\sqrt{b}) = - \sqrt{b}$.
Finally: $\sigma(\sqrt{a b}) = \sqrt{ab}$.
Answer: Check for correctness
You need to be careful with $\frac1a$ when $a=0$.

Where you assumed characteristic $2$
The notation $\operatorname{Gal}(F(\sqrt a)/F)$ assumes that $F(\sqrt a)/F$ is separable, but $X^2 - a$ has derivative $0$ in characteristic $2$.
Also, in characteristic $2$ we have $\sqrt a = -\sqrt a$, so your $\sigma$ is just the identity, and it certainly is not true that $\sigma(z) = z \iff z \in F$.

Counterexample in characteristic $2$
Set $F = \Bbb F_2(t)$, then $F(\sqrt t) = F(\sqrt{t+1})$ but $\sqrt{t(t+1)} \notin F$
Comment: On you comment for the check for correctness: as we have $\sqrt{a} \not \in F$, the case $a = 0$ will not happen.


Maximum interval of existence for the ODE $\space y'=\frac{y}{x}$.

Question: ODE: $\space y'=\frac{y}{x}$
Its solution is $\space y=Cx$
Here, I think Maximum interval of existence of solution is $(-\infty,+\infty)$
Or it is $\space \mathbb{R} \setminus \{0\} \space$ (because, ODE is not defined for $\space x=0$)
Please, help me in finding right solution. (I'm confused!)
Comment: When your book / lecture notes / whatever defines "maximum interval of existence", what exact words do they use? It's very possible that the answer to your question lies there.
Comment: As lim x->b- (y)=L and b<+INF
Comment: But here should we include 0 or not plz help and state reason plz
Answer: It is not $(-\infty, \infty)$ becasue of the reason you mentioned. It cannot be $\mathbb R \setminus \{0\}$ because this set is not an interval!. The correct answer is $(0,\infty)$ or $(-\infty,0)$.
Answer: The initial value problem
$$\dot{y}=\frac{dy}{dx}=f(x),\quad y(0)=y_0,\tag{1}$$
has a unique solution $y(x)$ defined on a maximal interval of existence $(\alpha, \beta)$. Furthermore, if $\beta < \infty$ $(\alpha > -\infty)$ and if
$$\lim_{x\to \beta^-}y(x)=L\quad\left(\lim_{x\to \alpha^+}y(x)=L\right)$$
exists, then $L\in\dot{E}$, the boundary of $E$. On the other hand, if the above limit exists and $L \in E$, then $\beta = \infty, f(L) = 0$.
Theorem: Let $E$ be an open subset of $\mathbb R^n$ and assume that $f \in C^1(E)$. Then for each point $y_0 \in E$, there is a maximal interval $J$ on which the initial value problem $(1)$ has a unique solution, $y(x)$; i.e., if the initial value problem has a solution $h(x)$ on an interval $I$ then $I \subseteq J$ and $h(x) = y(x)$ for all
$x \in I$. Furthermore, the maximal interval $J$ is open; i.e., $J = (\alpha, \beta)$.
Definition (Maximal interval of existence).
The interval $(\alpha, \beta)$ in the above theorem is called the maximal interval of existence of the solution $y(x)$ of the initial value problem $(1)$ or simply the maximal interval of existence of the initial value problem $(1)$.
Corollary.
Let $E$ be an open subset of $\mathbb R^n$ and assume that $f \in C^1(E)$ and let $(\alpha, \beta)$ be the maximal interval of existence of the solution $y(x)$ of the initial value problem $(1)$. If $\beta < \infty$ $(\alpha > −\infty)$ and if
$$\lim_{x\to \beta^-}y(x)=L\quad\left(\lim_{x\to \alpha^+}y(x)=L\right),$$
then $L \in \dot{E}$.
Example. Consider
$$\dot{y}=\frac{-1}{2y},\quad y(0)=1.$$
The solution is given by
$$y(x)=\sqrt{1-x}.$$
The solution is defined on its maximal interval of existence $(\alpha, \beta) = (−\infty, 1)$. The function $f(x)=-1/(2x)\in C^{1}(E)$ where $E=(0,\infty)$ and $\dot{E}=\{0\}$. Note that
$$\lim_{x\to 1^-}y(x)=0\in\dot{E}.$$
Original Problem.
$$\dot{y}=\frac{y}{x},\quad y(0)=y_0\tag{2}.$$
Solving $(2)$ we find that $y(x)=Cx$. Using the initial condition $y(0)=y_0$ implies that $y(0)=0$ or $y_0=0$. Therefore, we have
$$\dot{y}=\frac{y}{x},\quad y(0)=0\tag{3}.$$
Thus, the maximum interval of existence is $(\alpha, \beta) \in \{(−\infty, 0),(0, \infty)\}$. The above IVP is equivalent to the autonomous system
$$\dot{y_1}=1,\quad \dot{y_2}=\frac{y_2}{y_1},$$
$$y_1(0)=0,\quad y_2(0)=0.$$
Thus $f(y_1, y_2) = (1, y_2/y_1)$ is not continuous when $y_1 = 0$. Since the initial value is $y_1(0)=0$, $f$ satisfies the condition of the theorem on $E=\{(y_1,y_2):y_1\neq 0\}$.
The solution of the given IVP is $y_1(x) = x,~ y_2(x) = Cx$, which is defined for every $x$. As $x\to 0^-$ or $x\to 0^+$, $(y_1(x),y_2(x))\to(0,0)$ which is on the boundary of $E$, $\dot{E}=\{(y_1,y_2):y_1=0\}$.
Comment: Thanks for the extremely helpful feedback @LutzLehmann. I have updated my answer.


Elasticsearch indexing timestamp-field fails

Question: I fail at indexing timestamp fields with ElasticSearch (version 7.10.2) and I do not understand why.
So I create an index with the following mapping. You can copy & paste it directly to Kibana:
PUT /my-dokumente
{
    "mappings" : {
      "properties" : {
        "aufenthalt" : {
          "properties" : {
            "aufnahme" : {
              "properties" : {
                "zeitpunkt" : {
                  "type" : "date",
                  "format": "yyyy-MM-dd HH:mm:ss",
                  "ignore_malformed": true
                }
              }
            },
            "entlassung" : {
              "properties" : {
                "zeitpunkt" : {
                  "type" : "date",
                  "format": "yyyy-MM-dd HH:mm:ss",
                  "ignore_malformed": true
                }
              }
            }
          }
        }
      }
    }
}

Then I try to index a document:
PUT /my-dokumente/dokumente/1165963
{
    "aufenthalt" :
    {
        "aufnahme" :
        {
            "zeitpunkt" : "2019-08-18 15:02:13"
        },
        "entlassung" :
        {
            "zeitpunkt" : "2019-08-20 10:29:22"
        }
    }
}

Now, i get this error:
"mapper [aufenthalt.entlassung.zeitpunkt] cannot be changed from type [date] to [text]

Why is elastic search not parsing my date?
I also tried with many different mapping settings like strict_date_hour_minute_second or to send the timestamp as "2019-08-18T15:02:13" or "2019-08-18T15:02:13Z" also, I converted it to epoch millis, but I always get some different error message, for example Cannot update parameter [format] from [strict_date_hour_minute_second] to [strict_date_optional_time||epoch_millis].
So the basic question is just: How can I send a timestamp value to ElasicSearch? (with Kibana/CURL).
PS: I am not using a Client SDK like Java High Level Rest Client. Why are talking about basic Kibana/CURL.
It can't be that complicated. What am I missing?
Thank you!
Answer: Mapping types are removed in 7.x. Refer to this official documentation
You need to add _doc in URL when indexing a document to Elasticsearch
Modify the URL as PUT /my-dokumente/_doc
Comment: Oh my god. I was looking at the wrong place all the time. Thank you so much!!!


Why is it so hard to convert PDF to plain text?

Question: I needed to convert some PDF back to text. I tried many soft and online tools and result was always mediocre.
Why is it so difficult technically speaking ?
Comment: Depends on whether you are working with scanned document images or a document that was generated by a program directly. If it is scanned then the classic OCR issues come into play. If it was directly then it is due to the PDF format which is rather complex. If you are trying to write a PDF->text conversion program then provide more specifics. If you are looking for a utility then this is not the appropriate forum to ask as this is for programming issues.
Comment: The PDF format is *not **designed*** to be able to reliably copy text out of it. Some features make it difficult, others make it virtually impossible. Success or failure mainly depends on the software that a PDF was created with.
Comment: I am not looking for a specific software, I was just wondering why there aren't any good ones.
Answer: Let's not assume you are talking about PDFs which merely wrap some bitmap image because it should be clear that in that case you can only resort to OCR with all its restrictions.
Let's instead assume that text is drawn in the PDF at hand.
What is drawn on a PDF page is determined by a sequence of instructions in the content stream of that page. "Text is drawn" on a page means that among those instructions there are some setting the font to use by the instructions to come, some setting the text position and direction to use by the instructions to come, and some actually drawing text given by "string arguments".
Text extraction is the task of taking the sequence of instructions from a content stream and instead of drawing the text as indicated by the font and position setting instructions, to export it in a sensible order using a standard encoding, usually the encoding of the character type of the used programming language / platform.
The first problem is to understand the encoding of the string arguments of those text drawing instructions:

each font can have its own encoding; to extract the text one cannot simply ignore everything but the instructions drawing text and concatenate their string contents, you always have to take the current font into account (some extremely simple text extractors ignore this and, therefore, fail pretty often to return something sensible);
there are a large number of predefined encodings, some reminding of encodings you know, e.g. WinAnsiEncoding, many you likely don't know, e.g. Add-RKSJ-H; these encodings may use a constant number of bytes per glyph or they may be mixed-multibyte; so a text extractor must support very many encodings to start with;
encodings also may be completely ad-hoc and arbitrary; in particular in case of embedded subset fonts one often sees ad-hoc encodings generated by dealing out character codes from some starting value whenever one is needed; i.e. the first glyph in a given font used on a page is given the starting value as code, the next, different glyph is given the starting value plus one, the next, different one the starting value plus two, etc; "Hello World" and a starting value of 48 (ASCII value of '0') would result in "01223453627"; these fonts may contain a mapping to Unicode but they are not required to.

The next problem is to make sense out of the order of the strings:

the string drawing instructions may occur in an arbitrary order, e.g "Hello" might be drawn "lo" first, then after moving back "el", then after again moving back "H"; to extract the text one cannot ignore text positioning instructions and simply concatenate text strings, you always have to take the current position into account (some simple text extractors ignore this and, therefore, can fail to return something sensible);
multi-columnar text may present a difficulty, text may be drawn line by line, e.g. first the text of the top line of the first column, then the top line of the second column, then the second line of the first column, then the second line of the second column, etc.; there need not be any hints in the PDF that the text is multi-columnar.

Another problem is to recognize formatting or styling artifacts:

spaces between words need not be created by drawing a space glyph, it may also be done by text position changing instructions; text extractors not trying to recognize gaps created by text positioning instructions may return a result without spaces; on the other hand the same technique can be used to draw adjacent glyphs at an optimal distance, aka kerning; text extractors trying to recognize gaps created by text positioning instructions may falsely return spaces where there should be none;
sometimes selected words are printed s p a c e d o u t for extra emphasis; in the extracted text these gaps might be presented as space characters which automatic postprocessing of the text may see as word separators;
usually for bold text one uses a different, bold font program; if that is not at hand, people sometimes get creative and emulate bold by printing the same text twice with a minute offset; with a slightly larger offset (or a different transformation) and a different color a shadow effect can be emulated; if the text extractor does not try to recognize this, you end up having some duplicate characters in the output.

More problems arise due to incomplete or wrong extra information:

ToUnicode maps of fonts (optional maps from character code to Unicode) may be incomplete or contain errors; there e.g. are many questions here on stack overflow dealing with incorrect ToUnicode maps for Indian writings; the text extraction results reflect these errors;
there even are PDFs with contradictory information, e.g. with an error in the ToUnicode map but the correct information in an ActualText entry; this is used by some PDF creators to allow correct copy&paste from some programs (preferring an ActualText entry in such a situation) while injecting errors in the output of other programs (preferring ToUnicode information then).

Yet another problem arises if you expect the text extractor to extract only text eventually visible in the page:

text may be drawn outside the current clipping area or outside the visible page area; text extractors need to keep these in mind;
text may be drawn using the rendering mode "invisible"; text extractors have to keep an eye on the rendering mode;
text may be drawn using the same color as the background; to recognize this, a text extractor can not only look at the current instruction and a few graphics state details, it has to take into account anything drawn beforehand in the location of the text;
text may be drawn as a clip path; to recognize whether this text is visible in the end, a text extractor must keep track of what is drawn in the text area as long as the clip path is active;
text may be covered by something else later; a text extractor must drop recognized text in such a case; but depending on blend modes and transparency settings these coverings might or might not allow the text to shine through; thus, for a correct result the text extractor must for each glyph keep track of the color its drawn with, the color of the backdrop, and what all those spiffy effects do with those colors later on; and of course, both glyph color and backdrop color can be interesting, e.g. some shading colors; and the color spaces involved may differ, requiring one to convert back and forth between color spaces; and so on.

Furthermore, text may be drawn where text extractors usually don't look:

some tools hide text from text extraction by putting it into a pattern and filling the page area with that pattern;
similarly there are type 3 fonts; each character in a type 3 font is represented by its own content stream; thus, a tool can draw all text in the content stream of a single type 3 font glyph and then draw that glyph on the page.

...
You surely have meanwhile gotten an idea why text extraction results can be less than optimal. And be assured, the list above is not complete, there still are more complications for text extraction.
Comment: @Demeter I am quite familiar with the problems of text extraction, yes, but I merely have implemented specialized text extractors. Usually one merely has to deal with only some complications. OCR has its own set of complications. What is an appropriate approach, depends on the specific circumstances.
Comment: That, and the PDF might not contain any text at all, only images.
Comment: Tom, yes, bitmap or vector images, either way, not nice.
Comment: thanks @mkl that's a very good answer. You seem pretty familiar with the subject and you probably wrote such extractor. If I had to do it myself, after what you stated, I seems "easier" to rely 100% on OCR (maybe helped with some extracted text). What do you think ?


Finish cracks between sides and back?

Question: I recently bought a seven year old used mandolin online. It has edge binding where the sides meet the top but not the back. Where the sides meet the back, the finish has little cracks along that seam, almost the entire way around the instrument. There are links to pictures below.
Is this normal? Expected? It seems unexpected to me but maybe I've never looked that closely at an acoustic instrument that didn't have binding along both edges.
Comment: I'm not an expert. From what I know, seems like humidity might not have been controlled enough and the back and sides swelled or shrank differently and cracked the finish from the inside. But that's just a guess
Answer: First: don't just rely on strangers with photos; take it to an expert! They could spot all kinds of stuff and tell you what to do about it if anything.
But I'll say that it looks to me more like "scuffs" or "gouges" than cracks. They certainly don't look to me like cracks that go all the way through the wood; that would be a big deal, but "crazing" in a finish is just aesthetic, and any gouges might detract from value and appeal but shouldn't matter to the sound. From the first picture I was going to guess it was caused by a shoulder strap, but you say it's all the way around.
But again, take it in to somebody who knows what they're doing! No matter what you see, a "checkup" is in order when getting a new instrument.
Comment: I agree that it needs to be seen in person by a luthier.  To me it looks like cracks occurring at the glue joint between sides and back, as if the back were squeezed inward and those joints stressed.

Finish cracks between sides and back?


Não consigo perceber qual a causa deste erro

Question: Estou a fazer um projecto em python do jogo quatro em linha e tenho a função valor que me diz qual o valor que esta colocado num certo ponto da tabela.
grelha = [[0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0]]
fim = False
vencedor = None
jogador = 1
linha_vitoria = None
jogo = (grelha, fim, vencedor, jogador, linha_vitoria)

def valor(jogo, linha, coluna):
'valor'
##    grelha = jogo[0]
##    jogador_1 = 1
##    jogador_2 = 2
##    valor = 0
##
##    if grelha[linha][coluna] == 1:
##        valor = 1
##    elif grelha[linha][coluna] == jogador_2:
##        valor = 2
##    else:
##        valor = 0
##
##    return valor

    linha = linha - 1
    coluna = coluna - 1

    grelha = jogo[0]

    return grelha[linha][coluna]

Depois tenho o modo gráfico que vai usar o pygame para criar o gráfico do jogo e uso a função valor para obter numa dada posição da tabela qual peça colocar se amarela ou vermelha.
def construir_frame_jogo():

    # a frame de jogo é sempre construída para o jogador humano. O
    # computador joga imediatamente a seguir ao jogador humano no
    # evento da jogada do jogador humano.

    global nova_frame

    # criar uma nova frame
    nova_frame = pygame.Surface(tamanho)

    # cor de fundo
    nova_frame.fill(cor_fundo)

    linha        = 1
    coluna_mouse = get_coluna_mouse()
    peca         = ordem_escolhida
    if ha_espaco(jogo, coluna_mouse):
        desenha_peca_jogo(linha, coluna_mouse, peca)

    for l in range(6):
        for c in range(7):

            peca = valor(jogo, l+1, c+1)
            desenha_peca_jogo(l+1+1, c+1, peca)

    # processar jogada
    if mouse_click == True:
        processar_jogada()

Mas quando corro o código dá-me o seguinte erro e não consigo perceber porque.
Obrigado pela atenção.
Comment: Não consegui reparar onde você definiu o objeto `jogo`
Comment: Já coloquei a o jogo
Answer: O seu erro:
 return grelha[linha][coluna]
 TypeError: 'int' object is not subscriptable

Indica que nesta linha está tentando acessar um elemento contido dentro de um objeto int, como se ele fosse uma lista. Como ele não é lista, retorna esse erro.
Isso só deixa duas possibilidades: ou grelha é int (e você está tentando acessar o [linha] nele)  ou grelha[linha] é int (e você está tentando acessar o [coluna] nele.
Da forma que foi definido, no pedaço de código que você colou, grelha é jogo[0]:
grelha = jogo[0]

E jogo[0] é a lista de listas:
grelha = [[0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0]]
jogo = (grelha, fim, vencedor, jogador, linha_vitoria)

Logo, não deveria dar esse erro. Eu não consigo reproduzi-lo aqui. Ao tentar rodar um código parecido com o seu, completando o que falta, funciona perfeitamente aqui.
A única explicação é que, na parte do código que você omitiu da pergunta, tem alguma redefinição ou modificação de alguma dessas variáveis, que estaria colocando/passando um objeto do tipo int no lugar da lista.
Caso não consiga achar o problema com a explicação acima, edite a sua pergunta e acrescente um MCVE; Isso vai permitir que eu possa testar aqui e encontrar o problema.


Zabbix triggers during network problems

Question: I have a office zabbix server that is monitoring several distant servers. Most of the checks are via agents. When there are network problems in the office where zabbix server resides, I get lots of problem notifications (after restoring connection of course) of all services on all of the monitored servers. How can I disable triggers when there is no network connection on zabbix server? It comes to my mind to create trigger that is fired when it's not possible to ping google.com and to set it as action contidion, but would that be the most elegant way?
Answer: Think you should use an external check to ping multiple hosts, create a trigger on that and make your other triggers depends on that one.
maybe this one is a good starting point for you:
https://github.com/UnsignedLong/zabbix-pingcheck
Comment: Well, that's pretty much what I think I'll do. Guess there is no some inbuild way of checking network connection.

Zabbix triggers during network problems


Atualizar página quando usuário estiver ausente e não houver vídeos na página

Question: Preciso atualizar a página do meu site quando o usuário ficar inativo por 15 minutos e quando não houver vídeos incorporados na mesma.
se o usuário ficar inativo em uma página do site por 15 minutos a página deverá ser atualizada, mas não pode atualizar se a página possuir algum vídeo do youtube incorporado.
Sempre que houver um vídeo incorporado ele usará este código:

Comment: Sabemos se há video caso haja ou não algum iframe na página?
Comment: @Miguei sim, sempre que houver iframe será algum vídeo, caso tenha sido essa a pergunta :)
Comment: Foi sim, coloquei uma maneira em baixo, mas é com javascript/jquery, só com html/php não dá para fazer isso.
Answer: Só com php/html não dá para fazer isso, mas aqui está um exemplo de fazer com javascript/jquery:

Exemplo adapatado daqui
Caso não fosse preciso detetar alguma atividade na página bastaria no head do teu html:
<meta http-equiv="refresh" content="900">

Em que content é o número de segundos antes do refresh
Comment: desculpe a ignorância, estou começando a trabalhar com isso agora, mas fiz o seguinte http://i.imgur.com/8m6DJde.png e parece que não atualiza a página. Tentei modificar para atualizar a cada 10 segundos para ver se funciona, mas nada acontece. Fiz algo errado?
Comment: Vou ver se algo se passa, confesso que não testei @talnun. É importante estares a importar o jquery, mas eu vou testar rápido
Comment: @talnun acabei de testar, funcionou tudo ok, muda para `setInterval(timerIncrement, 100);` para testar, não te esqueças que estamos a trabalhar com milisegundos
Comment: Repara aqui a funcionar @talnun: https://jsfiddle.net/eeuqq7ux/
Comment: realmente faltava importar o jquery, funcionou como esperado. Gratidão.


Can a large stadium impact college basketball players' shooting?

Question: In the later stages of the NCAA Tournament (the Final Four, and possibly Elite Eight and Sweet Sixteen), the games are usually played in large stadiums to accommodate a huge number of fans.
Sometimes during these games, certain players (or even entire teams) have very bad shooting performances.  Often times people and commentators will say it's because the players aren't used to shooting in such large arenas. They frequently cite depth-perception problems as a result of the wide-open feel of the basketball court.
Is this true?  Can a large stadium really cause depth-perception or other problems that would impact a player's shooting?  I would imagine that most of these players grew up playing on outdoor courts, so I don't know why a wide-open feel would have any impact on them.
Comment: Are you sure it's the space? Or the 10,000 eyes staring at you.
Comment: Though I'm intrigued at the distinction @Shane makes between 'stadium' and 'arena'.  Is there an official difference?  I thought the words were used interchangeably.
Comment: @corsiKa Good question.  But I've heard announcers and others talk about the wide open space causing depth perception problems, and I was wondering if there was any validity to it.
Comment: There's also a distinction to be made between stadiums and large arenas. The Final Four, in particular, was played in a stadium last year and will be this year, also. The commentators indeed suggested that the amount of space between the backboard and crowd (which you don't generally have even in large arenas) made depth perception trickier for shooters. I doubt we have a large enough sample size to really say anything conclusive, but it certainly seems a reasonable conjecture, and probably one that the players echoed.
Comment: Sounds to me like announcer-talk and unlikely to be relevant. Most of these guys aren't using their eyes to shoot, anyway, they're using muscle memory, so as long as the basket's still the same distance away they're good.  Jitters from stress and crowd noise seem more relevant to me.
Comment: @Joe Not just announcers, here's a [NY Times article](http://www.nytimes.com/2015/03/30/sports/ncaabasketball/vast-stadium-falls-silent-except-for-clangs.html?_r=0) talking about it.  It even has a link to a [Ken Pomeroy statistical analysis](http://kenpom.com/blog/index.php/weblog/entry/the_nrg_effect) in which he says teams definitely shot worse than they should at NRG stadium.
Comment: The Twitter he links to seems to disagree (higher percentage in domes than arenas!). I think it has to do with confounding factors like which teams play in these places and such. But who knows.
Comment: @Joe I think traditionally you would think of a stadium as being outdoors and an arena as being indoors. Of course, those lines have been blurred. Now the difference probably exists more in the dimensions of interior. Soccer and American football use larger fields (and thus stadiums) and basketball and hockey use smaller playing surfaces, and thus arenas. When you put a hockey or basketball match in a stadium, there's a lot of open flat area (sometimes filled with seating) around the playing surface before it starts to go up.
Comment: @Joe ctd. And I would conjecture that it's that distance that troubles shooters, who are shooting on a translucent or transparent backboard. In an arena, the crowd is not so far behind the backboard, and usually shrouded somewhat in darkness. In a stadium, the crowd may be some distance behind the backboard and there's usually more light on them.
Answer: Short Answer: Scientifically, the size of the arena is irrelevant to the shooting performance though the nervousness of playing in front of a big crowd can negatively affect a player's shooting.
Long Answer: Statistically speaking, the stadium doesn't affect shooting by much (and this website makes that case). To prove this point, below are the shooting percentages in the three different types of stadiums during the 2009 and 2010 regionals.

Hockey arenas (nine games): 42.8 percent, 455-of-1064.
Traditional domes (nine games): 43.1 percent, 444-of-1030
Stadium setup (six games): 42.4 percent, 290-of-684.

Compare these numbers above to the average median shooting percentage between the 2009/10 and 2014/15 NCAA season (which is about 43%), you'll see that the arena doesn't affect the shooting.
Take it from Connecticut's coach Jim Calhoun, who really said it the best:

Every gym has a floor and two 10-foot baskets, and Reliant certainly qualified

But then in some cases, such as an under 20% 3pt shooting in a 2015 regional semi-final and 29.7% shooting half in another, why do teams have disastrous nights? There are always a number of factors that attribute to these horrible shooting nights (this website explains one). Whether it be the nervousness that comes with being in a big game with thousands of eyes on you or great, lock-down defense, bad nights can't be prevented.
Conclusion: Even if the NCAA somehow determines that big stadiums do affect shooting, they wouldn't move the games into the team's home or smaller arenas. This year, over 70 000 people watched the NCAA basketball finals in person, which resulted in millions for the NCAA and member institutions. In the end, with the big arenas, many more get to experience the thrill of the NCAA basketball game.
References:

Sporting News (April 2011), No evidence that stadiums impact shooting at Final Four, Retrieved from http://www.sportingnews.com/ncaa-basketball/story/2011-04-06/no-evidence-that-stadiums-impact-shooting-at-final-four
The New York Times (March 2015), Shooters Can't See? Fans, Cover Your Eyes, Retrieved from http://www.nytimes.com/2015/03/30/sports/ncaabasketball/vast-stadium-falls-silent-except-for-clangs.html?_r=0
Comment: You provided shooting percentages of 42-43% for hockey arenas, traditional domes, and stadiums, but provided no percentages for typical college arenas to compare them with.
Comment: The average median shooting percentage in all games from the 2009/10 through the 2014/15 regular season was around 43% (in all arenas), so the answer is that the arena doesn't affect the player's shooting
Comment: You should edit that information into your answer.  Also, your NY Times link includes a link to a [Ken Pomeroy](http://kenpom.com/blog/index.php/weblog/entry/the_nrg_effect) post which suggests there may be something about NRG Stadium that affects shooters.  I'm sure this topic will be revisited in 10 months when the 2016 Final Four is played at NRG Stadium.
Comment: In http://statpages.info/confint.html, I get a 95% confidence interval for hockey arenas to be 39.7% to 45.8%... which I believe shows the values are too closely clustered and there isn't enough data to make any statements.  There could be 0 difference, or as much as 5-10% reasonably, particularly given the smaller stadium sample.  And even moreso, these aren't independent samples whatsoever given the small number of games with numerous variables that could systematically effect it (team tendencies\skills involved, defenses encountered, specific location quirks, psychological momentum effects)
Comment: It's nice to have some data on this question, it's an intriguing question... but this is very bad statistics to make definitive statements with such minimal data... a problem all-too-often seen in sports.
Comment: All I think we may be able to get from this given data is that it appears to hint that the scale of any possible difference probably isn't ENORMOUS.
Comment: Though I do well agree with your conclusion Andrei (though it's really more of an unrelated guess\opinion than a conclusion to the data?).


how to find the confusion matrix of 5 different classification?

Question: I used this for getting the confusion matrix having 5 different classifications
y_test_non_category = [ np.argmax(t) for t in y_test ]
y_predict_non_category = [ np.argmax(t) for t in y_pred ]

from sklearn.metrics import confusion_matrix
conf_mat = confusion_matrix(y_test_non_category, y_predict_non_category)

and got
array([[ 76, 152,   4, 130,  56, 224],
       [  0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0]])

How do I calculate precision and F1 score? confusion matrix method
Answer: You can use the
sklearn.metrics.classification_report
to report get the respective metrics as you like.
>>> y_true = [0, 1, 2, 2, 2]
>>> y_pred = [0, 0, 2, 2, 1]
>>> target_names = ['class 0', 'class 1', 'class 2']
>>> print(classification_report(y_true, y_pred, target_names=target_names))
              precision    recall  f1-score   support
<BLANKLINE>
     class 0       0.50      1.00      0.67         1
     class 1       0.00      0.00      0.00         1
     class 2       1.00      0.67      0.80         3
<BLANKLINE>
    accuracy                           0.60         5
   macro avg       0.50      0.56      0.49         5
weighted avg       0.70      0.60      0.61         5
<BLANKLINE>
>>> y_pred = [1, 1, 0]
>>> y_true = [1, 1, 1]
>>> print(classification_report(y_true, y_pred, labels=[1, 2, 3]))
              precision    recall  f1-score   support
<BLANKLINE>
           1       1.00      0.67      0.80         3
           2       0.00      0.00      0.00         0
           3       0.00      0.00      0.00         0
<BLANKLINE>
   micro avg       1.00      0.67      0.80         3
   macro avg       0.33      0.22      0.27         3
weighted avg       1.00      0.67      0.80         3


Show skybox in hololens using MRTK

Question: I'm using Unity and MRTK to create an immersive application for the hololens (similar to Holotour). In this application, I need to simulate the sky. In Unity, a Skybox is sufficient to show this. However, in Hololens, it is not. How do I go about showing the sky/what's on the skybox in my Hololens? Thus far, I have tried adding a render texture for a camera high in the sky to an inverted sphere (i.e. a sphere that encompasses the playspace and shows the material of the sphere on the inside); but that doesn't seem to work...
Comment: why didnt the inverted sphere work?
Comment: Perhaps because it was getting culled by the camera clipping planes.
Comment: I realised I inverted the normals incorrectly. Having said that though, the render texture shows the view with respect to a single camera and thus only one direction. What I need is a stereoscopic/360 camera (and then apply its render texture?)
Answer: The HoloLens uses the Transparent camera display settings to determine how to clear the scene. If you change Clear Flags to Skybox, you should get your desired effect.
Comment: Thany you so much, this shows the Skybox! However, the objects in the app now seem to leave a trail (namely the MRTK sliders). Any idea why/how to fix this?
Comment: I'm not sure i have seen that before. Can you file an issue (with a video) at https://aka.ms/mrtk? That will help us track and investigate the issue.

Also, what versions of Unity and MRTK are you using?
Comment: After playing around with the app, I realised that the scene renders properly in the left eye, but not the right (right eyes has objects jitterring for whatever reason)
Comment: Which MRTK and Unity version?
Comment: I'm using Unity version 2019.2.8f1 and I am using the MRTK package: "Microsoft.MixedReality.Toolkit.Unity.Foundation.2.2.0"
Comment: After messing around with the application some more, I've realised that the smear/jitter is due to the depth buffer not clearing. To fix this, I went to Edit->Project Settings->XR Settings and changed "Stereo Rendering Mode" to "Multi Pass"
Comment: Thank you for the update! I will make note of that.
Answer: In Window>Rendering>Lighting Settings, set "Skybox Material" to the skybox of your choice. Also make sure, that your Camera "ClearFlag" is set to "Skybox".
If in doubt, please refer to the docs.

Show skybox in hololens using MRTK


Issue connecting second database in Codeigniter

Question: I have to use two databases in a controller. Even though I load the second database with second parameter TRUE to get reference without overwriting the default database it is replacing the default database. Any idea what should be done when loading the second database. Currently I am loading like below.
$testDB = $this->load->database('preview',TRUE,FALSE);

Comment: Are you doing anything else above or below?
Answer: set the pconnect param of both db to false
$db['preview']['pconnect'] = FALSE;

in your config/database.php
then on your model which is connecting to the second database, load it like this:
class Example_m extends CI_Model {

   function __construct(){
        $CI =& get_instance();
        parent::__construct();
        $this->db = $CI->load->database('preview',TRUE);
    }

Answer: //this will work sure or check your errors

//If you use group

//group name
$preview_DB = $this->load->database('preview',TRUE);

//another DB

$another_DB = $this->load->database('another',TRUE);

//if You use array

//create connection string
$db = array();
$db['hostname'] = "database_hostname";
$db['username'] = "database_username";
$db['password'] = "database_password";
$db['database'] = "database_name";
$db['dbdriver'] = 'mysql';
$db['pconnect'] = FALSE;

$DB = $this->load->database($db,TRUE);

Answer: I assume you've made the required configuration in your database.php
you can load your 2nd database like this: $testDB = $this->load->database('preview', TRUE);
and use it like this:  $query = $testDB->query("SELECT * FROM TABLE");
Comment: Thank you for the answer. But I tried this way also and that also replaces the default database.


Regex search and replace YouTube shortcode

Question: I have a WordPress plugin where I recently used regex to search and replace, however, I am finding it tricky to remove a space that now remains.
I have a YouTube link, which I managed to use regex to add:
[embed](youtubelinkhere)[/embed]

However, there is a space that I can't get rid of before [/embed] that is causing some issues.
What should I search for to remove this space before [/embed] please?
Many thanks.
Comment: you can search `\s[\/embed]` and replace with `[/embed]`
Comment: Thanks for your response...

Unfortunately, the plugin gave me this error:
Invalid regular expression: Delimiter must not be alphanumeric or backslash
Answer: You'll have to escape the square brackets:
\s\[\/embed\]

Live Demo
https://regex101.com/r/fT4dP3/1
Comment: Perfect thank you, just had to add "\s\[\/embed\]" so the plugin could understand it correctly.


View that uses both taxonomy terms and title(or nid) in contextual filters

Question: Is it possible to create a view that uses both taxonomy terms and the node title or nid as contextual filters?
Ideally this would mean that you could have one view that just handled the taxonomy terms eg. the parent-taxonomy-term/child-taxonomy-term view would display all the nodes matching those taxonomy terms and parent-taxonomy-term/child-taxonomy-term/node-title would display a different view with more information on the specific node returned.
Is such a view possible and if so how would i set it up (all my experiments at this have failed)?
The reason I require this is that I wish a view of the same node to be accessible via a number of different taxonomies. I am creating a store where users can see the same gold diamond ring by navigating on the main dropdown menu via 'Jewellery > Rings', 'Gemstones > Diamond' or 'Metal > Gold'. While the user is navigating in this way the breadcrumb trail and url are looking good 'jewellery/rings' etc. But when a product is clicked on and its node is viewed it has its own url that can only fit the pattern of one of the taxonomies. So the breadcrumb trail would suddenly change when getting to the product via another taxonomy.
Comment: Your problem looks similar to: http://drupal.stackexchange.com/questions/32019/how-to-use-a-views-contextual-filter-or . Maybe, those answers could help you.
Answer: I wasn't able to find a neat solution to this problem.
What I ended up doing was manually creating a page view from each taxonomy e.g. metals/gold/% and passed it the node title through contextual filters. This meant I was able to create a view of the correct product and the Easy Breadcrumb trail still looked good and a single product may exist in multiple breadcrumb trails. This works but isn't an elegant solution.
It would be great to find a solution to this that didn't need manual creation of page views. So any further thoughts on this are appreciated.


Nagios - Could not complete SSL handshake

Question: I'm trying to configure Nagios command for checking status of physical memory on a remote Windows host using NRPE plugin. I'm using Nagios v3.0.6 on Ubuntu Server v14.10, and latest stable version of NSClient++ 0.4.3.
Here are the snippets from the config files:
define command {
          command_name check_ph_mem
          command_line /usr/lib/nagios/plugins/check_nrpe -H $HOSTADDRESS$ -p 5666 -c CheckMEM -a MaxWarn=$ARG1$% MaxCrit=$ARG2$% ShowAl$
}

and
define service{
        host_name               remote-win-host
        service_description     Check Memory NRPE
        check_command           check_ph_mem
        use                     generic-service
}

Nagios could not retrieve any information from this command because when I execute
/usr/lib/nagios/plugins/check_nrpe -H  192.168.1.150

it gives back following error:
CHECK_NRPE: Error - Could not complete SSL handshake.

I've tried with reconfiguring part of C:\Program Files\NSClient++\nsclient.ini in following way:
[/settings/NRPE/server]

allow arguments = true

allowed hosts = 192.168.1.15

port = 5666

but it gives back the same error. I've already read dozens similar topics and tried different advices, but I still have the same issue.
Do you have any idea how to fix this?
Comment: The version of check_nrpe (2.10? 2.12?) in Ubuntu 9.10 might be too old to work with the 0.4 branch of nsclient++. Can you try a newer/supported version of Ubuntu?
Comment: I've tried with new version of Ubuntu 14.10 server, but problem remains. Ubuntu version (in question) is changed from 9.10 to 14.10 .
Answer: If you are using NSCP-0.4.3.x (rather then NSCP-0.4.2.x) on your Windows Host, then certificate based authentication became the default authentication method. That´s why your check isn´t working. To work around the issue you need to add the following to your config:
[/settings/NRPE/server]
insecure = true

After that you need to restart the NSClient++ Service. More infos can be found here (6.1 What is insecure mode)
Comment: As per the other answer from SysManSD, I also had to set `verify mode` to `none`
Answer: In my case I had to add under:
; ALLOW INSECURE CHIPHERS and ENCRYPTION - Only enable this if you are using legacy check_nrpe client.

the next two lines:
insecure = true

allow arguments = true

and change under:
; VERIFY MODE - Comma separated list of verification flags to set on the SSL socket

from
verify mode = peer-cert

to
verify mode = none

Comment: Eh. Is it really worth it to disable security measures?
Answer: Using NSClient++ 0.5.2.39 and check_nrpe 3.2.1, here's what worked for me:

Generate DH key on Linux machine (it takes a long time)
openssl dhparam -C 2048 2> /dev/null|sed -n '/BEGIN/,/END/p'

Paste your DH key to newly created file C:\Program Files\NSClient++\security\nrpe_dh_2048.pem
Edit C:\Program Files\NSClient++\nsclient.ini:
[/settings/NRPE/server]
dh = ${certificate-path}/nrpe_dh_2048.pem

Restart NSClient++ service: net stop nscp && net start nscp

This is based on the wonderful article http://hodza.net/2019/09/21/failed-to-establish-secure-connection-sslv3-alert-handshake-failure-1040/
Answer: Edit your nsclient.ini file and set parameter as below, its work for me:
[/settings/NRPE/server]
allow arguments = 1
allow nasty_meta chars = 1
allowed hosts = 10.10.83.94,127.0.0.1
port = 5666
use SSL = 1
ssl options = no-sslv2,no-sslv3
verify mode = none
insecure = true


Pitching a note based on where it resonates in your body?

Question: I was noticing how in the range E3 - E4, every note feels like it's coming from a  specific point. e.g. E4 is at the back of my mouth, C4 feels around my Adam's apple, G3 is at the bvery bottom of my neck, etc.
I wondered if I can actually use this to help me 'find' notes better? i.e. associate the positional sensation with specific notes. Is it a known/valid technique I could look into?
(As an interesting side-note, as I get to the top of my range my positional feel for notes actually starts moving left/right not just up/down, which is very strange!)
Comment: If you can learn exactly what notes resonate where, then I'm sure there's no reason why you couldn't use it. I'm not the most scientific of people but I'd imagine it's another form of muscle memory?
Answer: When we are born, we have a very limited "vocabulary" and our ability to vocalize is very basic and primitive. As we learn to speak in the language of those we hear in our environment (mostly our parents), we learn to make new sounds - mostly through trial and error as we attempt to emulate or replicate the sounds we here others make. Eventually our brain learns what to do with our body to make certain sounds and starts writing the code.
Speech and singing for most untrained individuals, is something that seems rather automatic.  In other words our brain tells us we want to make a certain sound, and without conscious thought, our brain has learned how to control all of the things our bodies must do to make that sound. We have to blow air across our vocal chords, stretch our vocal chords a certain distance, hold our mouth a certain way etc.  It's a very complex series of adjustments and mechanics that are all put into play without much conscious thought (other than "I want to make this sound").
Not every person makes a particular sound in exactly the same way as others.  Some may have learned to sing certain notes by placing much of the sound in the mask of the face to use as a resonator, while in others, the same note may emanate more from their throat. It probably depends on what worked first during the early trial and error process.   But once learned, it occurs automatically without having to think about it.
What you experience as you sing is what your brain has learned to do with certain sounds.  You have also probably discovered that you can shift the apparent source of any given note you sing, by consciously manipulating the mechanisms involved in producing the sound.  In other words you might be able to shift a particular note from chest voice to head voice or from head voice to falsetto.  Or shift the sound more to the front of your face or to the back of your throat.
You have learned through unconscious trial and error to place certain notes and sounds in certain areas within your vocal tract.  But through experimentation, you might discover that by shifting where the sound appears to emanate, certain notes may sound clearer or more resonant or have richer overtones.  Or they might be easier to sing and control by redirecting where the air travels after crossing the vocal chords on it's way out of your mouth.
Don't be afraid to experiment to see if some notes might sound better or be easier to sing if you alter their apparent point of travel (where you place most of the sound).  I could say apparent point of origin but the point of origin for all vocalization is the lungs.  Without air there is no sound (not even a whisper). And technically speaking of course, all sound "emanates" from the lungs.
But keep in mind that if you do discover a better way to place certain notes, it will take repetitive and intentional practice and conscious thought to override the automated process your brain and body have ingrained.
Undoubtedly, singing (as a hobby or profession) is something that we should "train" our bodies to do more effectively and efficiently.  This training involves overriding the code that our brain wrote in our infancy to trigger the process of making certain sounds and creating particular pitches.
We are all born with unique physical parts that go into play to make sounds.  We have all learned to make each sound in our own unique way.  My personal advice to anyone who wishes to learn the "best" area of the vocal tract to place all the notes they are capable of singing, as well as the most efficient and safest techniques to use to get the most out of their voice - is to solicit the services of a qualified vocal coach or voice teacher.
Answer: Yeah you should find some videos of people like David Weiss playing the musical saw.
The saw makes a theremin/cello-like sound, but it is important to bow it at the most resonant spot.
You can still make a sound with the bow on a saw, but if it is not in the particular "elbow" of that pitch/shape, the saw will not be at maximum resonance.
So finding out maximum resonant spots is actually very pro, and very advanced.  Go for it and GL!


Webform Address Element and Canada provinces

Question: In the webform (drupal 8) module I am using the address element and notice that the state/province field does not contain any Canadian provinces - only US States and Territories.
Where can I add the Canadian Provinces?
Answer: You can alter the default state options via /admin/structure/webform/config/options/manage.
I recommend installing the Address module for substantially better international address support.


SQL - Rank() on a table

Question: create table v (mydate,value)
as
select to_date('20/03/2010 00','dd/mm/yyyy HH24'),98 from dual union all
select to_date('20/03/2010 01','dd/mm/yyyy HH24'),124 from dual union all
select to_date('20/03/2010 02','dd/mm/yyyy HH24'),140 from dual union all
select to_date('20/03/2010 03','dd/mm/yyyy HH24'),138 from dual union all
select to_date('20/03/2010 04','dd/mm/yyyy HH24'),416 from dual union all
select to_date('20/03/2010 05','dd/mm/yyyy HH24'),196 from dual union all
select to_date('20/03/2010 06','dd/mm/yyyy HH24'),246 from dual union all
select to_date('20/03/2010 07','dd/mm/yyyy HH24'),176 from dual union all
select to_date('20/03/2010 08','dd/mm/yyyy HH24'),124 from dual union all
select to_date('20/03/2010 09','dd/mm/yyyy HH24'),128 from dual union all
select to_date('20/03/2010 10','dd/mm/yyyy HH24'),32010 from dual union all
select to_date('20/03/2010 11','dd/mm/yyyy HH24'),384 from dual union all
select to_date('20/03/2010 12','dd/mm/yyyy HH24'),368 from dual union all
select to_date('20/03/2010 13','dd/mm/yyyy HH24'),392 from dual union all
select to_date('20/03/2010 14','dd/mm/yyyy HH24'),374 from dual union all
select to_date('20/03/2010 15','dd/mm/yyyy HH24'),350 from dual union all
select to_date('20/03/2010 16','dd/mm/yyyy HH24'),248 from dual union all
select to_date('20/03/2010 17','dd/mm/yyyy HH24'),396 from dual union all
select to_date('20/03/2010 18','dd/mm/yyyy HH24'),388 from dual union all
select to_date('20/03/2010 19','dd/mm/yyyy HH24'),360 from dual union all
select to_date('20/03/2010 20','dd/mm/yyyy HH24'),194 from dual union all
select to_date('20/03/2010 21','dd/mm/yyyy HH24'),234 from dual union all
select to_date('20/03/2010 22','dd/mm/yyyy HH24'),328 from dual union all
select to_date('20/03/2010 23','dd/mm/yyyy HH24'),216 from dual

From this table, how to rank() over 'value', partitioning by each hour of the day? and select only the 1st ranked result?
Answer: select mydate,value from
(
select *,rank() over (partition by dateadd(hour,datediff(hour,0,mydate),0) as sno from v
) t
where sno=1

Answer: SELECT * FROM
(
 select value,MYDATE,
 rank() over (partition by EXTRACT(HOUR FROM DATE MYDATE) ORDER BY value) RK
 FROM V
)
WHERE RK = 1;

SQL - Rank() on a table


Using truth tables to determine whether (a ∧ ¬b) ↔ (a ∧ ¬c) is logically equivalent to b ↔ c

Question: I've solved the truth table, but I can't tell if they're logically equivalent as I'm not sure whether I am meant to stop at line 4 or consider the whole column.
Truth Table
So I have:
(a ∧ ¬b) ↔ (a ∧ ¬c):
T F F T T T T T
b ↔ c:
T F F T T F F T
The first 4 lines of each are logically equivalent, but the last 4 are different. Do I ignore the last 4 or consider the whole 8 lines of each column?
Cheers
Comment: Why do you think that possibly only a part of the truth table is relevant?
Comment: @drhab I thought maybe because there are only 2 variables considered it would only go down 4 times, but it's probably a very silly question.
Comment: @Jeremy: With the same reasoning, would you conclude that $a\land b$ is equivalent to $b$?
Comment: @HenningMakholm Wow, that made me realise how terrible of a question this is. Sorry, thanks.
Comment: Glad to help. :-)
Answer: No, they are not. Take $b=1$ and $c=0$. Then $b\Leftrightarrow c$ is $0$ (false), while $(a\wedge \neg b) \Leftrightarrow (a\wedge \neg c)$ with $a=0$ is $1$ (true), as both sides are $0$.


Judge countable and uncountable set

Question: Is $(1,2]$ uncountable? And is $\mathbb{Q} \cap [0,1]$ countable?
I'm confused about how to judge if it is countable, and I think the $(1,2]$ and $[0,1]$ are from $\mathbb{R}$?
Comment: $(1,2]$ can be put in correspondence with $\Bbb R$, so it's uncountable; subsets of $\Bbb Q$ are countable
Comment: Opps, I mean is (1,2] uncountable
Answer: First of all, $(a,b) , [a,b] , [a,b) , [a,b)$ have the same cardinality. And as any interval with $a\neq b$, $(1,2]$ is uncountable. The other set is a subtset of  $\mathbb{Q}$, so it can't be uncountable

Judge countable and uncountable set


What does a straight line connecting notes on different clefs mean?

Question: What is the meaning of the straight lines between notes in opposite staves, as shown in the picture? I keep seeing it, but Google and Wikipedia are not helping me.
Comment: I just have to ask, where did this music come from?  I keep seeing questions like this with such terrible formatting.
Comment: At a guess, this is from the _Ricercar a 6_ from the Musical Offering, @MattPutnam. That is why the "surplus" of rests. To be fair, this would be a very difficult piece to format on a Grand Staff.
Answer: It means quite simply that the voice in question is moving between the staves (and usually between the hands as well). In this case, the voice starting with G above middle C falls an octave to be continued in the left hand until it returns to G below middle C, then rises back up an octave to be played in the right hand.
Edit: Here is the original score of this passage (m.10ff of the Ricercar a 6 from the Musical Offering). Looking at the range of the individual voices, you can well imagine the number of times voices will cross between staves when this is transcribed to a Grand Staff.
Answer: In Barbershop style notation, such a line indicates that the melody is moving from one voice part to another.  By convention, a voice part does not move from one staff to the other.
In this case, it looks as if one musical line (perhaps on a single-note instrument or voice) moves from the treble clef staff to the base clef staff and then back.  As a singer, I would find this confusing.
Answer: If it is for piano then it could be considered to be a Glissandi or Glissando. What guitar players know as a slide.
An example of how this is notated.
Comment: It _could_ be a glissando (which is normally specified with _gliss._ over the line), but in this case it isn't; it's voice crossings. I've added the original score to my answer so you can see how the voices were originally notated.
Comment: Isn't glissando meant to be a wavy line, not a straight line connecting cleft. I believe it's moving voices.
Comment: Glissando can be applied to other instruments, right? Besides that, gliss is what came to my mind as well. +1


Ways to count lattice paths with backtracking

Question: I have been studying lattice paths, and I stumbled across this problem.
Given a rectangular grid with (0,0) and (m,n) as its corners, find the number paths possible from (0,0) to (m,n). There are several rules, of course.

The object must stay within the boundaries of the grid, inclusive.
The object must go either up one unit, or to the right one unit for each step. However ...
The object may choose to go down one unit once in the entire path, or not at all.

I started this problem with the formula:
C(n,k) = Choose k from n combinations
Number of paths = [number of paths without going down] + [number of path with going down]
Number of paths = C(m + n, n) + n * C(m + n + 2, m)
Is this the correct formula?
Part 2:
What would the formula be if object would not be allowed to land on an arbitrary point, (i, j), if given that 0 < i < m and 0 < j < n?
Comment: Your description is not clear. Obviously steps of type 2 can be made repeatedly, but if you allow the same for steps of type 3 you get an infinite number of solutions. Do you mean that one has the right, at most one time during the path, to include a step that goes one unit down or stays at the same point?
Comment: @MarcvanLeeuwen My interpretation is that at most one down step may be made, and it can't be made on the bottom edge.
Answer: $C(m+n,n)$ counts the number of ways without a down move.  For paths with a down move, there must be a total of $m+n+2$ moves because you need another up to counter the down.  I will take $m$ to be the horizontal direction of your grid.  I would count those by first changing the down to another up.  This gives us a path to $(m,n+2)$, of which there are $C(m+n+2,m)$.  Then we can choose any one of the ups to be the down except the first or last.  If we flip the first or last we go outside the grid, so there are $nC(m+n+2,m)$ paths including a down, for a final total of $C(m+n,n)+nC(m+n+2,m)$


"NoReverseMatch at/" no Django, quando tento colocar um link no botão

Question: Quando tento colocar um link em um botão aparece uma página com erro de NoReverseMatch at/, não sei mais o que faço, quero colocar esse link para ir para um app de cadastro de usuários que se chama login.
<button href="{% url "login.views.registrar" %}" class="btn btn-danger">Cadastre-se</button>

Exception Type:    NoReverseMatch
  Exception Value:
Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 >pattern(s) tried: []
Comment: **Funcionou** perfeitamente @mgibsonbr.
Em base ficou assim
`Cadastre-se`
Na urls principal
`url(r'login/', include('login.urls'))`
Com algumas modificações por fora, como o link do template em views.
`return render(request, "login/registrar.html", {"form": UserCreationForm() })`
Comment: Experimente remover as aspas das tags `url`. Ex.: `{% url article.views.post_new %}` em vez de `{% url "article.views.post_new" %}`. Veja [essa pergunta no SOen](http://stackoverflow.com/q/4981026/520779) para mais detalhes (se o problema for esse mesmo, comente dizendo se funcionou, e eu posto como resposta, acho que depende da versão). A propósito, quando fizer uma pergunta por favor inclua os trechos de código relevantes, não somente um link externo. No caso de um erro envolvendo exceções, um *stack trace* normalmente ajuda também. Fique à vontade para [edit] sua pergunta se quiser/puder.
Comment: Não funcionou tirando as aspas.
Obrigado pela dica da formatação, acho que é desse jeito agora né? :D
Comment: Eu reparei que no [seu `urls.py`](https://github.com/allancarlos123/ajuda_blog/blob/master/blog/urls.py) não há nenhum padrão referenciando a `login.views.registrar`, nem uma inclusão do [`login/urls.py`](https://github.com/allancarlos123/ajuda_blog/blob/master/login/urls.py) (tal como você fez com o `article` - `url(r'', include('article.urls'))`). Se nenhuma URL roteia para aquela *view*, então não tem como criar um link pra ela. Experimente incluir no seu `urls.py` [principal] algo como `url(r'login/', include('login.urls'))` (só um exemplo).
Answer: Um erro NoReverseMatch é consequência do Django não conseguir achar uma URL no seu sistema de mapeamento que resolva para uma determinada view, seja no template (tag url) ou no código Python (reverse). No seu caso, o erro está dando ao tentar formar uma URL para login.views.registrar, então é preciso ver se há algum padrão no urls.py que mapeie para essa view.
No seu exemplo completo (na revisão original da pergunta) eu vejo que não há nada no urls.py principal (o do projeto) que roteie para qualquer view de login:
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('article.urls'))
]

Como você já possui um urls.pyna app login, com um mapeamento para o view desejado:
urlpatterns = [
    url(r'^registrar/new/$', views.registrar, name='registrar'),
]

Então tudo o que você precisa fazer é acrescentar uma rota para a app login, tal como você fez para article. O tipo de URL é você que escolhe, mas a título de exemplo, assumindo que seu site esteja em http://example.com/django/ e você configure seu urlpatterns desse jeito:
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('article.urls'))
    url(r'login/', include('login.urls'))
]

Então a tag {% url "login.views.registrar" %} será substituída por:
http://example.com/django/login/registrar/new/

E essa URL servirá o resultado da view login.views.registrar. Fique à vontade para escolher outro roteamento, se desejar, o importante é que algum roteamento para a view exista, de modo a evitar o NoReverseMatch.