How do I interpret this Residuals Plot?

Question: I have some data where the histogram shows insurance premiums normally distributed except for a "spike" at the upper bound. (x-axis = price, y-axis = n_observations)

I am visualising the results of a Random Forrest Regression as follows
<code>from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from yellowbrick.datasets import load_concrete
from yellowbrick.regressor import ResidualsPlot

import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
%matplotlib inline

df = pd.read_csv('data.csv')

#df = df[df['INSURER3_PREMIUM'] < 380]

#Linear Regression
X = df[df.columns[:-1]]
y = df[df.columns[-1:]].values.ravel()

# Create the train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Instantiate the linear model and visualizer
model = RandomForestRegressor(n_estimators=15, min_samples_leaf=5, n_jobs=-1, random_state=0)
visualizer = ResidualsPlot(model, size=(1080, 720))

visualizer.fit(X_train, y_train)  # Fit the training data to the visualizer
visualizer.score(X_test, y_test)  # Evaluate the model on the test data
visualizer.show()
</code>
Result is ...

I then remove the "spike" in the histogram by uncommenting the line
<code>#df = df[df['INSURER3_PREMIUM'] < 380]
</code>
and re-running the code. The result is ...

I am struggling to understand how to interpret these results. Any advice will be greatly appreciated.
Comment: What happens when you separately model only the premiums *greater than* 380?
Comment: the residuals are all 0 because all training labels are the same (386.363985)
Answer: What exactly are you confused about? The straight line in the residuals? That comes from the observations you have at 386.363985, I believe.
The true value is this constant for all of the predictions on the line, but the model predicts different values for them. Since the outcome is always the same, the form of the residuals will be
$$y = x - y_{true} = x - c$$
where x is the model prediction, and $y_{true} = c = 386.363985$. So it's a straight line, just as you see. For example, at x = 250, $y = 250 - 386.36 \approx -136$, which is the value on the plot. In your second plot, you remove the values at around 386, so the straight line disappears.
Incidentally, you have a second straight line at 200, where things go the other way: the model predicts values greater than 200 and the true value is exactly 200.
Does this answer your question, or was there something else that was confusing you?
Comment: Is there any explanation for why the predictions for those 386.3 reach about double the error for the rest of the data
Comment: I am trying to understand the impact on the model of all those 386.3 observations. Clearly they skew the distribution of the residuals for example. Would an experienced data scientist ever remove most of those observations in order to return the distribution of the observations to a more Normal shape and improve the model?

How do I interpret this Residuals Plot?


"Converse" of optional stopping theorem

Question: Assume we are considering the discrete case. If $\{X_n\}_{n\in\mathbb{N}}$ is a martingale adapted to $F_n$ and $X_n\in L^1$, then for any bounded stopping time $\tau$, according to the optional stopping theorem (or optional sampling theorem), we will have that $E(X_\tau)=E(X_0)$.
I've seen some discussions on the condition such as the boundedness of the stopping time. However, now I am curious about that if we don't have the assumption that $X_n$ is a martingale does $E(X_\tau)=E(X_0)$ still holds for any bounded stopping time? In another word, does there exist any integrable random process $X_n$ adapted to $F_n$ which is not a martingale such that for any bounded stopping time $\tau$ it holds $E(X_\tau)=E(X_0)$?
Or we can rephrase this as "converse" of OST: if integrable random process $X_n$ adapted to $F_n$ and for any bounded stopping time $\tau$ it holds $E(X_\tau)=E(X_0)$, then $X_n$ is a martingale. Is this converse true or not?
Comment: Related: http://math.stackexchange.com/questions/2223020/bounded-stopping-times-and-martingales/2223494#2223494
Answer: Neat question! It is true, if I'm not mistaken.
Let $n$ be arbitrary and set $A = \{E[X_{n+1} \mid F_n] > X_n\} \in F_n$.  Set $\tau = (n+1) 1_A + n 1_{A^c}$; you may verify that $\tau$ is a bounded stopping time.  Then $X_\tau = X_{n+1} 1_A + X_n 1_{A^c}$.
Let $Y = E[X_\tau \mid F_n] = E[X_{n+1} \mid F_n] 1_{A} + X_n 1_{A^c}$ (by properties of conditional expectation).  Note that $Y \ge X_n$, and $Y > X_n$ on $A$.  But $E[Y] = E[X_\tau] = E[X_0] = E[X_n]$ since $n$ is also a bounded stopping time.  So we conclude that $P(A) = 0$, which is to say $E[X_{n+1} \mid F_n] \le X_n$ almost surely.  The opposite inequality can be shown in the same way, so we get $X_n = E[X_{n+1} \mid F_n]$ almost surely, and $n$ was arbitrary.  Thus $X_n$ is a martingale.
Intuitively, if you think of $X_n$ as a stock price, then $A$ is the event  that "information available by time $n$ suggests that, on average, the price is going to rise tomorrow".  So $X_\tau$ corresponds to the strategy "if on day $n$, it looks like the price is going to rise, then hold until tomorrow; otherwise sell today".  If $A$ had positive probability then this investment strategy would be profitable on average, which is supposed to be impossible if the stock price is a martingale.
Comment: Nice and clear answer. Thanks a lot.
Comment: Brilliant answer, thanks for the informative text at the end !
Answer: Nate Eldredge's answer provides some nice intuition on why the result holds true. Here's a different approach.
The task at hand is to prove that $\forall n, E(X_{n+1}|F_n)=X_n$. Let $n$ be fixed. Going back to very definition of conditional expectation, it is sufficient to prove that for every $A\in F_n$, $E(1_A X_{n+1})=E(1_AX_n)$.
Define $\tau = n 1_A + (n+1)1_{A^c}$. $\tau$ is indeed a bounded stopping time (easy to check) and $$E(X_{\tau})=E(1_AX_n +1_{A^c}X_{n+1})$$
Since the constant $n+1$ is also a bounded stopping time, $E(X_{n+1})=E(X_0)$, thus $$E(1_AX_{n+1})+ E(1_{A^c}X_{n+1}) = E(X_{n+1})=E(X_0) = E(X_\tau)=E(1_AX_n)+ E(1_{A^c}X_{n+1})$$
hence $$E(1_AX_{n+1}) = E(1_AX_n)$$ which concludes the proof.

"Converse" of optional stopping theorem


is it possible to mount a host directory as a volume on a running docker container?

Question: I only found instructions on how to run a container and mount a volume at the same time:
<code>$ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py
</code>
Taken from the user guide.
But I don't know the command to run once the container is running.
Comment: Why would you need this ?
Answer: This is not possible with the current version of docker. All volumes, links, networking, etc. need to be configured when the container starts.
Follow this docker pull request for when this functionality may end up being merged.
Comment: I'm not sure this feature will actually fit the author's need. This is more like an implementation of [centralized volume management](https://github.com/docker/docker/issues/8363) than volume hotplug/unplug.
Comment: Just a nitpick: networking can be configured on running containers (e.g. attaching a running container to a network you just created)


Swift: For loop - wait for animation to complete before iteration

Question: I am trying to display a sequence of animations based on a shuffled array.
On my ViewController I have 4 UIButtons with tags (1,2,3,4).
I then have a shuffledArray
shuffledArray = [3,2,4,1]

I am looping through that array using a for loop and animating the background of the UIButton like so:
for square in shuffledArray {
        let btn = view.viewWithTag(square)

        UIView.animate(withDuration: 1, delay: 0.0, options:[], animations: {
            btn?.backgroundColor = .red
            btn?.backgroundColor = .black
            btn?.backgroundColor = .red
        }, completion: nil)
 }

However, this just makes the 4 squares all flash black at the same time.
Is there a way to run this loop but wait for each animation to fire first before iterating through to the next index of the array?
I tried using:
sleep(4)

and the end of the for loop but that seems to freeze my app and then again all 4 squares change at the same time.
Side Note
This for loop is activated on a button click. After the for loop has ran I am generating a random number between 1 and 4 and then appending that to the shuffledArray. So it starts of:
 shuffledArray = [3]

then the second time it is
 shuffledArray = [3,2]

And the third
 shuffledArray = [3,2,4]

and so on....
The issue seems to only happen when the array contains more than 1 item.
Answer: Try something like this? (NOT tested)
var currentIndex = 0
func animateNext() {
    if currentIndex < shuffledArray.count {
        let btn = view.viewWithTag(shuffledArray[currentIndex])
        UIView.animate(withDuration: 1, delay: 0.0, options:[.autoreverse], animations: {
            btn?.backgroundColor = .red
            btn?.backgroundColor = .black
        }) { _ in
            self.currentIndex += 1
            self.animateNext()
        }
    }
}

Comment: The moment the shuffedArray gets two items it doest turn any of the squares black.
Comment: Resetting `currentIndex` to 0 before calling `animateNext()`
Comment: Also, try using `.autoreverse` to create a better blinking effect.
Answer: Try to use the delay property, like this:
for (index, square) in shuffledArray.enumerated() {
        let btn = view.viewWithTag(square)

        UIView.animate(withDuration: 1, delay: index, options:[], animations: {
            btn?.backgroundColor = .red
            btn?.backgroundColor = .black
            btn?.backgroundColor = .red
        }, completion: nil)
    }

UPDATED:

Try to combine animations by CAAnimationGroup (https://developer.apple.com/documentation/quartzcore/caanimationgroup).
Use CAKeyframeAnimation - for blink effects (https://developer.apple.com/documentation/quartzcore/cakeyframeanimation)
Comment: This solution may be better as it is much simpler.
Comment: This works for the first one and then it seems to jump the other 3 together.
Comment: @JamesG Are you sure that each button has a correct tag?
Comment: @NikitaErmolenko yup. Just checked.
Comment: @JamesG Can you for testing increase the delay? Something like that: delay * 3. And check the animations in slow simulator mode.
Comment: @NikitaErmolenko ok, I tried this with the index * 3. The issue is that they next animation loads before the flash has finished. And the delay black fade  slower, so when array gets to around5 items the black squares are staying for long time.
Comment: @JamesG oh, just noticed it. Why do you change the `backgroundColor` for three times in the animation block? oO
Comment: @NikitaErmolenko to create a blink/flash effect.


Ajuda em arrays em JS

Question: Pessoal estou realizando um curso e não consigo passar desse exercicio.
Escreva a função "medalhaDeAcordoComPosto(numero)", que recebe um número como parâmetro. Usando apenas o máximo de um "if" apenas. Talvez os arrays possam ser úteis aqui.
Você tem que devolver a medalha que corresponde às primeiras posições de uma competição:
medalhaDeAcordoComPosto (1)
"ouro"
 medalhaDeAcordoComPosto (2)
"prata"
 medalhaDeAcordoComPosto (3)
"bronze"
medalhaDeAcordoComPosto (4)
"nada"
 medalhaDeAcordoComPosto (5)
"nada"
function medalhaDeAcordoComPosto (numero){
    var medalhas = ["ouro","prata", "bronze"];
    numero= numero -1;
    if (medalhas[numero] = "undefined"){
        return "nada"
    }else{
        return medalhas[numero];
    }

}

Estou utilizando esse código, mas recebo um erro:
A função medalhaDeAcordoComPosto(1) deve retornar "ouro"
A função medalhaDeAcordoComPosto(2) deve retornar "prata"
A função medalhaDeAcordoComPosto(3) deve retornar "bronze"
Ao meu ver era pra dar certo, alguém poderia me ajudar a entender o que está errado nesse código?
Muito Obrigado.
Comment: Você está atribuindo um valor no `if` ao utilizar `=`, use `==` ou `===` para comparações
Comment: Inclusive, tem uma pergunta sobre esse exercício se você tiver outras dúvidas, dê uma olhada lá: [Exercício pegando a posição do array](https://pt.stackoverflow.com/q/422836/100416)
Comment: Então Rafael, coloquei o segundo=.
```
function medalhaDeAcordoComPosto (numero){
    var medalhas = ["ouro","prata", "bronze"];
    numero= numero -1;
    if (medalhas[numero] == "undefined"){
        return "nada"
    }else{
        return medalhas[numero];
    }

}
```
Mas agora aparecem outros erros:
A função medalhaDeAcordoComPosto(4) deve retornar "nada"
A função medalhaDeAcordoComPosto(45) deve retornar "nada"

Eu vi o seu código e entendi ele, mas eu queria entender o porque o meu está errado ainda, você poderia me ajudar?
Answer: O erro está em:
medalhas[numero] = "undefined"

Ao utilizar apenas um = ao invés de == você está atribuindo o valor a variável e não comparando.
Sugiro também verificar a função indexOf, que poderá ser útil na solução deste problema.

Ajuda em arrays em JS


How to simplify n(C∩A'∩B')? Demorgan's Law?

Question: i know by demorgan's law it becomes:
n(C∩(AUB)')
after this, in the book they turned this into:
n(C) - n(C∩(AUB))
i know what happens after this but i didn't get that last step. I tried to think about it logically without reaching anywhere. if anyone could provide both algebraic and logical approaches i will be thankful :)
Comment: What does the book mean by n(C)? Is it the number of members of C?
Comment: yes its the same as o(C)
Answer: $C \iff (C\wedge(A\vee B)) \vee (C\wedge \neg(A\vee B))$
Got it? Try to visualize the venn diagram.
Comment: thanks :D i'd like to know more though.
Answer: For any sets $C,X$ we have $C=(C\cap X)\cup (C$ \ $X).$ And the sets  $C\cap X,\; C$ \ $X$ are disjoint.
With $X=A\cup B,$ and with $C,X$ being subsets of some set $S,$ and $X'=S$ \ $X,$ we have $$C \backslash X=C\cap X'.$$
Since $C\cap X$ and $C$ \ $X$ are disjoint we have
$n(C\cap X)+n(C \cap X')=n(C\cap X)+n(C$ \ $X))=n(\;(C\cap X)\;\cup \;(C$ \ $X)\;)=n(C).$


Running selenium tests using Behat Drupal Extension inside DDEV containers

Question: Problem: Get Behat Drupal Extension based testing working inside of ddev containers.  This includes adding a separate selenium container to the existing configuration, being able to run Behat tests, and having the  be able to reference the web host container.
Answer: Prerequisites: have a working ddev instance hosting Drupal.  There are examples already to set that up, so I won't repeat that here.
The above task required the following additions:

selenium container: The container running selenium.  I used the chrome standalone version.  Add the following to your .ddev folder:

File: docker-compose.selenium.yml
version: '3.6'

services:
  selenium:
    container_name: ddev-${DDEV_SITENAME}-selenium
    image: selenium/standalone-chrome-debug:3.13.0-argon
    networks:
      default:
        aliases:
          - web

The last bit is critical; the selenium container needs to know about the web container running the drupal instance to connect to it, but as it is a dependency of the web container, you can't use 'links'.  You have to use the aliases approach, using the default network.

compose override: A file overriding the defaults for the web container to link the selenium container to it.

File: docker-compose.override.yml
version: '3.6'

services:
  web:
    depends_on:
      - db
      - selenium
    links:
      - db:db
      - selenium:selenium

Behat configuration: The following Behat configuration for MinkExtension worked for me:

(modify file behat.yml)
default:
  extensions:
    "Behat\\MinkExtension":
      goutte: null
      base_url: 'http://web'
      javascript_session: selenium2
      selenium2:
        browser: "chrome"
        wd_host: http://selenium:4444/wd/hub
        capabilities:
          extra_capabilities:
            idle-timeout: 50

base_url and wd_host entries were critical in getting this to work.
For more information on the last, see step 5 in the Behat Drupal Extension docs:

Configure your testing environment by creating a file called behat.yml with the following. Be sure that you point the base_url at the web site YOU intend to test. Do not include a trailing slash:

default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Drupal\MinkExtension:
      goutte: ~
      selenium2: ~
      base_url: http://seven.l
    Drupal\DrupalExtension:
      blackbox: ~

Comment: Thx! With this I managed to setup codeception testing with selenium for a CakePHP App.
Comment: The correct answer is still valid or has it changed in something about how to configure ddev drupal with behat selenium?
Answer: A current way to run Behat on Drupal with DDEV is via the ddev-selenium-standalone-chrome
Steps

Install the addon and restart DDEV

ddev get ddev/ddev-selenium-standalone-chrome
ddev restart

Update behat.yml to use the addon.

  extensions:
    Drupal\MinkExtension:
      base_url: https://web
      selenium2:
        wd_host: http://selenium-chrome:4444/wd/hub
        capabilities:
          chrome:
            switches:
              - "--ignore-certificate-errors"
              - "--disable-gpu"
              - "--headless"
              - "--no-sandbox"
              - "--disable-dev-shm-usage"


How can I check if a bracket is opened at one line and closed in another line in python3?

Question: I'm writing a little program to check if there's an error with tabulation and brackets but for the brackets I can only check in one line. How can I check if it's opened and closed in multiple lines? (like () [] {} )
And have the line number where is the error of the file where I've take the string?
I've tried to check in one line and it works but if I have a bracket that opens in line 3 and closes in line 4 it returns me like if there's an error.
def brackets():
    init = 0
    finish = 0
    err = []

    with open(sys.argv[1], "rt") as file:
        lines = file.readlines()
        for l in lines:
            for ch in str(l):
                if ch == "(":
                    init += 1
                elif ch == ")":
                    finish += 1

            if init == finish:
                if "-a" in sys.argv:
                    print( "[OK] " + str(lines.index(l) + 1 ) + ": " + str(l.strip("\n")) )
            else:
                if "-a" in sys.argv:
                    print( "[ERR] " + str(lines.index(l) + 1 ) + ": " + str(l.strip("\n")) )
                err.append( ["b", str(lines.index(l)), str(l)] )

            init = 0
            finish = 0

I expect that returns me errors only when a bracket is opened and not closed in the whole file.
for example if I have a string like this:
a = [ "hello",
      "world!"]

def hello():
    print("hello world")

It should be balanced because I've opened and closed the square brackets, not in the same line but I've opened and closed those brackets
but in this case there should be an error
a = [ "hello",
      "world!"

def hello():
    print("hello world"

because I've opened those brackets but I've not closed them in any line
Comment: Could you provide a few examples of inputs and desired outputs?
Comment: https://codereview.stackexchange.com/questions/180567/checking-for-balanced-brackets-in-python/195800#195800
Comment: @Xosrov I'm sorry, I noticed now that the formatting was wrong, fixed it and added the right examples
Answer: Try this, it should work:
# read the file as a whole
with open( 'somefile.txt' ) as fin :
    text = fin.read()

# filter everything but brackets out
brackets = ''.join( [i for i in text if i in '{}[]()'] )

# remove balanced pairs while we can
while len(brackets) > 0 :
    new_brackets = brackets.replace( '()', '').replace( '{}', '').replace( '[]', '')

    if brackets == new_brackets : break # no changes, bail out

    brackets = new_brackets

if len(brackets) :
    print 'unbalanced', brackets
else :
    print 'balanced'

The code above considers the following [(]) as unbalanced, because of the wrong order. If you don't care about the order, you may just count opening and closing ones, and make sure the number is the same:
>>> from collections import Counter
>>> Counter('[[]][[)()(}}')
Counter({'[': 4, ')': 2, '(': 2, ']': 2, '}': 2})

Comment: If I have a file where I take the string how can I have the line number where the bracket is opened but not closed?
Comment: @Ax34 instead of simple string containing the brackets, you may use the list of tuples, like `( '{', 23 )`, which means the opening bracket was in line 23. then you iterate over that list removing pairs of open/close brackets and see what's left. not a one-liner, but similar idea to what I did.


AngularJS and Visual Studio

Question: Is there an option to use AngularJS and all its features (including unit testing feature) in Visual Studio, without having NodeJS installed?
Apart from this, is there any Visual Studio template/extension for AngularJS?
Thanks and regards
Answer: have a look at NTVS, you would have to just install node.js to use this in visual studio, but running, debugging, testing all can be run from visual studio only.also you can host this using IIS as well (though this has nothing to do with NVTS).
EDIT
finally came up with even better solution, it doesnt need NTVS and can work with any VS version
have a look at my answer to my own question here
Comment: @TempOrary have a look at my answer [here](http://stackoverflow.com/questions/22115182/how-to-combine-these-angularjs-visual-studio-nodejs), I finally came up with a better solution
Comment: Thanks. I think this one is a better fit option. :)
Comment: But please let me know if there is any more better solution to this.
Answer: You can install Angular as a nuget package. When it comes to testing it's a little more complicated. You can read this http://codeforcoffee.org/setting-up-angular-js-jasmine-and-karma-in-visual-studio/
Comment: Thanks. But this still has a NodeJS dependency. I am looking for a way without NodeJS.

AngularJS and Visual Studio


Theming User Profile Edit Form not Rendering results.... Help?

Question: I am not rendering any results. This is my template.php:
function fueldeluxe_theme($existing, $type, $theme, $path) {
    /**
    *  Account edit Forms
    */
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'template' => 'user-profile-form',
        'path' => drupal_get_path('theme', 'fueldeluxe') . '/templates'
    );
    return $items;
}

function fueldeluxe_preprocess_user_profile_form(&$variables) {
    $variables['account'] = drupal_render($variables['form']['account']);
    $variables['picture'] = drupal_render($variables['form']['picture']);
}

This is my user-profile-form.tpl.php:

        <?php echo $picture; ?>

        <?php echo $account; ?>

As you can see I'm trying to load the user profile field forms. However I'm not able to render any results. The page loads okay when I add dummy text but no account field forms.
Answer:
Add a hook_theme() implementation
function YOURTHEME_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render_element' => 'form',
      'template' => 'user-profile-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
      //add '/templates' only if you store template files in an additional folder
    ),

  );
}

This tells the Drupal theming system that there's a template file waiting for it in YOURTHEME/templates.
Next we'll define some variables to pass into that template in a hook_preprocess_HOOK function. We can find the structured array of the form in $variables['form'] and assign the form elements to the variables we'd like to throw around our tpl.php file.
function YOURTHEME_preprocess_user_profile_form(&$variables) {
  $variables['rendered'] = drupal_render($variables['form']['account']);
  $variables['rendered'] = drupal_render($variables['form']['picture']);
}

This example will put the general account info fields and the user picture upload field (if pictures are enabled) into a variable called "rendered."
Now that we have defined a variable, we can output it in a template file. Create a template file named user-profile-form.tpl.php in 'YOURTHEME/templates'. This is a demo example:

  <?php echo $rendered; ?>

When you visit your user edit page, you should now see only some general account info fields and the picture fields. Create different variables in the preprocess function to separate out form elements and place them wherever you wish in the user-profile-form.tpl.php file, adding whatever markup you like.
Taken from HERE


Prove that $(2)$ is a prime ideal in $\mathbb Z[w]$

Question: Let $w\in\mathbb C$ be such that $w^3=1$ and $w\neq1$. Prove that $(2)$ is a prime ideal in $\mathbb Z[w]$, and describe $\mathbb Z[w]/(2)$.
What I wanted to do is to show that $\mathbb Z[w]$ is a PID, then $(2)$ would be prime because it's principal. To show that, I thought it would be easier to show a stronger claim that $\mathbb Z[w]$ is an Euclidean domain, but wasn't able to.
My textbook doesn't do a terrific job of explaining the notation here so I'm half-guessing that $\mathbb Z[w]=\{a+bw+cw^2:a,b,c\in\mathbb Z\}$.
Then I tried to construct a Euclidean function. Since $(a+bi)\mapsto(a^2+b^2)$ works for $\mathbb Z[i]$, I tried the similar $(a+bw+cw^2)\mapsto(a^2+b^2+c^2)$, but didn't know how to prove any of the properties for it.
Comment: Hints: Note that since $1 + w + w^{2} =0,$ we have $\mathbb{Z}[w] = \{ a+bw : a,b \in \mathbb{Z} \}.$ Try multiplying $a +bw$ by its complex conjugate for the Euclidean function.
Comment: While some of your ideas are good the assertion that the ideal would be prime because it is principal is false in general. You'd need to show in addition that you cannot factor $2$ in a nontrivial way. To this end use the euclidean function.
Comment: @GeoffRobinson What, what? Why is that equal to zero? I feel like I'm missing something obvious.
Comment: Note that $x^{3} - 1 = (x-1)(x^{2}+x+1)$ and consider what this says when $x = w.$
Comment: The minimal polynomial of $w$ is $x^2-x+1$, so that $\mathbf Z[w]=\{a+bw\mid a,b\\mathbf Z\}$. The euclidean function in this case is $a^2-ab+b^2$. It is indeed a euclidean ring, but you can have up to 4 quotients.
Answer: The ring $\mathbf Z[w]$ is isomorphic to the quotient ring $A=\mathbf Z[x]/(x^2+x+1)$. To show $2$ is prime, you have to show $A/2A$ is an integral domain.
We have:
$$A/2A \simeq \mathbf Z[x]/(2,x^2+x+1)\simeq \mathbf Z/2\mathbf Z[x]/(x^2+x+1)$$
so it is enough to show the polynomial $x^2+x+1$ is irreducible over $\mathbf Z/2\mathbf Z$, which means it has no root. It is easy to see the associated polynomial function is the constant $1$.
Comment: The 3rd cyclotomic polynomial is actually $x^2 + x + 1$, so I think that's the polynomial you wanted in the first place.
Comment: You're right. Sorry for the typo
Comment: In fact your quotient is a field (it is $\Bbb F_4$), whence the ideal is actually maximal.
Comment: It's true. It's a field as is the case for the quotient of any polynomial ring over any field by an irreducible polynomial. I just wanted to give as simple an answer as possible.


what path reduces magnetic field strength

Question: I'm having trouble solving this particular problem in Colley's Vector Calculus.  I believe my trouble lies in not being able to set up a differential equation.  Here is the problem;
Igor, the inchworm, is crawling along graph paper in a magnetic field.  The intensitiy of the field at the point $(x,y)$ is given by $M(x,y)=3x^2+y^2+5000$.  If Igor is at the point $(8,6)$, describe the curve along which he should travel if he wishes to reduce the field as rapidly as possible.
So, the section this is in is Directional Derivatives and the Gradient, and so this is a gradient problem.  Since we are minimizing magnetic field strength, we are looking for $-\nabla{M(x,y)}$ and we can easily find this at any point.  In this case, $(8,6)$.  But how do we go about doing this starting at a point and following the path for the entire magnetic field?
EDIT:  If it isn't necessary, please don't give me the answer.  Guidance would be much more appreciated, since I want to understand what is happening here.
Answer: Since Igor always moves in the direction of fastest decrease of $M(x, y)$, he follows a path $(x(s), y(s))$ such that $\frac{d}{ds}(x(s), y(s)) = -\nabla M(x, y)$, where $s$ is the distance or arc-length along $(x(s), y(s))$.  Now $\nabla M(x,y)= (6x, 2y)$, so Igor's path satisfies the system of ordinary differential equations $x'(s) = -6x$, $y'(s) = -2y$.  How convenient!  The variables are already seperated for Igor and ourselves!  It is easy to see, by solving this simple, decoupled system,  that $x(s) = x_0e^{-6s}$ and $y(s) = y_0e^{-2s}$, where the initial point is $(x_0, y_0)$.  So Igor's path is $(8e^{-6s}, 6e^{-2s})$.  Note that this path, as does any path satisfying $\frac{d}{ds}(x(s), y(s)) = -\nabla M(x, y)$, heads right into the point $(0, 0)$, where $M(x, y)$ clearly attains its global minimum value of $5000$.   And, there I suppose, Igor gets stuck! (Actually, he never quite gets there! ;))  Don't know exactly what the graph paper has to do with this, though . . .   ;)
Comment: I know the graph paper helped me visualize Igor walking on a flat surface with level curves of M on it, but I suppose looseleaf would have been just as arbitrary!  Thanks for the help!
Comment: @Christopher Ernst:  Oh yeah, just joking around, I know how useful gridded paper can be . . . and glad to be of service.  Cheers, Bob Lewis
Answer: Your system of differential equations is
$$
\begin{cases}
x'(t) = - 6 x(t)\\
y'(t) = - 2 y(t)
\end{cases}
$$
which can be easily seen is solved by $x(t) = e^{-6t}$, $y=e^{-2t}$.
Comment: while I see the implication, I never got to solving systems in my differential equation class.  Also, the book I am using has not given any lessons in such machinery either.
Comment: As a matter of fact your book does not require you to solve the equations, but only to describe the curve...
Comment: This is true, and it gives an answer of "Travel along the path $y^3=27x$ toward the origin."  I got the negative gradient and it results in that you have above.  But how to get the curve $y^3=27x$ is what I am struggling with.
Comment: @ChristopherErnst the differential equation $x'=-6x$ can be solved by separation of variables. $dx/dt = -6x$ thus $dx/x=-6dt$ integrate to get $\ln |x|=-6t+C$ then exponentiate to obtain $|x|=exp(-6t+C)$ which is the same as $x=kexp(-6t)$ for $k \neq 0$. Finally, observe $x=0$ is also a solution hence $k$ need not be restricted. The same goes for $y$. There are other ways, but this is most elementary modulo guessing.
Comment: okay, so basically once you know the system in x(t) and y(t), you can set them equal to one another with the appropriate variables (since $y=-6e^{-2t}, y^3=-216e^{-6t}$, and then since $x=-8e^{-6t}$ and $8*27=216$) and thus the curve $y^3=27x$.  Thanks.  I had no problem finding gradient of M, but the chapter focuses on single point gradients.  Thanks for walking me through it everyone!


What is the purpose of multiplying by the difference between the midpoints of two bins in this recipe?

Question: While browsing for information on how I might plot a fitted normal curve over a histogram, I found the following:
http://www.statmethods.net/graphs/density.html
There is a line I don't fully understand, though I recognize that it really does work:
yfit <- yfit*diff(h$mids[1:2])*length(x)

Here, yfit is initially a list of values drawn from the pdf of an inferred normal distribution at regular intervals along the x-axis, length(x) is the number of observations in a list x from which a histogram was prepared, and diff(h$mids[1:2]) is the difference between the midpoints of the second and first bars of said histogram on the x-axis. After this statement is run, yfit becomes itself multiplied by those other two terms.
I understand that multiplying by length makes sense as this turns values for a probability distribution function into number of observations around each respective value—taking into account that a continuous pdf is being used here and the number of observations at any single point is zero.
I don't understand why it is necessary to multiply by diff(h$mids[1:2]) to get the right outcome in the graph, although I can confirm that it does get the right outcome.
Does anyone have an explanation?
Comment: Think of it this way: `yfit` gives the heights of rectangles.  `diff(h$mids[1:2])` gives their bases.  The product gives their areas.  The so-called "histogram" is plotting *areas* (that is, frequencies) by means of bars whose *heights* represent the areas.  So it all comes down to the formula for the area of any rectangle, area = base * height.  This is explained in the links I first provided.
Comment: Perhaps you will find this question answered at http://stats.stackexchange.com/questions/4220 or even http://stats.stackexchange.com/questions/133369.  If not, then please edit it to explain what the terms in this code mean: it's important that your question be understandable on its own without requiring readers to visit another site.
Comment: I believe it is *precisely* about not understanding that `yfit` is a density and that the "histogram" you mention is not a histogram at all, but rather is a bar chart (showing frequencies rather than frequency densities).  I see nothing `R`-specific about this procedure, which is a standard one.
Comment: So do you know why diff(h$mids[1:2]) is needed?
Comment: "diff(h\$mids[1:2])*length(x)" - is the same as doing "h\$counts/h\$density". It is a multiplier which takes yfit (which is a density distribution) and scales it to frequencies exhibited in your data.
Answer: Since the histogram is a bar chart with
area = height (yfit from dnorm) times base "diff(h$mids[1:2])"
the area converts the bar chart area to a probability area
so final yfit (which is freq of occurrence) becomes probability (or area) times number of observations
classical formula is
$prob = \frac{freq occurrence}{total possible occurrence}$
Here is the mapping to classical formula
yfit             =     yfit * diff(hmids[1:2]) *   length(x)
freq occurrence  =     probability area         *   total occurrences


Is derivative of max(0, x) a diagonal matrix or a vector?

Question: I am reading this amazing tutorial and so far everything was clear and good. Unfortunately, there is this section which doesn't make sense to me:

Why is the derivative not a diagonal matrix but a vector?
According to this page tanh's derivative is a diagonal matrix. Tanh and max looks really similar to me. The tutorial also makes it clear that elementwise binary operators have diagonal Jacobians.
And it makes sense: when I differentiate $max(0, x_i)$ w.r.t $x_j$ it should be $0$, right?
What am I missing?
Comment: It looks like that are doing a component-wise derivative. I.e. the partial of this vector is defined as the vector of partials if that makes sense. This is what they mean by broadcasting across the elements.
Answer: You're not missing anything, you're just noticing how sloppy the math is in your current field of study.
When operating on a vector argument, functions are applied element-wise. The differential of such a function is given by
$$f = f(x) \quad\implies\quad df = f'(x)\odot dx$$
where $\odot$ denotes the elementwise/Hadamard product and $f'(x)$ is the ordinary scalar derivative, which is also applied element-wise.
The Hadamard product between two vectors can always be eliminated by converting one of the vectors into a diagonal matrix, e.g.
$$\eqalign{
a\odot b = Ab \quad\Longleftarrow\quad A = {\rm Diag}(a)
}$$
Eliminating the Hadamard product from the differential yields the gradient as
$$\eqalign{
\frac{\partial f}{\partial x} &= F' = {\rm Diag}\big(f'(x)\big) \\
}$$
These ideas apply not just to $\,\tanh(x)\,$ but to any function including
$\,\max(0,x)\;-$ also known as $\,\operatorname{ReLu}(x).$

I notice that some of the comments mention broadcasting to explain/excuse the sloppy mathematics that afflicts the field of neural nets/machine learning. But broadcasting is something different.
Broadcasting simply pads the dimensions of a
scalar/vector/matrix/tensor via repeated dyadic multiplication with all-ones vectors. For example
$$\eqalign{
&A\in {\mathbb R}^{m\times n} \qquad
&v\in {\mathbb R}^{m\times 1} \qquad
{\tt1}\in {\mathbb R}^{n\times 1} \\
&A\odot v
 \qquad&\big({\rm incompatible}\big) \\
&A \odot (v{\tt1}^T)
 \qquad&\big({\rm compatible\,via\,broadcast}\big) \\
}$$
Broadcasting works for simple multiplication and division, but is worthless (and confusing) when calculating gradients and Jacobians.
Answer: @KyleC has the right idea here. Given the functions you're looking at, I suspect you're studying neural nets. These are often implemented with libraries such as numpy to facilitate a multidimensional generalization of SIMD vectorization (see also here). From that perspective, a matrix is a vector of vectors (typically a column vector of row vectors in my experience, but that's not the only option).
Comment: Thanks for the answer both of you. You very well might be right, the only reason I am struggling with this is that nowhere else in the paper they did that. Whenever they talked about derivative it was never the component wise one...
Also, how am I meant to find out which one is it? They seem to have the exact same notation...
Comment: @Kristof Even if you don't pick up on them giving it away with the term *broadcasting* (which I hope they defined for you somewhere), you already know the reason why it's a matrix. When a scalar-to-scalar function $f$ is vectorized viz. $f(x)_i=f(x_i)$, $\partial_if_j=\partial_if(x_j)=f^\prime(x_j)\delta_{ij}$ is not only a matrix, but a diagonal one (which, admittedly, might be identified at times with its leading diagonal, construed as a vector). As you noted, it doesn't matter whether $f(x)=\tanh x$ or $f(x)=\max(0,\,x)$.


Python: Retrieve the Mac Address of the client using bottle framework

Question: I am looking to retrieve the Mac_Address of the user accessing my application.
I have tried the following code:
<code>import uuid
from uuid import getnode as get_mac
mac_address = get_mac()
mac_address = ':'.join(("%012X" % mac_address)[i:i+2] for i in range(0, 12, 2))
</code>
This works OK but returns the mac address of the server and not the client. Is there a way to retrieve the mac address of the client?
Comment: That should return the MAC of the computer where you run it from. If you're talking about a server-client, is this a web app ?
Comment: @AJK Yes its a web app.
Answer: The HTTP protocol does not send the MAC address of the client to the server, so there's no way for your server-side application to access it.
Answer: The client's MAC address is never revealed to the outside network. Thus it is not possible to get it. The only way for it is to install your app on user's machine.
Comment: Thanks for that. When I use `qlikview` i can easily retrieve the user mac adress but now I realise that it is only for the installed version of it and not the web version.
Answer: You will only be able to retrieve the MAC address of users who happen to be on the same LAN network segment as you are, so it is probably not a good idea to bake in the assumption that you can rely on the user's MAC address being available.


iOS get Visible portion of Image for an UIImageView

Question: I'm trying get the visible portion of UIImage from an UIImageView. UIImageView takes the entire screen. Pinch & Pan gesture is added to UIImageView. So, User can pan/zoom the imageview. After pan/zoom I want to crop only the visible part of the image view. I've tried a number of methods. But it returns me wrong part of image.
Thanks In advance.
Comment: Please share your cropping code, thanks
Answer: Include QuartzCore framework to your project and implement this method for getting visible part of image from your image view:
(one note: i mean that you are using ARC in your project)
#import <QuartzCore/QuartzCore.h>

- (UIImage*)imageFromImageView:(UIImageView*)imageView
{
    UIGraphicsBeginImageContext(imageView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextRotateCTM(context, 2*M_PI);

    [imageView.layer renderInContext:context];
    UIImage *image =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

Comment: Thanks a lot #DizAsm. It works perfectly for my imageview. I have set below property for my imageview.[imageView setClipsToBounds:YES];
 and imageView.contentMode = UIViewContentModeScaleAspectFill. It was very difficult to get exact image from imageview visible area. Now it works perfectly.
Answer: Thank you all. I've figured out the solution. Here is the code that I used to get the visible portion of the image. (Keep it in your mind that the image was not fully visible when zoomed or pan due to it was taking entire screen)
  - (UIImage *)cropVisiblePortionOfImageView:(UIImageView *)imageView {

  CGFloat zoomScaleX=imageView.frame.size.width/initialWidth;
  CGFloat zoomScaleY=imageView.frame.size.height/initialHeight;
  CGSize zoomedSize=CGSizeMake(initialWidth*zoomScaleX,initialHeight*zoomScaleY);

  UIGraphicsBeginImageContext(zoomedSize);
  [imageView.image drawInRect:CGRectMake(0, 0, zoomedSize.width, zoomedSize.height)];
  UIImage *zoomedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  UIGraphicsBeginImageContext(CGSizeMake(initialWidth, initialHeight));
  [zoomedImage drawAtPoint:CGPointMake(imageView.frame.origin.x, imageView.frame.origin.y)];
  UIImage *cropedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return cropedImage;
}

Comment: What is **initialWidth** & **initialHeight** ?


How to randomize quiz questions order in multidimensional array?

Question: var questions =[
new Question ("Who is the president of Czech Republic?", ["Donald Trump", "Andrej Kiska", "Milos Zeman", "Angela Merkel"], "Milos Zeman"),
new Question ("The capital of Czech Republic is:", ["Brno", "Ostrava", "Hradec Kralove", "Prague"], "Prague"),
new Question ("Which food is not common Czech food?", ["Cevapcici", "Svickova", "Trdelnik", "Tatarak"], "Cevapcici")];
var quiz = new Quiz(questions);
populate();

How do I randomize the order of the questions in this quiz? Here is the working sample:
https://jsfiddle.net/yhosftnt/
Answer: Sort them by using random numbers (demo):
this.questions = [].concat(questions).sort(function() {
    return Math.random() - Math.random();
});

The [].concat(questions) creates a new array, so the original array won't be changed.
Comment: Thanks a lot, very elegant solution!
Comment: One more small thing, since it is an array of strings how would I limit a number of random questions to pop up? Let's say in this example I want just 2 out of 3 questions to show up?
Comment: Slice the array after the sort - `.slice(0, number of questions)`


Residual vs fits for 2-level factorial design

Question: So I'm analysing a 2-level factorial design, and get the residual vs fits plot below. I don't understand why it's symmetrical around 0. In any form of linear regression I've learned that the plot in question should be randomly scattered (given the assumptions in the model are correct).
However, I've read that this symmetry in fact is the correct pattern for a factorial design, but the source doesn't explain why. (See page 6 of this source: http://www.calpoly.edu/~pan/teaching/Minitab%20DOE%20Tutorial.pdf.)
Can you explain why the residuals vs fits plot for a 2-factorial design is symmetrical around 0?
Answer: Consider a simpler model: two observations and one parameter.  The residuals of that model would be two points symmetric about 0.
If you run a two-level factorial with 2k observations so that two observations are at each design point, and if you have k+1 terms (k non-intercept terms) in your model, then you get the same kind of thing.  There's enough free parameters to generate a hyperplane that passes through the center of each of the pairs of observations sharing factor levels.
If you reduce the model or increase the number of observations at each factor level setting then you'll get something less regular looking.
Comment: thanks! On a side note, this is a split-plot design (i.e. some of the factors are blocked), meaning there are two levels of factors and hence two levels of error, say $\sigma_W$ at the whole-plot level and $\sigma_S$ at the split-plot level. Which error do you think the residuals explain?
Comment: Both.  I think software will decompose the residual error into the two components, either with something like maximum likelihood or the related REML, or via a method of moments estimator and the differing residual sums of squares...


jquery terminal: how to echo to terminal upon AJAX completion?

Question: jquery terminal should echo out to screen upon ajax GET completion. Currently, the terminal.echo wont fire inside a success callback
Tried setting CORS but still wont output. this is a client problem.
jQuery(function ($, undefined) {
    $('body').terminal({
        register: function (email, user, pw) {
            this.echo("register...")
            jQuery.ajax({
                url: "https://faf3fg.execute-api.us-west-2.amazonaws.com/api/register/" + email +
                    '/' + user + '/' + pw,
                crossDomain: true,
                success: function (result) {
                    this.echo(data);
                    console.log(data);
                },
                async: false
            });
        }
    },{
        greetings: 'say',
        name: 'sterm',
        height: $('body').height(),
        width: $('body').width(),
        prompt: 'sss> ',
        completion: true
    });
});

I expected it to return the response of the AJAX request at a later time but this seems to be unsupported.
Answer: The this keyword doesn't mean what you think it means here:
success: function (result) {
    this.echo(data);
    console.log(data);
}

This code is invoked long after the code in which is was being set, and this no longer refers to your terminal instance.  It now refers to the jqXHR object (the internals of the AJAX request/response).
You can capture that instance in a variable, which would retain that reference for later.  Something like this:
var terminal = this;
terminal.echo("register...");
jQuery.ajax({
    //...
    success: function (result) {
        terminal.echo(data);
         console.log(data);
    }
});

Side note: You should remove async:false from your code.  Not only is it a famously bad idea, but it's actively being deprecated from browsers.  I wouldn't be surprised if there are browsers in common use already which don't support it.
Keep your asynchronous code asynchronous.
Comment: Can also extract the callback outside of the ajax call which will avoid setting another variable.


Seleção com Dapper usando cláusula IN

Question: A minha ideia é gerar uma pesquisa no meu banco usando a cláusula in através do Dapper. Por exemplo:
select * from product
where CasNo in(@filtro)

Lembrando que dentro desse @filtro tem uma lista de CasNo que é do tipo List<String>.
Testes
List<Product> IProductRepository.RetornarPesquisaProdutos(List<string> filtroId) =>
    conn.Query<Product>(
        @"
        SELECT
            pr.IdProduct as IdProduct,
            pr.Name as Name,
            sup.Name as Supplier,
            sup.IdSupplier as IdSupplier
        FROM Product pr
            FULL OUTER JOIN Supplier AS sup ON (pr.IdSupplier = sup.IdSupplier)
        where
            pr.IdProduct in (@filtroId) or
            pr.CASNo     in (@filtroId)
        ORDER BY pr.CommercialName",
        param: new { filtroId }).ToList();

Isso não deu certo.
Também tentei fazer como eu passava no ADO.NET (que deu certo lá, porém era de uma forma muito escrota que eu tinha feito) concatenando direto nesta lista todos os itens que eu precisava. Exemplo filtro = "'123-1', '326-3', '684-8'"); e mandava esse filtro direto na minha Query sem fazer o cmd.Parameters.AddWithValue(filtro);.
Porém agora eu preciso fazer no Dapper essa ideia de passar uma lista dentro do IN
Answer: É só tirar os parênteses. O Dapper já faz isso.
select * from product
where CasNo in @filtro

Comment: Obrigado, funcionou!

Seleção com Dapper usando cláusula IN


Erro JPA com MySQL 8

Question: Olá,
Após atualizar meu banco de dados, minha aplicação vem apresentando exceptions, do tipo java.sql.SQLSyntaxErrorException.
A classe abaixo, é a que ele reclama, dizendo que não existe quando o hibernate tenta cria-la.
@Entity
@Table(name="Loja")
public class Loja {

// Omitido para facilitar a leitura

}

Este é meu arquivo persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
     http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">

 <persistence-unit name="persistence_elysium">

   <provider>org.hibernate.ejb.HibernatePersistence</provider>

   <properties>

      <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/elysium?useTimezone=true&serverTimezone=UTC" />
      <property name="javax.persistence.jdbc.user" value="pegasus" />
      <property name="javax.persistence.jdbc.password" value="password" />

       <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
      <property name="hibernate.show_sql" value="false" />
      <property name="hibernate.format_sql" value="false" />

      <property name="hibernate.hbm2ddl.auto" value="update" />
   </properties>
 </persistence-unit>
</persistence>

Reforçando, que começou esse problema ao migrar para o MySQL 8, nas versões anteriores funciona normalmente (testado com a versão 5.7).
Saliento também, que atualizei o mysql-connector, tentei as versões 8.0.11 e 8.0.12 do jar.
Estou usando Windows 10.
As tabelas são criadas tudo com letras minusculas, mesmo no Table name estar capitalizado.
Quando lança a exception, ele diz: Tabela 'elysium.loja' não existe.
Ficarei muito grato a quem me auxiliar a resolver esse problema, pois esta me tirando do sério.. rs.
Obrigado!
Comment: Foi criada a database antes de rodar?
O JPA só cria as tabelas, a database não.
Answer: Você pode começar a informar sua entity no arquivo persistence.xml:
<persistence-unit name="persistence_elysium">

   <provider>org.hibernate.ejb.HibernatePersistence</provider>

   <class>pacote.Loja</class>
...

Outra coisa é você verificar se tem algum banco de dados que tem a tabela loja. Outro banco de dados que não seja elysium.
Se tiver terá que excluir. Isso resolveu para mim.
Se você não quiser excluir o outro banco de dados, a solução seria trocar o nome dessa tabela de @Table(name="Loja") para @Table(name="store")
Comment: Olá Victor... Eu fiz o teste, tentando declarar a entity dentro do persistence.xml e não deu certo. Sobre deletar outras databases, vou testar e informo, pois realmente tem sim, uma outra database com a tabela loja criada.
Comment: Você deletou ao outro banco de dados ou a tabela **loja** que pertence ao mesmo?
Comment: Se você não quer excluir o outro banco de dados, a solução seria trocar o nome dessa **entity** de `@Table(name="Loja")` para `@Table(name="store")´, por exemplo. Ou qualquer outro nome diferente de Loja. Editei a minha resposta falando isso.
Comment: Obrigado Antonio! Resolveu mesmo dropando a outra database. infelizmente, não posso alterar o nome, o projeto é grande, tem relacionamentos e tudo mais. Espero que isso seja um bug dessa versão do MySQL, porque não tem cabimento isso.. hehe. Porque data1.nomeDaTabela é diferente de data2.nomeDaTabela.

Erro JPA com MySQL 8


Area of polar coordinate $r = e^{- \theta/4}$

Question: $$r = e^{- \theta/4}$$
$$\pi /2 \leq \theta \leq \pi$$
I know the formula is
$$\int_a^b \frac{1}{2} r^2 d\theta$$
$$\int_{\pi/2}^{\pi} \frac{1}{2} (e^{- \theta/4})^2 d\theta$$
From here I cannot figure out an easy way to integrate this.
Answer: Note that $(e^{-\theta/4})^2=e^{-\theta/2}$.  It is a special case of the general exponential rule $(a^b)^c=a^{bc}$.
Comment: I was attempting to work my way through how to do that so I did $2^3^2$ on my calculator and it gave me 512 which means that it is $2^9$ which means that I have to square the exponent. What went wrong?
Comment: @Jordan It may be because of the order of operation of the calculator.  $$(2^3)^2=8^2=64=2^{2*3}=2^6$$
Comment: @Jordan Your calculator chose to give you 2^(3^2); this is not the same as (2^3)^2. In general the calculator will have its own precedence rules, and without understanding them I'd be very careful about trusting what it says about composing operations.
Answer: Hint: $(x^a)^b=x^{ab}$. After that, it falls right out, either through FTC or a substitution.
Answer: The integral you compute should is:
$$\frac{1}{2} \int_{\pi/2}^{\pi}\left(e^{-\theta/4}\right)^2\, d\theta=\frac{1}{2} \int_{\pi/2}^{\pi}e^{-\theta/2}\, d\theta$$
Using the exponent rule $(a^b)^c=a^{bc}$.  Letting $u=-\theta/2$, $\theta=-2u$, $d\theta=-2\, du$
$$\frac{1}{2}\int_{\pi/2}^{\pi}e^{-\theta/2}\, d\theta=-\int_{-\pi/4}^{-\pi/2}e^u\, du=-\left[e^u\right]^{-\pi/2}_{-\pi/4}=e^{-\pi/2}(e^{\pi/4}-1)$$


Can someone clarify in simple terms what it means to "apply an inequality to a measure"?

Question: I am reading wikipedia's entry on Holder's inequality
https://en.wikipedia.org/wiki/H%C3%B6lder%27s_inequality#Counting_measure
There are quite a few variations of Holder's inequality "applied to different measures" - a phrase quite new to me. I have no idea what this notion of a measure is, when I look up, for example, the counting measure, it says that the counting measure $\nu: S \to [0,  \infty]$, is the size of a set $A$. https://www.ma.utexas.edu/users/gordanz/notes/measures.pdf
Can someone please clarify what it means to "apply an inequality to different measures". I am not a mathematician, what is a simple way to understand this idea? Must we specify which measure we are applying an inequality against?
Comment: If you don't know what a measure is, it's hard to see how one can write an answer that would be helpful.  Understanding what measures are and how to use them is typically a half-year course at the advanced undergraduate or graduate level.
Answer: Holder's inequality is a very general result concerning very general integrals in an arbitrary measure space. This is probably the most remarkable thing about Holder's inequality, and why it is so useful.
Even in the statement of the theorem (as stated in the wikipedia link) the result only requires that we have a measure space $(S,\Sigma,\mu)$. All they mean by "applied to different measures" is that we can explore some meaningful implications and say explicitly what the inequality means if we are given a priori certain popular measure spaces (e.g., counting measure, Lebesgue measure, etc...).
Comment: Thanks, it is not obvious to me as an engineer why we need to specify it. I just use it. If I am given a bunch of functions, I apply the one that has integral sign. If I am given a vector, I use the one with the counting measure. I never think about the underlying "measurable space" but then again I don't do proofs I just crank out results. Good to have this clarified.
Answer: Hölder's inequality is an inequality involving integrals.  You may be familiar with ordinary integrals of functions $f:\mathbb{R}\to\mathbb{R}$, but integrals can be defined in much more general contexts as well.  A "measure" on a set $S$ is a gadget that allows you to define integrals of functions $f:S\to\mathbb{R}$ (the measure on $\mathbb{R}$ that gives ordinary integration is called "Lebesgue measure").  Hölder's inequality is valid when talking about the integrals obtained by any measure in this way.  So "applying Hölder's inequality to a measure" just means using Hölder's inequality where the integrals in the inequality are integrals defined using that measure.
Comment: This is exactly my question: what is the process that give birth to Holder's inequality. Is this inequality the result of of a single unifying inequality to different contexts, or do different contexts have their own holder inequality but no unifying holder inequality. This is a very natural question, given that for example, Holder give birth to Cauchy Schwartz for p = q = 2.
Comment: I'm not sure what you mean by a "single unifying inequality".  It is possible to give a single proof of Hölder's inequality that works for all measures simultaneously, if that's what you mean.
Comment: In your answer you have specified that the unifying guy here is the one involving integrals. Defining the integral with respect to different measures give rises to different Holder inequality (different in the sense it is defined wrt to different measures). And yes it would be interesting to see that proof Eric!


wpf assign one color to another

Question: In my XAML I have this:
<Color x:Key="VeryLightGrey">#fff0f0f0</Color>
<Color x:Key="TabBackgroundColor">#fff0f0f0</Color>

I would love to have something like this:
<Color x:Key="TabBackgroundColor" Color="{StaticResource VeryLightGrey}"/>

I have tried various methods including this:
<StaticResource x:Key="TabBackgroundColor" ResourceKey="VeryLightGrey"/>

But my code become riddled with warning about:
"An object of type System.Wndows.StaticResourceExtention cannot be applied to a property that expects the type System.Windows.Media.Color"
Other posts say to ignore this warning, but it actually causes problems, so i cant.
Is there a better solution out there ?
Comment: What? why do you want to duplicate resources like that?
Comment: because i want to be able to assign verylightgrey to the tabbackground, not the number #fff etc. I also want the color to be defined as grey, not just the color brush. Its not a duplication really, it makes it easier for people to understand and also easier to change colors later
Comment: Not really. You seem to misunderstand how XAML resources work. Use Brushes as mentioned in @Emo's answer.
Answer: You could declare the color once and define multiple brushes that use the same color.
Use the Brushes for your UI Elements.
Comment: i cant uses brushed in all the UI elements I have, sometimes i must use Colors
Comment: @Andy - Please give me an example of a situation where you cannot use a brush.
Comment:   it has to use a Brush here, not a color
Comment: @andy this gradientstop is part of a gradientbrush. Just make multiple gradient brushes and refer to colors using StaticResource

wpf assign one color to another


Example of two norms and ONE linear operator that is bounded and unbounded in a norm.

Question: I am looking for an example of a linear operator that is bounded as well as unbounded depending on which norm you take. Since I do not have much experience with Functional Analysis, I do not know many examples.
Answer: Assume $\varphi : (E, \| \cdot \|_{E}) \to (F, \| \cdot \|_F)$ is an unbounded linear operator, i.e.
$$
\sup_{x \neq 0} \frac{\|\varphi(x)\|_F}{\|x\|_E} = \infty.
$$
Then define
$$
\forall x \in E, \qquad \|x\| \overset{def}= \|x\|_E + \|\varphi(x)\|_F.
$$
You can check that this gives a well defined norm on $E$ under which $\varphi$ is bounded. You don't need $\varphi$ to be unbounded for that to work, but if it is unbounded, then you have an example. The reason why $\varphi$ becomes bounded is because
$$
\sup_{x \neq 0} \frac{\|\varphi(x)\|_F}{\|x\|} = \sup_{x \neq 0} \frac{\|\varphi(x)\|_F}{\|x\|_E + \|\varphi(x)\|_F} \le 1.
$$
This is an example that happens in practice, it is not just a counter-example ; for instance, if $E = C^1[a,b]$ and $F = C[a,b]$, if we equip both of them with the supremum norm $\| \cdot \|_{\infty}$, then $\varphi : E \to F$ defined by $\varphi(f) = f'$ is not a bounded linear operator. Thus we define the new norm on $E$, namely $\|f\| = \|f\|_{\infty} + \|f'\|_{\infty}$, so that differentiation becomes continuous.
Hope that helps,
Comment: Yes, it does, thanks


How to register rss for a website?

Question: I am not sure if I ask this question in the right place, because I am new to it. What I want to ask is, do I need to register/create RSS for my website?
I have a website, lets say:
[http://blog.domain.com] => its a 2.9.2 wordpress blog
So, if I want to display the latest content in another subdomain, for example: [news.domain.com], how do I do that? I know a little bit of php and mysql.
Answer: You don't need to do anything special to generate an RSS feed from a WordPress blog. That's built in. Not sure what you mean by "register"?
As for your last paragraph: You want to display content from blog A on blog B. Where? In the sidebar of blog B? Use the built-in RSS Widget as that's exactly what it is for. Or do you mean you want the posts from Blog A to show up as Posts on Blog B? Then you'll want to find a syndication plugin (here's a search on the WordPress plugins page). FeedWordPress used to be the de facto standard for this stuff but I've lost track if it is still updated. I'm sure you can find another if not.
Hope that all helps.
Side note: WordPress support forum can be found at http://wordpress.org/support
Answer: Normally there is a plugin or module that generates a RSS feed for a website if using a framework. Then all that needs to be done is to add an appropriate <link> element to the web page's header in order to notify the browser about the availability of a feed.
If you are talking about consuming a feed, then some web frameworks have modules available that will read a given feed and generate HTML for the articles contained within.

How to register rss for a website?


How to train a neural network to generate movements based on a training set of hand motions?

Question: I am making a game in Unity that involves creatures whose animations are determined by physics. For example, to move a limb of a creature, I can apply forces to the rigidbody it's associated with. I know how to apply forces programmatically through a script to create movements, but I'd like to create more complex and organic movements and thought that I might be able to use a neural network to do this.
I'd like each of the creatures to have a distinct way of moving in the world. I'd like to first puppeteer the creatures manually using my hand (with a Leap Motion controller), and have a neural network generate new movements based on the training I did with my hand.
More concretely, my manual puppeteering setup will apply forces to the rigidbodies of the creature as I move my hand. So if I lift my finger up, the system would apply a series of upward forces to the limb that is mapped to my finger. As I am puppeteering the creature, the NN receives Vector3 forces for each of the rigidbodies. In a way this is the same task as generating a new text based on a corpus of texts, but in this case my input is forces rather than strings.
Based on that training set, is it possible for the NN to generate movements for the characters (forces to be applied to the limbs) to mimic the movements I did with my hand?
I don't have that much experience with neural networks, but am eager to learn, specifically for this project. It would be great to know about similar projects that were done in Unity, or relevant libraries I could use that would simplify the implementation. Also, please let me know if there is anything I can clarify!
Answer: Not really an answer but would not fit for comments
I'm not sure the strategy you want to apply to train your model is the right one.
I would go for reinforcement learning methods (you can check this question for more infos about it) using, for example, the distance traveled by the center of mass of the creature on the x-axis as a fitness. If this leads to weird behaviours (like this well known robot) you could, for example, think of strategies like penalizing your individuals given the distance traveled on y and z axis (still by the CoM) to try having guys that keep there CoM on the same plane.
Without knowing exactly what you want to achieve this is hard to give you more advices. Although, if you are not looking only for neural network based techniques, there is this really great paper you might want to have a look at (here is the video of their results).
Comment: This is great, thank you for the suggestion! I'm going to look into reinforcement learning.


Why is there no general solution to $\sin(ax)+\sin(bx)=0$?

Question: Is there a theorem stating that a general formula for the solution to the equation
\begin{equation}
\sin(ax)+\sin(bx)=0
\end{equation}
does not exist in terms of elementary functions?
I don't know what keywords to search for to better understand this problem; on google I keep finding methods to find the numerical solution rather than an algebraic discussion.
When $a,b$ are integers, is this problem related to Galois theory, since in this case $\sin(ax)$ and $\sin(bx)$ can be expressed as polynomials in $\sin(x)$ and $\cos(x)$?
Comment: Actually a formula exists, and it is quite simple. You can use the fact that $\sin A = \sin B$ if and only if $A = n \pi +(-1)^n B$
Comment: Yes, I just realized that...
Comment: I think this is unrelated to Galoia theory.
Answer: $$\sin(ax)=-\sin(bx)=\sin(-bx)$$
$$ax=n\pi+(-1)^n(-bx)$$ where $n$ is any integer
If $n$ is odd$=2m+1$(say), $ax=(2m+1)\pi+bx$
If $a\ne b, x=\dfrac{(2m+1)\pi}{a-b}$
What if $a=b?$
What if $n$ is even $=2m$(say)?
Comment: I just realized the same thing. I am really trying to figure out more complicated equations like a generic sum of sines and cosines with different frequencies. I think I underthought the wording of the question. My fault.
Comment: what is in the case $$a=b$$?
Comment: @Dr.SonnhardGraubner, Updated the answer for better understanding
Answer: Hint. One may recall that
$$
\sin(ax)+\sin(bx)=2\cdot\sin\left(\frac{ax+bx}2\right) \cdot \sin\left(\frac{ax-bx}2\right).
$$


Kernel panic - not syncing - Attempted to kill init

Question: I am using Linux  2.6.32-33-server  #70-Ubuntu  10.04.3  as Data-Nodes and Name-Node  in my Hadoop cluster, but one of my data node is down since morning. When i restarted that particular system it showed an error
"Kernel panic - not syncing - Attempted to kill init!"
I dont know how to fix it!! Is this a problem with RAM of that system!!
Answer: /sbin/init is always the first process launched on your system. If the binary doesn't exists, the system cannot start. I don't know what happened, but it seems it has been erased from your disk, the easiest way to repair it is to reinstall the entire system. If you did correctly install your system first, you'll just have to reinstall the root partition, and just link your others (/home, /boot, etc...).
If you don't want to do that, first check if the /sbin/init binary exists, you can do that mounting the partition from another one or a LiveCD.
Comment: it is also saying `run -init:/sbin/init : no such file or directory`
Comment: `/sbin/init` is the first process launched on a computer. If it doesn't exists, your system crashes. I think the simplest way for you is to reinstall it...
Answer: In all recent systems initd is started from initrd image. If the kernel can not find it this means that initrd is missing or corrupted.


What can actually go wrong when defining global functions in a cpp file?

Question: On my project I often see people defining global functions in .cpp files, i.e functions that are not restricted to file scope, class scope or any particular namespace.
These are clearly local helper functions that the author only wanted to be able to access in that file.
I know this is bad practice and the solution is to restrict them to file scope either by using the static keyword or better yet use an anonymous namespace.
But my question is, if these functions are not declared in the header file, what can actually go wrong?
I would like to advise these people against this practice but I feel my argument would have more weight if I could clearly describe what could go wrong. Or even what what might already be going wrong that we are not aware of!
Thanks.
Comment: Never tried that, but I think if you define 2 functions with the same signatures in 2 different source files, you'll get an error when linking, probably some kind of "multiple definition of ...".
Comment: @KirilKirov Except if you use `extern` to declare a function.
Comment: It depends on the scale of the particular project. If it is a small utility with limited scope and few dependencies, then probably there's no need to be fanatic about namespace tidiness. But in a library, or in a large project, it is certainly intolerable. By the way, functions declared in global scope are not evil per se. We used to do that by necessity in the old ages when not every compiler supported namespaces. But we certainly gave the public function names prefixes that served as namespaces.
Comment: @KirilKirov. I tried it. And you do. In VS2012: `Error 1 error LNK2005: "void __cdecl myGlobalFunction(void)" (?myGlobalFunction@@YAXXZ) already defined in AnotherClass.obj`. Thanks
Comment: @user3467895 - thanks for informing me about the result :) It was useful to me.
Answer: One, you are cluttering the namespace. The result can be multiple definitions, i.e. linker errors, and programmers choosing awkward function names to circumvent this. Imagine one source file defining its helper() function, the next one a my_helper() because helper() resulted in an error, then a third a other_helper() and so on... in any case, the cleaner the namespace, the easier it becomes to understand what is actually going on.
Two, and this is an extension of the above, imagine a helper( int x ) and a helper( long y ), and you can imagine the kind of ambiguity that could arise from this. If you are lucky (and using appropriate warning options), the compiler will warn you about these conditions, but you might end up calling a different function than what you expected.
Three, and this is from a maintainer's point of view, if you see a function that is static or declared in an anonymous namespace, you know that you only have to check the current source file for calls to this function. This makes refactorings that much easier. ("Does anyone actually use this exotic but buggy feature, or can I optimize it away?")
Comment: @user3467895: See Kiril's comment. As soon as you try to link them into a single binary.
Comment: @user3467895: Trivial examples tend to have trivial solutions and workarounds, and are not very convincing. Things get tricky when you're looking at non-trivial setups, e.g. conversion constructors turning your integer into a `MyClass` instance implicitly. Global functions are not a problem *in themselves*, but they are the hallmark of untidy code, and can *lead* to problems. Usually *much* later on...
Comment: And how do these two source files have to be related for these linker errors to occur?
Comment: On your second point, can you describe a situation where 'you might end up calling a different function than what you expected'. I tried it out in a test project and it compiled and linked fine and called the helper from the current file.
Comment: @user3467895 Re 2nd point: Existing code which calls `helper(long)`with an `int` argument will perhaps unexpectedly call the better matching `helper(int)` when that function is added to the global namespace. (This will require a visible declaration though, for example in a header. If both functions are defined and used in only one file declaring them static will change nothing to the better.)
Answer: Ulrich Drepper's paper on shared ELF libraries is relevant for you if you produce dynamically shared objects, usually shared libraries. I assume that some considerations also apply to applications which just are dynamically linked. The paper discusses the GNU tools but similar concerns will likely apply to other tool chains.
In short there may be build-time, load-time and run-time penalties for global objects and functions.
Build- and load-time penalties are rooted in the number of (string) comparisons needed to resolve dependencies which are not necessary for locally-defined symbols like file static functions and variables. Drepper discusses this at page 8 using the example of OpenOffice.
The reason for run-time penalties is ELF specifying that even locally-defined but global symbols could be replaced at run time with definitions in other objects. Therefore function code cannot be inlined and further optimized, even though it is visible at compile time; and the function call proper is more complicated than necessary, involving more indirections. See Drepper's paper, pp. 17 and 18.


Prove that $\sum_{n = 1}^{N} \text{arccot}^{2} (\sqrt{n^2+n+1}-x)$ has a bound for $x \in \mathbb{R}$

Question: Consider $\sum_{n = 1}^{N} \text{arccot}^{2} (\sqrt{n^2+n+1}-x)$. I need to prove that it is bounded by a universal constant not depending on $N$ or $x$. I could consider an integral on $\int_{0}^{\infty}$, but i guess it's couldn't be represented as elementary functions. Also I thought that this function is periodic (depending of $x$) and so it could be bounded.
But maybe there is a better way to show the bound ?
Comment: @Winther how to show that bounded by $\pi^{2} / 4$?
Comment: But what about $\sqrt{n^{2}+n+1}$ term ?
Comment: @JackD'Aurizio I just want to prove that for $\forall N \in \mathbb{N}$ this sum is bounded by some constant (which doesn't depend of $N$).
Comment: @openspace: is the wanted constant allowed to depend on $x$?
Comment: @JackD'Aurizio I guess no. Actually that's part of Dirichlet's test for $\displaystyle \sum \frac{arcctg^{2}(\sqrt{n^{2}+n+1}-x)}{\sqrt{n}}$, so I need to prove that particular sum is bounded.
Answer: $$\sum_{n\geq 1}\arctan^2\frac{1}{\sqrt{n^2+n+1}-x}\leq\sum_{n\geq 1}\min\left[\frac{\pi^2}{4},\frac{1}{\left(\sqrt{n^2+n+1}-x\right)^2}\right] $$
and for any $x\in\mathbb{R}$ there are at most $2$ values of $n\geq 1$ such that $\left|\sqrt{n^2+n+1}-x\right|\leq\frac{2}{\pi}$. By excluding these terms (if existing), the contribution provided by the remaining terms is bounded by $\sum_{n\in\mathbb{Z}\setminus\{0\}}\frac{1}{n^2}=\frac{\pi^2}{3}$, hence
$$\sum_{n\geq 1}\arctan^2\frac{1}{\sqrt{n^2+n+1}-x}\leq \frac{5\pi^2}{6}$$
holds. It is a pretty crude inequality, but it does the job.
Comment: @openspace: we consider $\arctan^2(z)\leq z^2$ then replace $z$ with $\frac{1}{\sqrt{n^2+n+1}-x}$.
Comment: I guess there should be $max$?
Comment: @openspace: no no, it is a min. $\arctan^2(x)$ is simultaneously bounded by $\frac{\pi^2}{4}$ and $x^2$, so by their minimum.
Comment: And we take $\frac{1}{(\sqrt{n^{2}+n+1}-x)^{2}}$, because of Taylor representation?
Comment: And why we get $\frac{5\pi^2}{6}$?
Comment: @openspace: we have at most two "ugly" terms giving a contribute $\leq 2\cdot\frac{\pi^2}{4}$, the remaining terms give a contribute $\leq \frac{\pi^2}{3}$ and $\frac{1}{2}+\frac{1}{3}=\frac{5}{6}$.


List of objects based on user relationships

Question: So I've got a model, Post, which is related to a User. Users can have connections (basically just friends). I would like to get a list of all posts made by a user's connections. I've already got something that works, but this is getting into territory that is unfamiliar to me, and I'd be very appreciative of any advice anyone can give me in terms of performance and best practices. Here is what I have so far:
    connections = self.request.user.connections.all()
    id_list = []
    for connection in connections:
        id_list.append(connection.to_user.id)
    posts = Post.objects.filter(user__in=id_list)

Any help is much appreciated. I'm sure there're more Django-y ways of doing this.
Answer: Simpler:
posts = Post.objects.filter(user__in=self.request.user.connections.all())

Answer: You can directly use a queryset with the in lookup. This will translate your lookup directly into a database query. So, the overhead of the for loop is saved.
connections = self.request.user.connections.all()
posts = Post.objects.filter(user__in=connections)

Also, this is a django-y way :)


Fit line to width with Pango and Cairo (Pycairo)

Question: I've several lines of text and I'd like each to fit in width (scaling the font size) to the width of the Context. Is there a way of doing this?
I'm using pangocairo and python for this.
Answer: I wish to have time for a working solution, but you can start with something like:
import cairo
import pango
import pangocairo
import sys

W = 500
H = int(1.4 * W)

surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H)
context = cairo.Context(surf)

#draw a background rectangle:
context.rectangle(0, 0, W, H)
context.set_source_rgb(1, 1, 1)
context.fill()

#get font families:

font_map = pangocairo.cairo_font_map_get_default()
families = font_map.list_families()

# to see family names:
#print sorted([f.get_name() for f in   font_map.list_families()])

# context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)

# Translates context so that desired text upperleft corner is at 0,0

text = """Fit line
to width with
Pango
and Cairo"""

fontname = "Arial"
context.set_source_rgb(0, 0, 0)

y = 0
for line in text.split("\n"):
    pangocairo_context = pangocairo.CairoContext(context)
    pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    layout = pangocairo_context.create_layout()
    font = pango.FontDescription(fontname + " 25")
    layout.set_font_description(font)
    layout.set_text(line)
    pangocairo_context.update_layout(layout)
    w, h = layout.get_pixel_size()
    print w, h, y
    context.translate(0, y)
    pangocairo_context = pangocairo.CairoContext(context)
    pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    layout = pangocairo_context.create_layout()
    font_descr = "{} {:0.1f}".format(fontname, float(W) / w * 25)
    font = pango.FontDescription(font_descr)
    layout.set_font_description(font)
    layout.set_text(line)
    _, y = layout.get_pixel_size()
    pangocairo_context.update_layout(layout)
    pangocairo_context.show_layout(layout)

with open("cairo_text.png", "wb") as image_file:
    surf.write_to_png(image_file)

Result:

I will left improving this algorithm as an exercise for the reader, you can try to:

verify the width of the layout after scaling the font and adjusting
render in a big font size and scale pangocairo_context instead
I don't know, in fact I knew nothing about pycairo until I read your question and goggled for the docs.


Parallelogram: find the difference between the lengths of the diagonals?

Question: Two different sides of a parallelogram are $8 \ \mathrm{cm}$ and $6 \ \mathrm{cm}$ and the ratio of the diagonals is 3 : 4.
Find the difference between the lengths of the diagonals?
I clearly understood that if $x$ & $y$ are the diagonals, then $x=4k$ and $y=3k$ where $k$ is some constant.
We know that the $x + y = 2 (a + b)$ where $a$ and $b$ are sides.
But still I am not able to get the right answer.
There is no option in MCQ:

5
7
8
$\sqrt8$
Answer: You can apply the cosine's law twice to obtain what follows:
\begin{align*}
\begin{cases}
x^{2} = 6^{2} + 8^{2} - 2\times 6\times 8\cos(\theta)\\\\
y^{2} = 6^{2} + 8^{2} + 2\times 6\times 8\cos(\theta)
\end{cases} \Rightarrow x^{2} + y^{2} = 200
\end{align*}
Since $4x = 3y$, one gets the solution $(x,y) = (6\sqrt{2},8\sqrt{2})$ according to the calculations:
\begin{align*}
\begin{cases}
x^{2} + y^{2} = 200\\\\
4x = 3y
\end{cases} \Longleftrightarrow
\begin{cases}
16x^{2} + 16y^{2} = 3200\\\\
4x = 3y
\end{cases} \Longleftrightarrow
\begin{cases}
25y^{2} = 3200\\\\
4x = 3y
\end{cases} \Longleftrightarrow
\begin{cases}
y^{2} = 128\\\\
4x = 3y
\end{cases}
\end{align*}
Consequently, the answer should be $y - x = 2\sqrt{2} = \sqrt{8}$, and we are done.
Hopefully this helps!
Comment: Oh damn! so i got it wrong its not x + y = 2 (a + b)
Answer: Let's look at the parallelogram ($ABCD$) OP's talking about:

According to the question, AB = 8 cm and AD = 6 cm. Also given that $\frac{BD}{AC}=\frac{4}{3}$. Asking is what the difference between the lengths of the diagonals $(BD - AC)$.
This cab be easily solved by applying Law of cosines twice on two triangles carring these two diogonals. Suppose $AC = x$, $BD = y$, and $\angle ADC = \alpha$. Thus, parallelogram's propaties gives us, $\angle BCF = \alpha$ and $\angle BCD = \pi -\alpha$.
Now let's apply Law of cosines on $\triangle ACD$ where $AC=x, AD = 6,$ and $CD = 8$:
$$x^2 = 6^2 + 8^2 - 2\times 6\times 8\cos (\alpha) \tag1$$
Now again, apply Law of cosines on $\triangle BCD$ where $BD=y, BC = 6,$ and $CD = 8$:
$$y^2 = 6^2 + 8^2 - 2\times 6\times 8\cos (\pi - \alpha) = 6^2 + 8^2 + 2\times 6\times 8\cos (\alpha) \tag2$$
Add the equations $(1)$ and $(2)$ to give:
$$x^2 + y^2 = 2(6^2 + 8^2) = 200 \tag3$$
Since $\frac{y}{x}=\frac{4}{3}$ thus $4x = 3y$, you can get the solution by simplifying the equation $(3)$ easily:
$$\left(\frac{3}{4}y\right)^2 + y^2 = \left(\frac{9}{16}\right)y^2 + y^2 = \left(\frac{25}{16}\right)y^2 =200 $$
$$\therefore \ y = \sqrt{8 \times 16} = 4\sqrt{8}$$
Thus, $x = \frac{3}{4} y =\frac{3}{4} \times 4\sqrt{8} = 3\sqrt{8}$
Consequently,
$$y - x = 4\sqrt{8} - 3\sqrt{8} = \sqrt{8}$$
Comment: I really like the way how you taken some time to put the figure and explain. Thank you
Answer: $$x^2 + y^2 = 2 (A^2 + B^2)$$
Where,
$x$ & $y$ are the diagonals of a parallelogram;
$A$ & $B$ are the sides which is in our case 8 & 6
And we got the ratio as 3:4 nothing but $x=4k$ & $y=3k$
$$16k^2+9k^2=2(8^2+6^2)$$
from which $$k=\sqrt8$$
now that we need the difference
rest is simple calculation.
Answer is $$k=\sqrt8$$
Comment: thanks for the edit @mathew


Android creating a folder using shell or command within app

Question: I know that there are other ways to create folder in  android I am doing this for learning purpose.
Here is my code
val cmd="mkdir -p /external_files/hell"
            val process=Runtime.getRuntime().exec(cmd)
            val bufferedReader = BufferedReader(InputStreamReader(process.inputStream))
            var line="d"
            while (line!=null) {
                line=bufferedReader.readLine()
                if(line!=null)
                Log.d("tag", line)
            }

I am testing in  real oreo device. Folder is not created and I get this error.
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.testterminal, PID: 8516
    java.lang.IllegalStateException: bufferedReader.readLine() must not be null
        at com.example.testterminal.MainActivity$onCreate$1.onClick(MainActivity.kt:28)
        at android.view.View.performClick(View.java:6304)
        at android.view.View$PerformClick.run(View.java:24803)
        at android.os.Handler.handleCallback(Handler.java:794)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6651)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

Answer: Use :-
val dir = File(context.getExternalFilesDir(null), "/Your Directory")
if(!dir.exists()) {
    dir.mkdirs()
}


function in inc file not being found

Question: I put this function in my inc file
function getLanguage(){
  $url=url() ;
  $language="";
  $pos=strpos($url,"/es");
  if ($pos===false){
    $language="en";
  }else{
    $language="es";
  }
  return $language;
}

And then I try to call that function from the module, but the module says Fatal error: Call to undefined function getLanguage()
What am I doing wrong? thanks
Comment: Any files other than the .module file (exceptions are, the .install file and autoloaded classes) are not loaded unless you explicitly load them or specify the file location in the relevant hook.
You can use module_load_include() to include the file before calling the function.
Comment: Where exactly would you put the module_load_include()? which part of the module?
Comment: I am now putting  module_load_include('inc', 'mymodule', 'mymodule');  at the beginning of every function in the module, but isnt there some way to put it at the top of the module and not have to repeat it in every function?
Comment: You're understanding it the wrong way round, within the .module file you put your hooks and shared functions.

Usually in the callbacks, you get to declare 'file' to point to an include for your functions to reside in a nice separate place.  See https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7 and https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_theme/7
Answer: thank you pobtastic, this is the answer:
within the .module file you put your hooks and shared functions. Usually in the callbacks, you get to declare 'file' to point to an include for your functions to reside in a nice separate place. See api.drupal.org/api/drupal/modules%21system%21system.api.php/… and api.drupal.org/api/drupal/modules%21system%21system.api.php/… –  Pobtastic 1 hour ago

function in inc file not being found


Covariance of prior and posterior normal distributions

Question: Suppose I have a parameter $\mu$ with a normal prior distribution with mean $\mu_0$ and standard deviation $\sigma_0$. On learning data $D$ with normal likelihood, with empirical mean $\mu_D$ and empirical standard deviation $\sigma_D$, the posterior is a normal distribution with mean $\mu'$ and standard deviation $\sigma'$ (which can be found in terms of $\mu_0,\sigma_0,\mu_D,\sigma_D$).
I am interested in a (weighted) sum of the prior and posterior, which is normally distributed. To find the standard deviation, we need the covariance of prior and posterior. Presumably, these are entirely dependent with covariance $1$, but I am unsure if that's right and if so I am unsure how to prove it.
Comment: I'm getting a strong x/y problem vibe out of this. Could you elaborate why are you looking for that weighted sum?
Comment: I'm doing Bayesian inference with uncertain data. So rather than updating to the normal posterior via Bayes' rule, I'm using something like Jeffrey's rule. I'm interested in the sum of prior and posterior, weighted by the probability that the data is correct
Answer: This question does not seem to make sense from a probabilistic viewpoint. Both the prior and the posterior distributions are covering the same random variable, $\theta$ say, the prior being the marginal distribution of $\theta$ and the posterior the conditional distribution of $\theta$. It is thus impossible to consider a linear combination

of the prior and posterior, which is normally distributed

since, again, this is the same random variable.
Comment: yeah, thanks. what I originally wrote was clearly quite confused. What I mean is that I want a pdf given by a weighted sum of the prior ($p$) and posterior (given data $D$): $\bar{p}(\theta)=wp(\theta)+(1-w)p(\theta|D)$.

In this case, the prior and posterior are both normal distributions
Comment: Then the mixture of prior and posterior (a) is not a Normal (b) does not involve a correlation coefficient and (c) has no direct meaning from a Bayesian point of view.
Comment: Thanks, yep, makes sense. Yes, although this isn't used in classical Bayesianism, it makes sense when one is uncertain about the evidence that one is updating on. (https://statweb.stanford.edu/~cgates/PERSI/papers/AltBayes.PDF)


Can PXE Boot in UEFI but not in Legacy

Question: looking for some advice on why my lab setups is acting this way regarding PXE boot.
A breakdown of the unit is:

Host OS is  Server 2016 running hyper V with 2 VMS Hyper V
VM1 is the  DC, running AD, DHCP , DNS
VM2  WDS

When I PXE boot a Client (Dell E7470 7480 ) while the Pre-OS environment (Firmware) is in UEFI mode it works like a charm pulls down the NBP file and can then take an install.wim
however if I change the client it to Legacy BIOS it PXE boots and receives the error PXE-E53 No Bootfile name received.
Within DHCP if I set 66 to the IP of the WDS server and 67 as says \boot\x64\wdsnbp.com it then works in Legacy but doesnt in UEFI
the reason I'm confused is because i shouldnt have to set option 66 67 within DHCP as the WDS is on a different VM.
what am i missing here to be able to PXE both legacy and UEFI machines without having to change options every time I want to do so?
I can get the client working in both UEFI and Legacy but only seperately
thanks all
Comment: Your question doesn't look very well on the first spot, but I think it could be made much better with only a little work. Read [this](https://meta.stackoverflow.com/questions/291362/advice-for-non-native-english-speakers/291370#291370).
Answer: PXE UEFI and BIOS clients boot different NBPs (Network Boot Program).
The PXE booting clients announce their Pre-OS environment mode by using DHCP Option 93 (RFC 4578) on their DHCPDISCOVER packet.
Then the PXE enabled DHCP Server parsing option 93 decides which NBP to offer.
In your case your DHCP server is not offering a NBP for BIOS clients while is correctly providing it for UEFI clients
Comment: Thanks for the input. Any idea as to why its not offering an NBP for Legacy units when it should do as it does for UEFI? I understand its putting a proxy request in for the correct architecture but I cant understand why it would fail on Legacy based on this query alone. WDS is separated from the DC completely so it should not require any scope options to be set to get this working.
Comment: your DHCP server must be using a custom vendor class  and `different DHCP (architecture based) policies` for the following DHCP Options: Option 60 Option 66 Option 67. See how here https://www.experts-exchange.com/articles/29394/Using-DHCP-to-Boot-WDS-to-BIOS-UEFI-with-SCCM.html
Comment: those policies require that open 60 be set within a specified DHCP policy combined with a specified Vendor Class. However; as WDS is not on the same VM as DHCP Option 60 does not become available under DHCP standard options.
Comment: Can't you see that in this case option 60 is always constant...= "PXEClient" . This is the answer to your problem now you have to implement it; That's it.
Answer: There are different ways of setting up WDS/PXE boot - either WDS responds to a broadcast from the DHCP client OR DHCP server tells the DHCP client to contact the WDS server (options 66+67).
In your situation (one subnet, DHCP and WDS on different servers) it should just work without options 60, 66 or 67 (according to Google), though I don't know which boot loader it picks in that case. Looking at our system, that's what we have here (which works - 2012R2, DHCP + WDS on different servers, routed network) - none of 60, 66, 67 options are set and we can boot legacy or UEFI.
You could at a push use DHCP policies to set the options for different machine types (eg different MAC address prefixes) - so for instance only set 66/67 for a subset of machines, leave the rest unset.
Options 66 and 67 are useful when you have a routed network. you can either set 66 and 67 OR add the IP of the WDS server to ip helpers on the routers (as we have here)
Hope that helps.
Comment: Im at a loss of why its doing this. I've tried different gen client units from haswell up to kabylake incase it was something strange with the client but only UEFI seems to pull down the boot.wim. when this setup should work. I know DHCP etc works all well and fine because of the successful UEFI build
Comment: The PXE-E53 error relates to it not being able to download a file via TFTP. This has nothing to do with .wim files - it hasn't got that far in the boot process yet. What have you got for DHCP option 67? It pulls this file via TFTP, I'm pretty sure its case sensitive. Have you tried putting nothing for 66 + 67? What do you get then?
Comment: Hi, Option 66 and 67 are not set because WDS is on a seperate VM but on the same subnet, it shouldn't require these options to be set. It would only need to be set if WDS was installed on the domain controller with DHCP active on that.  However; if i set 66 and 67 LEGACY PXE does work but then UEFI doesnt work. Its  a very strange issue as i shouldnt have to set a bootfile NBP or direct the client to a specific TFTP location. WDS on the seperate VM should proxy this by itself.
Comment: Also, see https://technet.microsoft.com/en-us/library/cc732351(v=ws.10).aspx - What have you got set in the boot tab of server properties?
Answer: I'm not sure that this goes for the E7440, but on the Latitude 7480 you will need to activate the UEFI network stack, to get this to work.
On the 7480 that setting is found under System Configuration -> Integrated NIC.
It's a checkbox called "Enable UEFI Network Stack"

Can PXE Boot in UEFI but not in Legacy


SwiftyJSON Alamofire How to return what you got?

Question: How to return what you got?Excuse me, novice, I understand only.enter image description here
enter image description here
Comment: You should always copy your code into your question, instead of adding a screenshot. It just makes it difficult to test your code when we need to rewrite it.
Comment: You are missing either concept or vocabulary/key words to do a proper search on your issue: "Async (or asynchrone) + Swift + Closure"
Answer: Alamofire.request is an asynchronous task, so any code written after this is most likely going to be executed before the task is complete. There are a few ways of doing what you want, but since you haven't provided much information, I have just moved the JSON inside the closure. So you should get something to print out.
Alamofire.request("https://...").responseJSON { (response) in

    // Inside this closure is where you receive your JSON

    if let value = response.value {

        let json = JSON(value)

        let title = json["posts", 3, "title"].stringValue

        print("Title:", title)
    }
}

// Any code after this request will most likely be executed before
// the request has completed because it is done asynchronously.

This is another way that might work better for you.
I understand that you are a beginner and these kinds of operations can be quite complex. You need to understand the order at which code get executed, and how variables work. You are getting that error because swiftyJsonVar is declared in a block that is not accessible to code in the viewDidLoad. I suggest you learn about multi-threading and other asynchronous tasks and probably learn how to declare and use variables properly.
override func viewDidLoad() {
    super.viewDidLoad()

    load { (json) in

        if let json = json {

            let title = json["posts", 3, "title"].stringValue

            print("Title:", title)
        }
    }
}

func load(completion: @escaping (JSON?) -> Void){

    Alamofire.request("https://httpbin.org/get").responseJSON { (response) in //https://...

        var json: JSON?

        if let value = response.value {

            json = JSON(value)
        }

        completion(json)
    }
}

Comment: It is clear to me. Under my question I meant: how to handle the fact that json received from Alamofire.request. For example it will write error(does not see the variable):
Comment: `override func viewDidLoad() {
        super.viewDidLoad()

        load()
        var oneTitle = swiftyJsonVar["posts", 3, "title"].stringValue
        print("Title: " + oneTitle)

    }
    func load(){

        Alamofire.request("https://gg").responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let swiftyJsonVar = JSON(responseData.result.value!)

        }

        }

    }`
Comment: I understand that the compiler executes the program from the top down. But the question is, can I get json from Alamofire.request and write it into a variable declared in the program. Ie, that would then use the received data.
Thanks for the answers, I really appreciate them.
Comment: What I have shown above is how you are suposed handle these kinds of requests. Also in this case, the code doesn't really run top to bottom, because `Alamofire` requests are done `asynchronously`. You need to understand how that works. I suggest looking at other `Alamofire` questions on this site.


Bounding boxes around all the different objects in an image

Question: Given an image, I want to get bounding boxes around all the objects detected in the image. The type of objects is not of concern to me. Is there an effective way to do so or at least tell me where should I start?
I searched about it and found that given an image we can detect the object of a defined type once the network learns to detect that object. But the image in my case can have any random objects and it is not feasible to train a network to detect all the different objects there are. Can we use the fact that we don't want to know the type of the object, just something that distinguishes one object from another and bounds it in a box?
Please help me out in this regard.
Answer: You can use a model like YOLO trained on COCO dataset that has 80 classes of objects. But to detect any object of any type, I have not seen any model like that.