Remove content of a list out of other list

Question: I have some code that creates a list with numbers, from 1 to 407. What I want to do it to take the numbers of the "ultimate" and "super_rare" list out of the "common" list. How can I do that? This is the general code I have.
import random

def common(x):
    list = []
    for i in range(1,x+1):
        list.append(i)
    return (list)

cid = common(407)

ultimate = [404, 200, 212, 15, 329, 214, 406, 259, 126, 160, 343, 180, 169, 297, 226, 305, 250, 373, 142, 357, 181, 113, 149, 399, 287, 341, 37, 284, 41, 328, 400, 217, 253, 204, 290, 18, 174, 36, 310, 303, 6, 108, 47, 298, 130]

super_rare = [183, 349, 134, 69, 103, 342, 83, 380, 93, 56, 86, 95, 147, 161, 403, 197, 215, 312, 375, 359, 263, 221, 340, 102, 153, 234, 54, 7, 238, 193, 90, 367, 197, 397, 33, 366, 334, 222, 394, 371, 313, 83, 276, 35, 351, 83, 347, 170, 57, 201, 137, 188, 179, 170, 65, 107, 234, 48, 2, 85, 74, 221, 23, 171, 101, 377, 63, 248, 102, 272, 129, 276, 86, 88, 51, 197, 248, 202, 244, 153, 138, 101, 330, 68, 368, 292, 340, 315, 185, 219, 381, 89, 274, 175, 385, 19, 257, 313, 191, 211]

def new_list(cid, ultimate):
    new_list = []
    for i in range(len(cid)):
        new_list.append(cid[i])

    for i in range(len(ultimate)):
        new_list.remove(ultimate[i])
    return (new_list)

#print (new_list(cid, ultimate))
cid_mod0 = new_list(cid, ultimate)
cid_mod1 = new_list(cid_mod0, super_rare)

print (cid_mod0)

Most of the prints and whatnot are just tries to see if it's working.
Answer: I recommend using sets for this. You can check if an item is in a set in constant time. For example:
import random

def common(x):
   return list(range(1, x + 1))

cid = common(407)

ultimate = { 404, 200, ... }
super_rare = { 183, 349, ... }

def list_difference(l, s):
  return [ elem for elem in l if elem not in s ]

cid_mod0 = list_difference(cid, ultimate)
cid_mod1 = list_difference(cid_mod0, super_rare)

If you don't care about the order of your resulting list you can use a set for that as well for a bit more convenience:
import random

def common(x):
   return list(range(1, x + 1))

cid = set(common(407))

ultimate = { 404, 200, ... }
super_rare = { 183, 349, ... }

cid_mod0 = cid - ultimate
cid_mod1 = cid_mod0 - super_rare

Comment: I tried that last one but it says "unsupported operand type(s) for -: 'list' and 'list'.
Comment: Did you try exactly as it is now? I had a little typo in there sorry.
Comment: I tried it with the new version and the same error appears :/
Comment: Strange, I ran this and it worked for me. did you wrap `cid` in `set` and change `ultimate` and `super_rare` to curly braces? You can wrap them in `set` as well.
Comment: The curly braces were missing, now it's running perfectly, thank you!
Answer: Use this loop to remove the elements out of common that are in the super_rare and ultimate lists:
for x, cnum in enumerate(cid):
    if cnum in ultimate or cnum in super_rare:
        del cid[x]
print(cid)

The loop assumes you have a list named cid that is already established.
Comment: I tried that one, but it says " 'function' object is not iterable" on "for x, cnum in enumerate(common): "
Comment: Try it now with the new edits. I didn't see your list was called `cid`.
Comment: It doesn't give an error anymore but when I printed it, it just gave me a loop printing the list
Comment: Outside of the loop, `print(cid)`
Answer: You can create your target list that includes all the numbers from the target range, but without those numbers from ultimate and super_rare list, by list comprehension:
my_filtered_list = [i for i in range(1, 408) if i not in ultimate and i not in super_rare]
print(my_filtered_list)

Comment: I'm sorry, I'm a beginner at this, I don't know how and where should I write that xD
Comment: I edited my answer.  That list contain all the numbers you need.
Answer: Make a union set of both sets of numbers you want to exclude.
>>> su = set(ultimate) | set(super_rare)

Then filter the input list based on whether the value is not present in the set.
>>> list(filter(lambda i: i not in su, cid))
[1, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 16, 17, 20, 21, 22, 24, 25, 26, 27, 28,
 29, 30, 31, 32, 34, 38, 39, 40, 42, 43, 44, 45, 46, 49, 50, 52, 53, 55, 58, 59,
 60, 61, 62, 64, 66, 67, 70, 71, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 84, 87,
 91, 92, 94, 96, 97, 98, 99, 100, 104, 105, 106, 109, 110, 111, 112, 114, 115,
 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 127, 128, 131, 132, 133, 135,
 136, 139, 140, 141, 143, 144, 145, 146, 148, 150, 151, 152, 154, 155, 156, 157,
 158, 159, 162, 163, 164, 165, 166, 167, 168, 172, 173, 176, 177, 178, 182, 184,
 186, 187, 189, 190, 192, 194, 195, 196, 198, 199, 203, 205, 206, 207, 208, 209,
 210, 213, 216, 218, 220, 223, 224, 225, 227, 228, 229, 230, 231, 232, 233, 235,
 236, 237, 239, 240, 241, 242, 243, 245, 246, 247, 249, 251, 252, 254, 255, 256,
 258, 260, 261, 262, 264, 265, 266, 267, 268, 269, 270, 271, 273, 275, 277, 278,
 279, 280, 281, 282, 283, 285, 286, 288, 289, 291, 293, 294, 295, 296, 299, 300,
 301, 302, 304, 306, 307, 308, 309, 311, 314, 316, 317, 318, 319, 320, 321, 322,
 323, 324, 325, 326, 327, 331, 332, 333, 335, 336, 337, 338, 339, 344, 345, 346,
 348, 350, 352, 353, 354, 355, 356, 358, 360, 361, 362, 363, 364, 365, 369, 370,
 372, 374, 376, 378, 379, 382, 383, 384, 386, 387, 388, 389, 390, 391, 392, 393,
 395, 396, 398, 401, 402, 405, 407]

If you don't want to use filter, just use a list comprehension.
>>> [v for v in cid if v not in su]

You could also do the whole thing with sets like
>>> list(set(cid) - (set(ultimate) | set(super_rare)))

Others have suggested this already (I take no credit). I'm not sure how guaranteed it is to come back in the right order. Seems to be ok on my py2 and py3, but doing the last step as a list will give you the order absolutely guaranteed (not as an implementation detail) and wont need converting back to a list as a final step.
If you want to see the changes in the original list, you can just assign back to the original variable.
cid = [v for v in cid if v not in su]

This is assigning a different list to the same variable though, so other holders of references to that list won't see the changes. You can call id(cid) before and after the assignment to see that its a different list.
If you wanted to assign back to the exact same list instance you can use
cid[:] = [v for v in cid if v not in su]

and the id will remain the same.
Comment: @curious was wondering if you made any progress on your problem?
Comment: It didn't give me an error! But I printed the original cid list and it prints all the numbers from 0 to 407.
Comment: This creates a new list. The original is not changed. So you wanted to change the original list?
Comment: Yes, I want the original list to stop having those numbers.
Comment: Ok well just assign back to `cid`. `cid = [v for v in cid if v not in su]`. `cid` will point to a new list in this case though. A way to assign back to the original list is to use `cid[:] = [v for v in cid if v not in su]`.
Answer: If you want to keep the original order for cid, you could try to use OrderDict to convert cid as an ordered dict object, and then remove keys that you want, the code would be something like:
from random import choices, seed
from collections import OrderedDict

seed(123)

ultimate = [404, 200, 212, 15, 329, 214, 406, 259, 126, 160, 343, 180, 169, 297, 226, 305, 250, 373, 142, 357, 181, 113, 149, 399, 287, 341, 37, 284, 41, 328, 400, 217, 253, 204, 290, 18, 174, 36, 310, 303, 6, 108, 47, 298, 130]
super_rare = [183, 349, 134, 69, 103, 342, 83, 380, 93, 56, 86, 95, 147, 161, 403, 197, 215, 312, 375, 359, 263, 221, 340, 102, 153, 234, 54, 7, 238, 193, 90, 367, 197, 397, 33, 366, 334, 222, 394, 371, 313, 83, 276, 35, 351, 83, 347, 170, 57, 201, 137, 188, 179, 170, 65, 107, 234, 48, 2, 85, 74, 221, 23, 171, 101, 377, 63, 248, 102, 272, 129, 276, 86, 88, 51, 197, 248, 202, 244, 153, 138, 101, 330, 68, 368, 292, 340, 315, 185, 219, 381, 89, 274, 175, 385, 19, 257, 313, 191, 211]

cid = OrderedDict.fromkeys(choices(range(407), k=407))
_ = map(cid.pop, set(ultimate + super_rare))

result = cid.keys()

If you don't need the original order, you could try to convert cid as a dict, it's superfast to remove key from a hashmap, the code would be something like:
cid = dict.fromkeys(range(407))
_ = map(cid.pop, set(ultimate + super_rare))

result = cid.keys()

Apart from the dictionary method, you can also try to convert everything into a set variable like the following:
result = set(range(407)) - set(ultimate) - set(super_rare)

Hope it helps.
Comment: I ended up with this:
`
return (list(range(1, x+1)))

cid = set(common(407))
cid_mod0 = cid - ultimate
cid_mod1 = cid_mod0 - super_rare
`
(there's some code missing but it isn't very important) and I changed the vars to dictionaries. Now I'm trying to call .random.choice() on cid_mod1 but it says, on that line, " 'set' object is not subscriptable. Since you talked about sets, I was hoping you could help me.
Comment: Hi @curious , random.choice() is trying to create some random data, you don't have to use that if unnecessary, maybe you can try to convert that set object to a list object, e.g. cid_mod1 = list(set( YOUR-OBJECT )).


Is it possible to use Survival Analyis on a time series to predict events?

Question: I have a time-series of noisy data which occasionally triggers an event, and once that happens, the noise calms down and the cycle repeats itself (until the event is triggered once again). What I want to try and model is essentially the likelihood of the event occurring at any point throughout my univariate time series.
For example, in the picture below, the blue line measures the time to event, with the red line being the actual data. How could I predict when the blue line dips/the event occurs?
I thought Survival analysis would fit the bill, as it deals with modelling time to events, but I have had difficulty locating the right resources, and would appreciate any advice.
Answer: You may be looking for joint models.
These models are a combination of a survival model to consider events and a mixed model to take into account evolution of some factors over time.
There is a R tutorial you can try (never tried myself so I'm no help sorry), and here is what it says you can do (I added bold in what you should be interessed in):

The whole model and its parts can be extended in several ways:

To find latent population heterogeneity (latent class joint models).
Allow for multiple longitudinal markers.
Allow for the analysis of multiple failure times. This is the case of competing risks and recurrent events (for instance, when a child develops asthma attacks, to find the risk of recurrence).
Time-Dependent accelerated failure time (AFT) Models.
Dynamic predictions when new values are added for the longitudinal variable, using Maximum Likelihood Estimates and empirical Bayes
  estimates.
Comment: Huh, absolutely never heard of them before. Will take a look, and report back at some point. Thanks!


In Windows 7 identify ip of a mapped drive and reconnect it

Question: I know that I can show mapped drives in windows 7 using
c:\>net use
and it shows
Status       Local     Remote                    Network
-------------------------------------------------------------------------------
OK           X:        \\192.168.168.100\c\Output
                                            Microsoft Windows Network
OK           Y:        \\192.168.168.100\c\Input
                                            Microsoft Windows Network

Is it possible to discover if X (or Y) are connected to ip 192.168.168.100 ?
And in this case disconnect them using
net use X: /delete
net use Y: /delete

and reconnect them to same path but different ip using (from 192.168.168.100 to 192.168.168.101)
net use X: \\192.168.168.101\c\Output /user:user01
net use Y: \\192.168.168.101\c\Input  /user:user01

and viceversa, if they are connected to 192.168.168.101, disconnect and reconnect
to 192.168.168.100
Can someone help me to parse the net use output ?
Comment: It looks like you figured it out. What specifically do you need help with?
Comment: I don't know how to identify, within a .bat, if the mapped drive refers to 192.168.168.100 or 192.168.168.101 and then act accordingly
Comment: As you saw, you can use the `net use` command and parse the output.
Comment: Can someone help me to parse the net use output ?
Comment: You can use the `for` command to parse the output of a command. Type `for /?` for details.
Answer: Not pretty but it works in my limited testing:
@echo OFF
setlocal ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
goto start

:checkone
setlocal
echo INFO: %3 is mapped to drive %2
set "server="&set "new="
for /F "usebackq tokens=1,* delims=\" %%A in ('%3') do @set server=%%A&set share=%%B
if "%server%"=="192.168.168.100" set new=192.168.168.101
if "%server%"=="192.168.168.101" set new=192.168.168.100
if not ".%new%"=="." (
    call net use %2 /delete
    call net use %2 \\%new%\%share% /user:user01
)
endlocal
@goto :EOF

:start
for /F "tokens=*" %%A in ('net use^|find ":"^|find "\\"') do @for /F "usebackq tokens=1,* delims=:" %%B in ('.%%A') do call :checkone %%B: %%C

If the remote path has spaces there will probably be trouble...


Is $\sum_{x=1}^n (3x^2+x+1) = n^3+2n^2+3n$?

Question: I wanna check if the following equation involving a sum is true or false? How do I solve this? Please help me.
$$ \sum_{x=1}^n (3x^2+x+1) = n^3+2n^2+3n$$
for all $n \in \{0,1,2,3, \dots\}$.
Comment: I'm not sure if $n=0$ is defined.  $n=1$ is clearly false.  Should that be $x=0$ in the summation maybe?
Comment: A notation cannot be *true* or *false*. It can be *right* or *wrong*. Expressions can be *true* or *false*. So, you want to check if this equality holds for all $n\in N_0$?
Comment: @Mike, for $n=0$ there is no summand, the usual convention is to define an empty sum to be $0$, the neutral element of addition. With that convention the equation holds for $n=0$.
Answer: Not quite. Note that it fails at $n=1$. A closed form expression for the sum is $n^3+2n^2+2n$.
Remark: Recall that $\sum_1^n k^2=\frac{n(n+1)(2n+1)}{6}$ and $\sum_1^n k=\frac{n(n+1)}{2}$. And of course $\sum_1^n 1=n$.
Or else you can prove the result directly by induction.
Answer: $(x+1)^3=x^3+3x^2+3x+1\iff3x^2+3x+1$ is the difference of two consecutive cubes, so the sum will be telescopic, since $3x^2+x+1=(3x^2+3x+1)-2x=\Big[(x+1)^3-x^3\Big]-2x$. $$\sum_{x=1}^n(3x^2+x+1)=\sum_{x=1}^n\Big[(x+1)^3-x^3\Big]-2\sum_{x=1}^nx=\Big[(n+1)^3-1^3\Big]-2\bigg[\frac{n(n+1)}2\bigg]=$$ $$=\Big[(n^3+3n^2+3n+1)-1\Big]-(n^2+n)=n^3+2n^2+2n.$$ See Faulhaber's formula for more information.


Servidor ionic não inicia

Question: Estou iniciando um projeto em ionic (versão 1), porém meu servidor não inicia mais.
Eu digito ionic serve --lab, aparece a seguinte mensagem:
Starting server (address: 0.0.0.0, port: 8100, dev server port: 53703, livereload port: 35729) - Ctrl+C to cancel
[OK] Development server running!
     Local: http://localhost:8100
     External: http://192.168.1.5:8100
     DevApp: AluraCar@8100 on DESKTOP-PQPJV63

Mas quando coloco localhost:8100 no navegador ele diz que não está iniciado.
Alguém tem alguma ideia do que pode ser?
Comment: Experimenta digitar apenas **ionic serve** para iniciar o servidor
Answer: É possível que o seu código esteja com erros, verifique o código na hora de atribuir os valores, que esteja assim:
private foo: number;
private foo = 100;

e não assim:
private foo = number;
private foo: 100;

Comment: Mas onde ficam esses valores?

Servidor ionic não inicia


How to avoid infinite loop in when call a function to change state in useEffect?

Question: On a sub component I have a function that updates a local state based on some conditions. I want to call the function when data changes, but it result in an infinite loop following the useEffect guidelines.
const func(val:any,arr:any[]){
  ...
  setArr(arr)
}

useEffect(() => {
  val && val.length > 0 && func(val,arr)
},[val,func,arr])

Comment: Remove `arr` in `[val,func,arr]`
Comment: React Hook useEffect has a missing dependency: 'arr'. Either include it or remove the dependency array  react-hooks/exhaustive-deps
Answer: const func(val:any,arr:any[]){
  ...
  setArr(arr)
}

useEffect(() => {
  val && val.length > 0 && func(val,arr)
},[val])

I'm hoping val is a variable inside the component function this renders if and only if val changes you have to pass variable which you want useEffect to look out for and make changes based on that change.
adding a function in an array dependency will always lead to an infinite loop because array dependencies watch for changes and render components based on those changes
useEffect: hey function I was told to call you.
Function: hey useEffect I hear you.
useEffect: hey function you answered bro I have to call you again since you're in my dependency.
Comment: Thanks, I changed the useEffect as in your example and everything work except that React keep sending warnings. Val is a local state based on a prop value.
Comment: Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global, Global variables are those declared outside of a block, Local variables are those declared inside of a block . For example, a function is a block of code any code outside that function can't access any variable inside that function.


Show whole taxonomy tree starting from current term

Question: I'm trying to show taxonomy tree starting from current term.
Like this when you are in taxonomy term1 page.

-term1 (this is the term1 page where we are now)
  --term2
  --term3
  ---term4
  ----term5
  ----term6
  -----term7
  -----term8

And if we are for example term4 page then it will show starting from term4:

---term4
  ----term5
  ----term6
  -----term7
  -----term8

I have used Views Tree to but I have not found proper way to "filter" to show right terms when you are for example in term4 page.
All I can get is to show first child level like:

--term1
  ---term2
  ---term3

It should show whole tree starting from current term - as deep as the tree goes.
Comment: Have you tried Views Tree module? https://www.drupal.org/project/views_tree
Comment: @tunic Please read my whole question. I mention there that I have used Views tree, but could not figure out how to show right terms.
Comment: Oops, sorry, I miss that part. I tend to detect module names by its capitalized name.
Answer: Take a look at Taxonomy Menu Block Module

Taxonomy Menu Block allows you to make blocks containing unordered
  lists that represent the structure of your vocabularies, creating a
  menu out of your taxonomies (without using Drupal's menu system).
Comment: Thank you! Very nice! This module did the trick. In Taxonomy Menu block module I did settings: "Select a parent option" to Dynamic parent and "Select a parent level" to Follow active item. Now it shows exactly like I needed it to show.
Comment: Glad it helped.


Find the shortest distance between $y^2=4x$ and $y^2=2x-6$

Question: My attempt:-
differentiating $y^2=4x$
$$y_1'=\frac{4}{2y}$$
and doing the same for $y^2=2x-6$
$$y_2'=1/y$$
for the distance to be the least $y'_1=y'_2$ as the distance between  two lines, hence two tangents and thus two curves is minimised when their slopes are the same
which means $y=0$
that happens at the vertex of the parabolas
the distance between the vertices is 3. However, my book says it's $\sqrt5$
where am  I going wrong?
Comment: See my answer below…
Comment: Your mistake is in assuming that the $y$ values are the same for the corresponding points on the two curves where the tangents have equal gradient.
Comment: oh, so I find a relation between $y_1 and y_2$ and the solve that's it, right?
Answer: I cannot say where you went wrong, since I do not understand your approach. However, note that if $\left(\frac{x^2}4,x\right)$ is an arbitrary point of the first curve and $\left(\frac{y^2}2+3,y\right)$ is an arbitrary point of the second one, then the square of the distance between them is$$f(x,y)=\left(\frac{x^2}4-\frac{y^2}2-3\right)^2+(x-y)^2.$$But$$\nabla f(x,y)=\left(\frac{x^3}4-2y-x-\frac{xy^2}2,-2x+8y-\frac{x^2y}2+y^3\right)$$and then$$\nabla f(x,y)=(0,0)\iff(x,y)=(0,0)\vee(x,y)=\pm(4,2).$$But $f(0,0)=9>5=f(\pm4,\pm2)$, and therefore the minimum is attained at $\pm(4,2)$. And the minimal distance is $\sqrt{f(\pm4,\pm2)}=\sqrt5$.
Answer: Here is another way, without requiring the use of $\nabla$.
Following your idea, the tangent to the curve $y^2=4x$ at the point $(t^2, 2t)$ has gradient $\frac1t$.
Set this equal to the gradient of the curve $y^2=2x-6$ at the general point $(x,y)$, which is $\frac1y$, and we have $y=t$.
Therefore the coordinates of the point on the second curve are$$(x,y)=\left(\frac12 t^2+3, t\right)$$
It follows that the distance $h$ between the points on the two curves where the tangents are parallel is given by $$h^2=\left(t^2-\frac12 t^2-3\right)^2+\left(2t-t\right)^2=\left(\frac12t^2-3\right)^2+t^2$$
Differentiating, $$\frac{dh^2}{dt}=2t\left(\frac12t^2-3\right)+2t=0$$
So we have either $t=0\implies h=3$ or $t=2\implies h=\sqrt{5}$
Comment: Thanks! This was what I was trying to achieve, but I wasn't .
Comment: isn't the derivative of the first curve 2/t?
Comment: No, it's $\frac1t$ as I wrote
Comment: oh, so you have basically differentiated parametrically, right?
Comment: Yes but it works differentiating implicitly or otherwise…
Comment: thanks a lot!!!


How to handle simultaneous editing and deletion of nodes?

Question: This is a slightly different version of the question about what happens when two people are editing and saving the same node.  My version involves node deletion instead of editing:

Alice starts to edit the node (/node/123/edit).
Bob starts to edit the same node (/node/123/edit)
Alice deletes node 123 via the Delete button on the form and the followup "are you sure" page.
Bob, not knowing the node has been deleted, hits the Save button on the form.

Currently, Bob gets a 404 error back from the server -- "The requested page '/node/123/edit' could not be found."  This makes good sense, since the node has in fact gone away, but in a perfect world I would trap the doomed request and send back something a little more helpful, perhaps redirecting the user to a more reasonable page.  Is there any way to do this, short of major surgery on the forms API?  I can't think of one, to be honest -- it's the web server here that's unhappy, not Drupal -- but I thought I'd ask...  Maybe there's a hook out there that I don't know about?
Answer: A better solution may be to use content locking to prevent double editing.
for example: http://drupal.org/project/content_lock
Comment: Yeah, I've thought about that.  Thanks for the suggestion!
Comment: This module seems not to be maintained anymore and have security issues
Answer: You can also use the Workbench module

Workbench provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:

A unified and simplified user interface for users who ONLY have to
  work with content. This decreases training and support time.
The ability to control who has access to edit any content based on an organization's structure not the web site structure
A customizable editorial workflow that integrates with the access control feature described above or works independently on its own
Comment: Can you expand on this a little bit?  I don't recall seeing anything in Workbench that does this.
Comment: i didn't say workbench may do the same,but a delete action need an admin approval


Difference between pre and post gain

Question: I've noticed that some amps instead of just having gain have pre and post gain. I know that gain affect the distortion of the amp, but I don't know the difference between pre and post gain. What is the difference between pre and post gain and is there a reason it is split up?
Answer: Most guitar amps have two amplification stages:

The pre-amp which takes the very low signal levels output by the guitar and amplifies them to a higher level, approximately like line-level.
The power-amp which takes the line-level signal and further amplifies it to drive the speaker.

These are separate since different design considerations are important in amplifying the original signal on one hand, and sending a hefty amount of power to the voice coils in the speaker on the other.
The two amplification stages have different distortion characteristics when they are over driven.
Answer: It's complicated, but the simple answer is:
Post makes it louder.  Presuming you have plenty of headroom in your post amplification stage, that should be all it does.
Pre drives the input harder, causing more distortion.  It does not necessarily make the overall output any louder, but it will tend to compress the peaks in a fuzzy sort of way, and if you keep turning up the pregain you'll simply hear a big mess.

Difference between pre and post gain


How to describe the transformation $\sin(3x)$ to $\sin(3x+\frac{7\pi}{4})$

Question: In my precalculus lab I read the following question incorrectly and hence I believe I have given them incorrect information.

Describe how you can obtain the graph of $y = \sin(3x + \frac{7\pi}{4})$ from the graph of $y = \sin(3x)$.

I initially read the second equation as $y = \sin(x)$. To me this requires a different set of transformations to obtain the desired graph: horizontal compression by a factor of $\frac13$ and apply a horizontal shift of $\frac{7\pi}{12}$ to the left.
Going from $\sin(3x)$ to $\sin(3x + \frac{7\pi}{4})$ requires a horizontal shift of $\frac{7\pi}{4}$ units to the left. I'm imagining what I'd call the "$(3x)y$-plane", i.e. the typical cartesian plane where the horizontal axis is labeled as "3x" instead of the usual "x"
Please help with the following:

Is my correction correct? (Sorry if that sounds weird)
How would you explain this to a group of precalculus students?

Thanks in advance!
Comment: You don't need to re-label anything. Also write it as $\sin(3[x+\frac{7 \pi}{12}[)$
Comment: @randomgirl: This was my initial response to my students, but for some reason it feels odd.
Comment: @randomgirl: To me writing $\sin\left[ 3(x + \frac{7\pi}{12}) \right]$ is telling me what transformations to apply to $\sin(x)$ to obtain the desired graph. I don't believe it tells the correct transformations to apply to $\sin(3x)$.
Answer: The graph of $y=\sin\left(3x + \frac{7\pi}{4} \right)$ has exactly the same shape as $y=\sin\left(3x  \right)$ but shifted $ \frac{7\pi}{12}$ units to the left.  The easiest way to see this is to use function notation:  If
$$f(x) = \sin\left(3x\right)$$
then
$$f\left(x + \frac{7\pi}{12} \right)=\sin\left(3\left(x+\frac{7\pi}{12}\right)\right)=\sin\left(3x + \frac{7\pi}{4} \right)$$
whereas
$$f\left(x + \frac{7\pi}{4} \right)=\sin\left(3\left(x+\frac{7\pi}{4}\right)\right)=\sin\left(3x + \frac{21\pi}{4} \right)$$
Comment: I somehow think I lead myself into thinking that $3x$ is the independent variable which lead me to relabeling the horizontal axis. Silly me.


Javascript with Firefox innerText issue

Question: function OpenWindow(anchor) {
        var toUsername = anchor.innerText;
        window.open("ChatWindow.aspx?username=" + toUsername,'_blank', "width=340,height=200");
    }

this function opens up a page with parameter as undefined in firefox where as in google chrome  I get proper value.
Firefox url:
http://localhost:9452/ChatWindow.aspx?username=undefined
What is the solution for this issue?
Answer: While innerText is non-standard, it significantly differs from textContent, because first one is doing pretty printing (for example,
 are converted to new lines), while second one - is not.
So, while common wisdom is to use:
var toUsername = anchor.innerText || anchor.textContent;

or some kind of wrapper, it can probably be smarter to just use jQuery's .text or its analog from other library you are using.
Answer: try to change anchor.innerText with:
anchor.textContent

this hopefully works in all browsers.
also see here: 'innerText' works in IE, but not in Firefox
P.S. I really reccomend using JQuery to avoid these kind of issues and to be sure to always write fully cross-browser javascript.
Comment: Just a little note: `textContent` does not work in IE8.
Comment: yes exactly, that's why I suggested to use JQuery :)
Answer: innerText is a Microsoft invention whereas textContent is a W3C standard.
function OpenWindow(anchor) {
    var toUsername = anchor.textContent || anchor.innerText || '';
    window.open("ChatWindow.aspx?username=" + toUsername,'_blank', "width=340,height=200");
}

This should work. MooTools or some other JavaScript framework should be able to help with cross-browser inconsistencies.
Comment: MooTools! good one! :)
Answer: use textContent for innerText.
example

it will work on ff. and chrome too. but not work on IE.
Answer: I was getting the same problem because Firefox does not support the innerText property, instead, it supports the textContent property. so check for the browser's feature support to use the correct property accordingly.
if(document.all){
 document.getElementById('element').innerText = "myText";
} else{
document.getElementById('element').textContent = "myText";
}

or it's better to use Jquery to resolve cross browser issues.
Usage:
$('element').text("myText");

Javascript with Firefox innerText issue


Not able to map all the product variations fields in commerce feeds importer

Question: I have one content type and added one field Product Variations' as product reference with widget 'Inline entity form - Multiple values'. But when I used Node Processor, I am not able to map other fields of the product variations. It only shows SKU and Product ID fields in target drop-down. It shows all the fields from node but not from the product variations.
Because of this I am not able to add more fields in my CSV file except title and sku.
Does anyone have any ideas on this?
Thanks
Comment: Maybe it's just me, but I can't understand what's your setup and what you are actually trying to do. Try to read your own question like if you had no idea what it's about. Is it clear? If no, please edit. If yes, well, then it's just me.
Comment: I have updated my question.
Answer: Another user gave me this to answer my question:
How to use Commerce Feeds to Import Stock for the Commerce Stock module?
The user https://drupal.stackexchange.com/users/8943/watergate suggested this:

If you're using commerce_feeds 7.x-1.3, uninstall it.
Make sure you've updated the standard Drupal feeds to 7.x-2.0-beta1
Download commerce_feeds 7.x-1.x-dev

After I did that, I could use mapping and see all the target fields for my product variation, including those fields enabled when you use commerce_stock.


Is there a pre-styled Omega subtheme out there?

Question: I am after a theme that looks good out of the box and I don't need to make a lot of theming changes. The customer is not fussed about the styling but obviously doesn't want a stark/bare looking site either. The omega theme fits the bill functionality wise, it's responsive and the regions/sections suit us. However, it is way too bare/stark. I've so far tried Omega kickstart, omega and omega-alpha.
Any suggestions on a pre styled free theme I can used that is based on the Omega "framework"?
Answer: Here is the complete listing of themes which uses the omega theme as a base theme.
Apart from that you can get the list of various themes/sites which uses omega theme on omega theme project page
Comment: Thank you @mohit_rocks

I ended up going with the corporate clean theme, but it does not offer as many grids as the omega does. Or maybe I just don't know how to get to them? There are not as many sections/regions as there are in Omega :(


AttributeError: 'Enemy' object has no attribute 'blit'

Question: I am making a spaceship game where you control a spaceship and fire bullets to defeat enemies. However, when I run my game, I get this:

Traceback (most recent call last):
File "C:/eqodqfe/t2.py", line 98, in  enemies.draw(enemy)
File "C:\Users\linpang2018\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pygame\sprite.py", line 474, in drawsurface_blit = surface.blit
AttributeError: 'Enemy' object has no attribute 'blit'

Why does this happen? How do I fix it? This is my current code: (Some parts omitted or replaced by --snip--)
class Spaceship(pygame.sprite.Sprite):
    def __init__(self, s, x, y):
        pygame.sprite.Sprite.__init__(self)

        self.screen = s
        self.x, self.y = x, y
        self.image = pygame.image.load("C:/eqodqfe/spaceship.png")
        self.image = pygame.transform.scale(self.image, (175, 175))
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)

    def update(self):
        self.rect.center = (self.x, self.y)

class Bullet(pygame.sprite.Sprite):
    def __init__(self, s, x, y):
        pygame.sprite.Sprite.__init__(self)

        --snip--

    def update(self):
        self.y -= 5
        self.rect.center = (self.x, self.y)
        if self.y < 0:
            self.kill()

class Enemy(pygame.sprite.Sprite):
    def __init__(self, s, x, y):
        pygame.sprite.Sprite.__init__(self)

        self.screen, self.x, self.y = s, x ,y
        self.image = pygame.image.load("C:/eqodqfe/enemy.png")
        self.image = pygame.transform.scale(self.image, (240, 210))
        self.rect = self.image.get_rect()
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)

    def update(self):
        self.rect.center = (self.x, self.y)

spaceship = Spaceship(screen, 400, 400)

bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()

clock = pygame.time.Clock()

running = True
while running:
    --snip--  # (event loop and spawning bullets)

    bullets.update()

    key = pygame.key.get_pressed()
    amount = 5

    if key[pygame.K_a]:
        spaceship.x -= amount
    --snip--

    spaceship.update()

    screen.fill((255, 255, 255))

    screen.blit(spaceship.image, spaceship.rect)

    enemy = Enemy(screen, randint(-200, 800), -100)
    enemies.add(enemy)

    bullets.draw(screen)
    enemies.draw(enemy)

    pygame.display.update()
    clock.tick(60)

Answer: pygame.sprite.Group() works like this:

Draws the contained Sprites to the Surface argument.

So the line
enemies.draw(enemy)

should be
enemies.draw(screen)

as the argument has to be a Surface, not a Sprite.
Comment: Because you set the y coordinate to -100, which is outside the screen.
Comment: OK, I understand. But when I tried it, Nothing showed up on the screen but the player and bullets. Why is this? Or am I doing something else wrong?
Comment: Oh noew. Let me fix that.


Blanchard and Quah output gap

Question: In the paper of Blanchard and Quah (1989), they estimate the impact of demand shock on delta(real GDP). And from that they could estimate the impact of demand shock on real GDP (which is output gap). But they didn't show clearly how they move from delta(realGDP) to real GDP.
Can you help me with this question? Many thanks!
Comment: For a given $x_t$, if you know $\Delta x_{t+1}$ you easily get $x_{t+1}$ as $x_{t+1}=x_t+\Delta x_{t+1}$. Does that help? In Blanchard and Quah terms, they are modelling $\Delta x_{t+1}$ and move from that to $x_{t+1}$, is that right?
Comment: @RichardHardy thank you! and so sorry for not clarifying better here. Actually they move from estimating impact of demand shock on deltaGDP to estimating impact of demand shock on GDP.
Comment: so I wonder if those two estimations are the same (so that they didn't show details in their paper)? or something else quite easy but I still couldn't get...?
Comment: That requires us to actually read the paper, doesn't it?
Comment: no, i think the paper was already from 1989 and people now have standadized the BQ method to estimate output gap so it is widely used now... i think there are some clear steps in this method... but to read the paper would take time ...
Comment: Maybe try Economics Stack Exchange instead?
Answer: Blanchard and Quah use a structural VAR to estimate the impact of a demand shock on delta(realGDP). Using the estimate of the simultaneity matrix (that results A-B identification) you can transform the residuals of the VAR into supply and demanda shocks.
If you are using eviews, it is very easy to estimate and generate de Impulse response functions. Let me know if you need any help.
Comment: thanks a lot Gustavo! Actually im using R. I already generated the IRF, but still on the way to get the output gap.
Comment: just a short question. Now that from VAR model I have got the transformed matrix of residuals and also the transformed matrix of Phi. Restriction already applied. What shoud i do next to get output gap? i guess this is the last step... Thanks in advance!
Comment: This part is very tricky. With the residuals and the matrix associated with the shocks you can generate the structural shocks.

the output gap is the acumlated impact of the demand shock on gdp growth, which you can generate using the impulse response function values.

Is there a way to send private messeges on stack exchenage? Send me your email and I can send you a excel worksheet that calculates this. It is easier to understand how its done.
Comment: Honestly i don't know how i can chat privately here. But my usual email is email@example.com. Hope you don't mind. Thanks a million times!

Blanchard and Quah output gap


How to distribute cell height evenly within a row spanning two cells vertically?

Question: I have a table with the following html structure:

  A (This is a dynamic column. I don't know its height).
  B
  D
  E

  C
  F

If the height of cell A is 200px, cells B, C, E and F would distribute themselves evenly to a height of 100px when viewed with Firefox 19.0 browser. However, Google Chrome 25.0 would display the same table with cells B and E having a height just sufficient to contain its content and cells C and F occupying the remaining space.
DEMO in JsFiddle
My question is, how do I distribute the height of these cells evenly without specifying the cell height in CSS? Edit: My objective is to have the internal cells distribute evenly when cell A changes in height.
Answer: You should set the height for td in css. Hence you dont need to specify height for #A.
If you want to set the height of cell A to 100px, set td height to 50px
Here is the fiddle
Comment: My objective is to have the internal cells distribute evenly when cell A changes in height. Sorry, if I am not clear enough.
Comment: By setting the td height, you are also setting the height of cell A( which is twice the height of td). This will work for the tables with the structure you provided.
Comment: The height of cell A is suppose to be dynamic, not static. So, I wouldn't know what height to set for td.
Comment: You can set the height for td dynamically just like setting height for cell A, can't you?
Comment: For the benefit of your understanding, I have remove the height specification for cell A. Please take a look at the JsFiddle again to understand what I mean by dynamic.
Answer: I have this same issue. Here's how my data table looks in IE8 & FF23
The second image is how it looks in Chrome & Opera (notice the blue highlighting how the bottom row is expanded to fill the height).

The answer is you can't as far as I have tried. It's how the underlying browser treats the standards. IE & FF will divide the cells on the right evenly where Chrome & Opera just expand the bottow cell to fill the height. The best you can do is vertically align the bottom row to the top so at least all the data is together.


g++ throws "undefined reference to" static class member

Question: I'm writing CCITT Group 4 encoder and it seems I have a problem with linker.
I have some raw binary data stored as static const class members (Fakskod.h):
class Fakskod {
  public:
  // ...
   static const unsigned char codesTerminateWhite[64][3];
   static const unsigned char codesTerminateBlack[64][3];
   static const unsigned char codesMakeUpWhite[40][3];
   static const unsigned char codesMakeUpBlack[40][3];

  private:
  //...
} ;

I had to initialize them elsewhere, because brace-enclosed initializers can't be used in class definition. Not to mention clearness of the header. So in another file (Fakskod-codes.cpp) I assigned data:
const unsigned char codesTerminateBlack[64][3] = { {0x0d, 0xc0, 0xa},
{0x40, 0x0, 0x3},  {0xc0, 0, 0x2}, {0x60, 0, 0x3},  {0x30, 0, 0x4},
{0x20, 0, 0x4}, {0x18, 0, 0x5},  {0x14, 0, 0x6},  {0x10, 0, 0x6},
//... (~200 hex bytes)
} ;

And that's what I got:
/tmp/ccm0ijoi.o: In function `Fakskod::makeCode(int, fkColor)':
rectangle_test.cpp:(.text+0x19b0): undefined reference to `Fakskod::codesTerminateWhite'
rectangle_test.cpp:(.text+0x1a02): undefined reference to `Fakskod::codesMakeUpWhite'
rectangle_test.cpp:(.text+0x1a7b): undefined reference to `Fakskod::codesTerminateWhite'
rectangle_test.cpp:(.text+0x1b0f): undefined reference to `Fakskod::codesTerminateBlack'
rectangle_test.cpp:(.text+0x1b5e): undefined reference to `Fakskod::codesMakeUpBlack'
rectangle_test.cpp:(.text+0x1bce): undefined reference to `Fakskod::codesTerminateBlack'
collect2: error: ld returned 1 exit status

It seems the source of trouble is this method (Fakskod-Horizontal.cpp):
std::vector<unsigned char> Fakskod::makeCode(int num, fkColor color) {

  #define FAKSKOD_MKCD(TERM, MKUP) \
  if(num < 64) \
    return vectorize( TERM [num]); \
  else { \
    for(int i=40; i>0; i--) \
       if(num/64 == i) { \
           code = vectorize( MKUP [i-1]); \
           num -= 64 * i; \
       } \
    return mergeStreams(code, vectorize( TERM [num])); \
  }

   std::vector<unsigned char> code;
   if(color==WHITE)    { FAKSKOD_MKCD(codesTerminateWhite, codesMakeUpWhite) }
   else                { FAKSKOD_MKCD(codesTerminateBlack, codesMakeUpBlack) }

} // Fakskod::makeCode

I'm sure that everything is ok with the macro. Preprocessor (g++ -E) resolves it correctly and when I paste expanded version to my code, the message is the same.
Also I tried to #include the header file and Fakskod-codes.cpp, or add these files to g++ command. Didn't help. Error raises even if I move assignments to header.
Answer: The static class members you have declared are really named Fakskod::codesTerminateWhite and so on.  When you define them in the source file, you're no longer within the class scope, so you need to type the full name:
const unsigned char Fakskod::codesTerminateBlack[64][3] = {
    // ...
};

Without that, C++ thinks they are two different arrays.


If f is a continuous function and $f(1)=k$, prove that $f(x)=kx$ for all $x$.

Question: Let $f$ be a function that satisfied $f(x+ y) = f(x) + f(y).$
So the first part required me to prove that if $f$ is continuous at some point $c$, it is continuous on $\Bbb R$. I was able to do this.
The second part is as follows:
Suppose that $f$ is continuous on $\Bbb R$ and that $f(1) = k$. Prove that $f(x)=kx$ for all $x \in\Bbb R$.
I am having difficulty understand how to approach this problem. Any help whatsoever would be appreciated!
Answer: This is a standard. We prove that $f(ax)=af(x)$ firstly for $a\in\Bbb N$, secondly for integer $a$, and finally for rational $a$. Next it is enough to use continuity to prove this claim for any $a\in \Bbb R$. Now put $x=1$, that's it.
Answer: Hint: Let $n$ an integer, shows recursively that $f(n)=kn$, then show that $f({1\over n})={k\over n}$ if $n\neq 0$ by using that $f(n{1\over n})=nf({1\over n})=k$ then show that $f({p\over q})={kp\over q}, p,q$ integers, then use the fact that rational are dense in $R$ and the continuity.
Comment: But its for x $\in$ R, not for n $\in$ N
Comment: You show it for $x\in Q$, $x=lim x_n, x_n\in Q$, $f(x)=lim_nf(x_n)=lim_nkx_n=kx$.


What does _ngcontent-c# mean in Angular?

Question: I'm learning Angular 2/4 and I see the html tags with the ng generated attributes: _ngcontent-c0, _ngcontent-c1...
What does this c value mean?
Answer: _ngcontent-c# attributes are added when you use ViewEncapsulation.Emulated - which is default. Angular uses these attributes to target specific elements with the styles. The number c is sort of a unique identifier of the host component. For example, if you have two components with the following templates:
ComponentA

<comp-b></comp-b>

ComponenB

Angular will mark all elements with styles inside component A as _ngcontent-c0 and all elements with styles inside component B with _ngcontent-c1:
<comp-a>

    <comp-b _ngcontent-c0>

    </comp-b>
</comp-a>

Comment: @TomStickel, ViewEncapsulation.Emulated is default mode. It's specified in the Component decorator descriptor properties
Comment: Not sure I like or want / need this `_ngcontent..`   how do i turn it off ?
Comment: All good and well, but what effect do the _ngcontent-c# have?
Comment: So the root component will be 0 and nested ones would go 1...n?
Comment: @TomStickel, what [view encapsulation](https://angular.io/api/core/ViewEncapsulation) are you using? If you use Native or None, Angular shouldn't add these attributes
Comment: Well I came from Angular 1 world ,  dabbled with angular 2 -   then got into 4, and now new project from scratch with angular 5.    I have been using Angular CLI,  I have not intentionally added any view encapsulation so this is all new to me.   I don't recall the _ngcontent on last contract project with angular 4, so I'm unsure about this  "Native" vs "None"  -  Is angular CLI adding it when I'm using ng serve ?
Comment: @Scott, can you clarify what you mean? I used `#` instead of a number. It's used to target CSS selectors and apply encapsulated styles
Comment: @AngularInDepth.com right, but I mean what specific styles are applied using it?
Comment: @Scott, they depend on what styles you used in your `style` property of Angular decorator
Comment: You can follow this link.
    https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html
Comment: "when you use ViewEncapsulation.Emulated"?  This is confusing.  I didn't use ViewEncapsulation.Emulated!  Can you re-write that so it's clearer?  "By default, Angular... This is technically ViewEncapsulation.Emulated"
Comment: @MaxKoretskyi, would you be able to help with an issue I'm having?  I'm trying to create a reusable form in Angular to use on other pages.  I'm not getting any errors but the component is not showing up.

https://stackoverflow.com/questions/72788182/cant-see-content-of-reusable-angular-form-on-home-page
Answer: you can disable it by adding below import to your component,
import {ViewEncapsulation} from '@angular/core';

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

please note this line :
 encapsulation: ViewEncapsulation.None

make no addition of dynamic attribute from angular


How to install extensions in contao 4.4

Question: I installed contao 4.4 in my localhost successfully.After successful installation I tried to install an extension via contao manager.Unfortunately it fails with console error.So I download zip file of extenson from codefog
and put it in the folder root/system/modules .But the extension is not found in backend.I think the extension is not installed successfully. How to make it works? Please help me.
Answer: You do not need to install this extension manually. Simply run
composer require codefog/contao-news_categories

in the root folder of your Contao installation. Depending on how you installed composer the command might be different.
Answer: This is how i install extensions in my contao 4 standard-edition. As commented, this only applies to the standard-edition, not the managed-edition. If you don't want to change to the standard-edition, you may better wait, until they fix the problem in the contao manager... Otherwise this is how it works:
Installing a Contao 4 bundle
Info: A bundle is the best thing you can find for extending contao.
It is the cleanest way of adding functionality to the contao cms.

Find the module on https://packagist.org/
Get the "require ..." command from under the title
Connect to your hosting (or if local, open cmd or terminal)
Change to the root of your hosting
Execute the require ... command for this extension
composer require madeyourday/contao-rocksolid-columns
Add the module to AppKernel (File: app/AppKernel.php)
In the "$bundles" array we can now add our bundle to the list of bundles, that contao should load: (the bundle name used in this line can be found in vendor/%developer%/%extension%/src/ and then there is a ...Bundle... php File there, that tells you the name of the bundle)
new MadeYourDay\RockSolidColumns\RockSolidColumnsBundle(),
Open the installtool of contao (contao/install) and update the database

Installing a Contao 4 extension
Info: A contao 4 extension is defined by it's developer, it is actually still the same method of programming like in 3.5 but someone has tested it in contao 4 and approved of its functionality. This is the second best thing you can find for extending contao.

Find the module on https://packagist.org/
Get the "require ..." command from under the title
Connect to your hosting (or if local, open cmd or terminal)
Change to the root of your hosting
Execute the require command for this extension
composer require heimrichhannot/dlh_googlemaps
Add the module to AppKernel (File: app/AppKernel.php)
In the "$bundles" array we can now add our extension to the list of extensions, that contao should load:
new ContaoModuleBundle('dlh_googlemaps', $this->getRootDir()),
Open the installtool of contao (contao/install) and update the database

Installing a Contao 3.5 extension
Info: A contao 3.5 extension is your last hope, it is the same code as in contao 3.5 may or may not work - you have to test it yourself.

Find the module on github (or some other repo)
Conntect to your hosting with ssh (or if local, just open cmd or terminal)
Change into "system/modules"
Download the repo (e.g. git clone https://github.com/ContaoBlackForest/contao-system-notification system-notification) - notice the added "system-notification" at the end, that should be the foldername, in which the extions has to be (you can find the folder in the composer.json file inside the extension under "Resources/contao")
Create syslinks (bin/console contao:symlinks)
Add the module to AppKernel (File: app/AppKernel.php)
This line should be added once, just after "use Symfony\Component\HttpKernel\Kernel;" (this only has to be added once and only if you are using contao 3.5 extensions)
use Contao\CoreBundle\HttpKernel\Bundle\ContaoModuleBundle;
In the "$bundles" array we can now add our extension to the list of extensions, that contao should load:
new ContaoModuleBundle('system-notification', $this->getRootDir()),
Open the installtool of contao (contao/install) and update the database

Your Question
To awnser your question, as the module you want to install, is a contao 4 extension, you could use the according instructions from above.
contao 4 extension - https://packagist.org/packages/codefog/contao-news_categories
Comment: The bundle you are referring to is not the same as codefog/contao-news_categories. Furthermore, your instructions only apply to the contao/standard-edition (just in case anyone wants to try this with the contao/managed-edition).
Comment: File: app/AppKernel.php is not found in my instance.Can I manually create this file?
Comment: No, if you do not have the file `app/AppKernel.php` you are probably using the `contao/managed-edition`. In that case, simply install the extension via composer and open the Contao Install Tool afterwards.
Comment: yeah.So How can I fix the compatibility of an extension in contao 4.4???
Comment: @Aswathy S What exactly do you mean?
Comment: @Rory what do you mean by "until they fix the problem in the contao manager"? What problem are you referring to?
Comment: @fritzmg Well i think the contao manager can't handle the hosting Aswathy is using or the extension he wants to install. But users using the managed edition depend on it working and in this case it doesn't seem to work.
Comment: @Aswathy Can you send a printscreen of the contao manager Error? at the bottom of the page, i belive you can "show more details" and there you probably will see what's wrong
Comment: @Rory yeah it seems I misread the original post - I missed that there were errors. However it's a local development environment, not a remote hosting.
Comment: @fritzmg I downloaded custom_module extension from codefog.The extension is currently working with contao 3.x . How can I fix the compatibility of the extension so that the extension is perfectly working with the contao managed edition
Comment: You already asked that here: https://community.contao.org/en/showthread.php?23710-Migration-of-extensions-from-contao-3-to-contao-4 And as already said there, in general any Contao 3 extension is compatible with Contao 4 - with a few exceptions depending on specific API changes.

How to install extensions in contao 4.4


Typo mistakes in input still meet conditions for text based RPG game with Python 2.7 on UNIX

Question: I've been learning how to code for a month now using the "Learn Python The Hard Way" tutorial.
So far it's been a lot of fun.
I challenged myself in creating a text based RPG game.
I am currently re-writing the code for improved readability and maintenance.
I am facing a problem:
If I type in the choice input "open heaby door" (notice the typo mistake), the conditions are still met and I get the expected print as if it didn't have the typo mistake.
Any ideas on what I've done wrong?
Thanks for the help :)
PS: I have another question but I figured I'd have to ask on a separate question file.
prison_key = False
def test():
    global prison_key
    curr_prompt = "What do you do?"
    print curr_prompt
    choice = raw_input("> ").lower()
    while "quit" not in choice:
        if "go" in choice:
            if "cellar" in choice:
                print "cellar"
            elif "gravel" in choice or "path" in choice:
                print "gravel path"
            elif "prison" in choice and prison_key:
                print "You enter the prison."
            elif "prison" in choice:
                print "The door is locked."
            else:
                print "Invalid"
        elif "search" in choice:
            if "search" == choice:
                print "invalid"
            elif "prison":
                print "The door is closed."
            elif "bucket" in choice:
               print "The bucket is empty."
            elif "keg" in choice:
                prison_key = True
                print "You find a key."
            elif "door" in choice and ("heavy" in choice or "steel" in choice or "metal" in choice):
                print "It looks like a prison door"
            elif "search door" == choice:
                print "Which one?"
            else:
                print "You find nothing."
        elif "open door" == choice:
                print "which one?"
        elif "open" in choice:
            if "door" in choice and ("wooden" in choice or "cellar" in choice):
                print "gravel path"
            elif "door" in choice and ("steel" in choice or "metal" in choice or "door" in choice or "heavy" in choice or "prison" in choice) and prison_key:
                print "You open the prison"
            elif "door" in choice and ("steel" in choice or "metal" in choice or "door" in choice or "heavy" in choice or "prison" in choice):
                print "the door is locked"
            elif "prison" in choice and prison_key:
                print "You enter the prison."
            elif "prison" in choice:
                print "the door is locked."
            else:
                print "invalid"
        elif "drink" in choice and "wine" in choice:
            print "You alcoholic."
        else:
            print "invalid"
        print curr_prompt
        choice = raw_input("> ").lower()
    exit(0)

test()

Answer: so found your problem. In the elif condition for
elif "door" in choice and ("steel" in choice or "metal" in choice or "door" in choice or "heavy" in choice or "prison" in choice):

You are checking for door again, and thus it passes the if condition.
Same applies for this condition also
elif "door" in choice and ("steel" in choice or "metal" in choice or "door" in choice or "heavy" in choice or "prison" in choice) and prison_key:

    print "the door is locked"

Answer: I think the mistake is that you put "door" in choice in the second aprt of your and clause:
elif "door" in choice and ("steel" in choice or "metal" in choice or "door" in choice or "heavy" in choice or "prison" in choice) and prison_key:
            print "You open the prison"

The same applies for the next elif.
Nice project btw.
Comment: Oh my gosh !! DUH ! Sorry for this post I should've taken a quick break and re-read my code carefully before posting ! Thanks a lot Anurag and Thomas for the input anyways !


Razor MVC - Ao utilizar @using (Html.BeginForm()) os campos não ficam um na frente do outro

Question: Estou começando a estudar MVC + Razor e em exemplo de CRUD básico, estou tentando colocar os campos em duas colunas, como se estivesse usando  em HTML.
Porém meu código só funciona se eu retiro o @using (Html.BeginForm()).
Utilizando o @using (Html.BeginForm()), fica assim minha tela.

Sem utilizar o @using (Html.BeginForm()), fica assim minha tela.

Não estou conseguindo entender porque isto está afetando a parte visual do código.
@model Vecchi_Igreja.Models.ViewModel.CadUsuarioViewModel

@{
   ViewBag.Title = "Cadastro de Usuário";
}

@*@using (Html.BeginForm())
{*@
@Html.AntiForgeryToken()

Cadastro de Usuário

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
                @Html.TextBoxFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Senha, htmlAttributes: new { @class = "control-label col-md-2" })
                @Html.PasswordFor(model => model.Senha, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Senha, "", new { @class = "text-danger" })

    <form role="form" class="form-inline">

            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-1" })

                @Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Ativo, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.CheckBoxFor(model => model.Ativo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Ativo, "", new { @class = "text-danger" })

    </form>

            <input type="submit" value="Create" class="btn btn-default" />

@*}*@

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")
}

Answer: Tente remover a tag abaixo. Você está aninhando form dentro de form, o que provoca efeitos colaterais:
<form role="form" class="form-inline">

Além disso, quando utilizamos o snippet BeginForm o Razor vai escrever a tag form no seu HTML, consequentemente não é necessário colocar o form novamente, veja documentação. Lembrando que form dentro de for é proibido dentro dos padrões HTML e XHTML.
Seção B. "Element Prohibitions", diz que:
 "form must not contain other form elements."

http://www.w3.org/TR/xhtml1/#prohibitions
Reforçando, o problema não está no Razor e sim na estrutura do HTML e nas classes CSS do Bootstrap. Veja no guia do bootstrap 4 ou Bootstrap 3 como deve ser a estrutura de um formulário


How would you compare two big ( cca 2 mil rows x 60 cols) dataframes / data tables?

Question: I have seen a few methods that, how can i compare ( compare_df, dplyr, etc.) and they are effective enough. However when i would like to compare big or huge dataframes i get memory exhausted error, so i would like to ask some method how can i do it better.
I have datas in DB2 databases/data tables, i could accept server side solutions too if there is any.
The task is basicly that i should find all the differences between the two data table. I could use primary key as a join.
Also i taught that it could be a solution if i'd concatenate rows into one string and i compare that on primary key join (and in this case i could have only 2 columns) but i should get where is the difference between the two rows, so it would be an extrastep.
Any out-of-box ideas are welcomed.
Comment: How do you like to get the difference for some row exactly? In 60 columns of the result set or in one column? Somehow else?
Comment: I'd prefer to get back a dataframe where the differences marked somehow. However could go with just  indexes as well( for example: if it give back that there is a difference between the two dataframe at "id: 6253 at col 14")
Answer: You may try the following as is using handy DISTINCT predicate (starting from Db2 11.1). Equivalent expressions may be used for earlier versions, but they are a little bit longer.
WITH
  A (ID, C1, C2) AS
(
VALUES
  (1, '=', '=')
, (2, '=', '=')
, (4, 'A', '=')
, (5, '=', NULL)
, (6, 'A', 'A')
)
, B (ID, C1, C2) AS
(
VALUES
  (1, '=', '=')
, (3, '=', '=')
, (4, 'B', '=')
, (5, '=', NULL)
, (6, 'B', 'B')
)
SELECT
  COALESCE(A.ID, B.ID) AS ID
,  CASE
    WHEN A.ID IS NULL THEN '-A'
    WHEN B.ID IS NULL THEN '-B'
    ELSE ''
   END
|| CASE WHEN A.ID = B.ID AND A.C1 IS DISTINCT FROM B.C1 THEN ', C1' ELSE '' END
|| CASE WHEN A.ID = B.ID AND A.C2 IS DISTINCT FROM B.C2 THEN ', C2' ELSE '' END
--...
--|| CASE WHEN A.ID = B.ID AND A.C60 IS DISTINCT FROM B.C60 THEN ', C60' ELSE '' END
  AS FLAG
FROM A
FULL JOIN B ON B.ID = A.ID
WHERE
   A.ID IS DISTINCT FROM A.ID
OR A.C1 IS DISTINCT FROM B.C1
OR A.C2 IS DISTINCT FROM B.C2
--...
--OR A.C60 IS DISTINCT FROM B.C60;

The result is:
|ID         |FLAG      |
|-----------|----------|
|4          |, C1      |
|6          |, C1, C2  |
|3          |-A        |
|2          |-B        |

We use FULL OUTER JOIN between 2 tables with the following OR conditions:

The KEY (ID) is NULL for one of these tables only (there is no match in the counterpart table by this KEY)
There is a difference in one of the corresponding column values

The FLAG column contains the type of difference:

-TABNAME - the absence of the KEY in the table TABNAME
, Cx - there is a difference in the column Cx - for each such a column

If you have a large number of columns in both tables, you may generate the corresponding expressions for this SELECT statement using a number of Db2 system views.
For example, if we want to generate such expressions for the SYSIBM.SYSTABLES table,
using one of its unique indexes (you must choose such an index, preferably the one supporting primary key), then run this as is to check:
SELECT
  '|| CASE WHEN ' || I.KEY_EXPR || ' AND A.' || C.COLNAME || ' IS DISTINCT FROM B.' || C.COLNAME || ' THEN '', ' || COLNAME || ''' ELSE '''' END' AS SELECT_LIST_EXPR
, 'OR A.' || C.COLNAME || ' IS DISTINCT FROM B.' || C.COLNAME AS WHERE_EXPR
FROM
  SYSCAT.COLUMNS C
, TABLE
(
SELECT LISTAGG('A.' || U.COLNAME || ' = B.' || U.COLNAME, ' AND ') AS KEY_EXPR
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE U ON U.INDSCHEMA = I.INDSCHEMA AND U.INDNAME = I.INDNAME
WHERE
    I.TABSCHEMA=C.TABSCHEMA AND I.TABNAME=C.TABNAME
AND I.INDSCHEMA='SYSIBM' AND I.INDNAME='INDTABLES01'
AND I.UNIQUERULE IN ('P', 'U')
) I
WHERE C.TABSCHEMA='SYSIBM' AND C.TABNAME='SYSTABLES'
--FETCH FIRST 10 ROWS ONLY
;

Answer: One way (of many) is
(SELECT 'A', * FROM A EXCEPT ALL SELECT 'A', * FROM B)
UNION ALL
(SELECT 'B', * FROM B EXCEPT ALL SELECT 'B', * FROM A)

Rows returned that have 'A' in the first column are in TABLEA but not in TABLEB.
Rows returned that have 'B' in the first column are in TABLEB but not in TABLEA.


Integrate monomials over unit circle

Question: I'd like to integrate monomials $x^{2m} y^{2n}$ over the unit circle analytically, and while I got a correct expression, it's not symmetric w.r.t. $m$ and $n$, which is weird. (Btw, if one of the exponents is odd, the value of the integral is 0, hence the $2$s.)
Here is what I did: I'd like to calculate the value of
$$
I = \int_0^{2\pi} \cos^{2m}\theta \sin^{2n}\theta\:\text{d}\theta.
$$
We get
$$
\begin{split}
I
&= \int_0^{2\pi} \left(1-\sin^2\theta\right)^m \sin^{2n}\theta\:\text{d}\theta\\
&= \sum_{k=0}^{m} (-1)^k \binom{m}{k} \int_0^{2\pi} \sin^{2(k+n)}\theta \:\text{d}\theta.
\end{split}
$$
For any $\mu\in\mathbb{N}$, we have
$$
\int_0^{2\pi} \sin^{2\mu}\theta \:\text{d}\theta
= 2\pi \frac{(\mu-1)!!}{\mu!!}
= 2\pi \frac{(2\mu)!}{\left(2^{\mu} \mu!\right)^2},
$$
so eventually
$$
I = 2\pi \sum_{k=0}^{m} (-1)^k \binom{m}{k} \frac{\left(2(k+n)\right)!}{\left(2^{k+n} (k+n)!\right)^2}.
$$
Swapping $m$ and $n$ doesn't change the value – as it should – but it's impossible to see this from the formula. This makes me think that there is a better way to express $I$.
Any hints?
Comment: Do you know the beta function? Another option would be to use Stokes' theorem.
Answer: One suggestion would be to use Euler's formulae. Modulo erreurs it should go like this:
$$ \cos^{2m}  \theta \; \sin^{2n} \theta =
 \frac{1}{4^{m+n}} \left( e^{i\theta} + e^{-i\theta} \right)^{2m}
\left( e^{i\theta} -e^{-i\theta} \right)^{2n} (-1)^n =
$$
$$\frac{1}{4^{m+n}}\sum_k\sum_\ell
\left( \begin{matrix} 2m \\ k \end{matrix} \right)
\left( \begin{matrix} 2n \\ \ell \end{matrix} \right)
e^{2i\theta \; (k+\ell-m-n)} (-1)^{n-\ell}
$$
Integrating only gives contributions when $k+l=m+n$ (and the last sign is in fact symmetric in $n-\ell=m-k$)
Answer: \begin{align}
\int\limits_{0}^{2\pi} \cos^{2m}(x) \sin^{2n}(x) dx
&= 4 \int\limits_{0}^{\frac{\pi}{2}} \cos^{2m}(x) \sin^{2n}(x) dx \\
&= 2 \mathrm{B}\left(\frac{2n+1}{2},\frac{2m+1}{2}\right) \\
&= 2 \frac{\Gamma\left(\frac{2n+1}{2}\right) \Gamma\left(\frac{2m+1}{2}\right)}{\Gamma(m+n+1)}
\end{align}

Integrate monomials over unit circle


Oracle select from table and join where date is oldest

Question: My real life problem is more comlpex, but the issue can be washed down to the following: I have one table with clients, and another table with clients' bank accounts. Now I want to do a select returning all clients that have bank accounts, joining with the bank account that was used least recently, ordered by the BANK_ID.
CLIENT:
CLIENT_ID    NAME
-----------------
1            JOE
2            BEN
3            SUE

BANK_ACCOUNT:
BANK_ID    CLIENT_ID    LAST_USED
-----------------------------------
1          2            Jan 1  2020
2          1            Mar 15 2020
3          2            Aug 5  2020
4          1            Feb 7  2020
5          1            Oct 13 2020

So Joe has three bank accounts, Ben has two, and Sue does not have any.
The select should contain only Joe and Ben. Ben should go first because his "oldest" bank account is on BANK_ID 1 while Joe's is on BANK_ID 4.
BANK_ID   CLIENT_ID    NAME
---------------------------
1         2            BEN
4         1            JOE

I've been playing around with joins and subqueries, but I'm not sure what would be the best way to accomplish this query.
Thank you
Comment: Tag your question with the database you are using.
Comment: You're right. I'm afraid we're still on 11g, pending update for 19c.
Answer: A typical method is to use row_number():
select ba.bank_id, ba.client_id, c.name
from client c join
     (select ba.*,
             row_number() over (partition by client_id order by last_used) as seqnum
      from bank_account ba
     ) ba
     on ba.client_id = c.client_id and ba.seqnum = 1
order by ba.bank_id;

In Oracle, you can also use aggregation:
select max(ba.bank_id) keep (dense_rank over order by ba.last_used) as bank_id,
       ba.client_id, c.name
from bank_account ba
     on ba.client_id = c.client_id
group by ba.client_id, c.name
order by ba.bank_id;

Comment: Thank you. The row_number() variant does the trick. Didn't try the aggregation yet.
Answer: One option uses a lateral join:
select ba.bank_id, ba.client_id, c.name
from client c
cross apply (
    select ba.*
    from bank_account ba
    where ba.client_id = c.client_id
    order by ba.last_used
    fetch first row only
) ba

The upside is that you can easily bring more columns from the bank account tables (say you want the last_used date for example), by just expanding the select clause.
Comment: Interesting! CROSS APPLY seem to be >=Oracle 12. Our production environment is still on 11g, pending update for 19c. Meanwhile maybe there's a JOIN expression that will obtain the equivalent result, I can investigate a bit on that one. Sorry for not tagging with Oracle version.


Do redirect after redirecting options removed in .htaccess file

Question: I do some redirecting things on my apache server using rewrite rules and it worked well and after I removed this options, my browser get redirect link yet but when I test it in other system it does't.
This is so strange to me and I don't find out what is the problem.
Is there some logic explain for this or I dreaming?
I am using win 10 in client and apache-2.2 on server, if them help.
Tanks.
Comment: If this is intended to be a _temporary_ redirect, then make it a 302, as opposed to a 301 (ie. permanent). 301s are naturally cached locally, 302s should not be cached.
Answer: Your browser has cached the redirect, so it doesn't even make the request to the page. You need to clear the browser cache or wait for the cache to expire.
You established a HTTP 301 redirect, indicating that the page moved permanently. Use a HTTP 302 redirect for temporary redirects.


How to combine a strings and store it in a array after using strtok() from a "full string" in C

Question: Im a new learner of C and i got trouble combining the strings which separated by strtok().
Using Clion (C99)
Lets have a look at my codes.
char recipient[30];
char final_destination[50];
char status[10];

printf("Please enter 1> Recipient-, 2> Final Destination- and
3>Delivery status :\n");    Entered(L-Rat Kitchen-House Not-Arrived)

scanf("%29s%49s%9s", recipient, final_destination, status);

///only recipient first///The purpose of storing "recipient final_destination, status" in a string is because to let user input data in a same line while using scanf .After that, i use strtok to separate those words before/after "-" .Separate different string by using the spacebar in scanf  which prevents data input like (L-ratKitchenHouseNot-arrive).
const char s[] = "-";
char *token;
token = strtok(recipient, s);
while( token != NULL )
 ???????????????????????

token = strtok(NULL, s);

At the line of ?????????????? , im stuck , i dont know how or is there a way to put those processed data in a array and combine it.
Expecting:
Input: (L-Rat House-Kitchen Not-Arrive)
Output: (L Rat House Kitchen Not Arrive)
Would be very helpful if theres a solution !!!
Comment: Do you just want to replace dash with space in the last string? No need to use strtok for that!
Comment: @hyde how? how to replace it ?
Comment: Just use for loop over the string, and replace any characters you want. Though better solution would be to change the scanf format string so that the last item would be everything until the end of the line, so user could actually enter spaces in the last field.
Answer: try this, if you want store tokens in an array.
while (token != NULL)
    {
        printf("%s\n", token);
        token = strtok(NULL, "-");
    }

Comment: "*tokens in an array*" which "array" please?
Comment: @alk Nothing I just meant instead of just printing it.


How to compare two columns in separate spreadsheets and if the columns match, output related data in from one spreadsheet to the other

Question: Had a search and sadly couldn't find a related question
Im trying to compare two columns in separate spreadsheets and if the columns match, output related data in from one spreadsheet to the other. In the Screenshot below, I am trying to compare the two "required functionality description" fields which are in separate spreadsheets. Then If the two fields match, output the Importance field from one to the other.

I really appreciate any help/guidance on this! Thanks!
Comment: If they match exactly, this is a simple application of `VLOOKUP` or `INDEX-MATCH`.  Do they match exactly?
Comment: @Byron Yeah they should match exactly. Or at least I only want data from  the ones that do.
Answer: Try:
<code>=IFERROR(VLOOKUP(G6,[SO31165136a.xlsx]Sheet1!$G:$H,2,0),"")
</code>
adjusted for your sheet and workbook names.


How to add a safe area programmatically

Question: When you open the view, it will look like the image below,
i Phone x open view
i Phone 8 open view
For iphone x, I would like to add a safe area programmatically in the current view.
The source to try is as follows.
UIView *view = self.view;

if (@available(iOS 11.0, *)) {
    UILayoutGuide * guide = view.safeAreaLayoutGuide;
    [view.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
    [view.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;
}

I suppose to apply this source, but I do not know what to do.
please answer about my question.!
Comment: This source seems to be applicable too.

            UIWindow *window = UIApplication.sharedApplication.keyWindow;
            CGFloat topPadding = window.safeAreaInsets.top;
            CGFloat bottomPadding = window.safeAreaInsets.bottom;
Answer: Here is sample code for Safe Area Layout. Try this in Objective-C and see:
UIView * myView = // initialize view using IBOutlet or programtically

myView.backgroundColor = [UIColor red];
myView.translatesAutoresizingMaskIntoConstraints = NO;

UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
[self.myView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
[self.myView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
[self.myView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
[self.myView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;

// Refresh myView and/or main view
[self.view layoutIfNeeded];
//[self.myView layoutIfNeeded];

Ref from: Use Safe Area Layout programmatically
Result:
Comment: myView.translatesAutoresizingMaskIntoConstraints = NO;
If you use this source, the screen will be completely garbled.
Comment: @Nam - I've tried this code practically and here is its result (a red view). It working fine for me.
Comment: @Krunal Instead of reposting your answer over and over, you should vote to close the question as a duplicate.

How to add a safe area programmatically


Conversion between trig functions and hyperbolic trig functions

Question: Using trig identities we can see that  $\sin^2 x + \cos^2 x =  \tanh^2 x + \text{sech}^2 x = 1$ , and so the parametric graph $(\cos t, \sin t)$ is similar to $(\text{sech} t, \tanh t)$. The first graph produces a semicircle when $-\frac \pi2 \le t \le \frac \pi2$ and the second graph when $-\infty \lt t \lt \infty$. My question is if it is possible to convert between the graphs;  e.g. if there is a function $f$ where $(\text{sech} t, \tanh t) = (\cos f(t), \sin f(t))$.
Comment: See the [Gudermannian function](https://en.wikipedia.org/wiki/Gudermannian_function).
Answer: You want the Gudermannian function: it is defined by
$$ \operatorname{gd}{x} = \int_0^x \operatorname{sech}{y} \, dy $$
In particular, this can be expressed, by changing variables, as
$$ \operatorname{gd}{x} = (\operatorname{sgn}{x}) \arccos{(\operatorname{sech}{x})} = \arcsin{(\tanh{x})}, $$
so
$$ \cos{(\operatorname{gd}{x})} = \operatorname{sech}{x},\\
\sin{(\operatorname{gd}{x})} = \tanh{x}, $$
and then everything follows as you wish, since $\operatorname{gd}:(-\infty,\infty) \to (-1,1)$ bijectively.
Comment: Thanks. So, could gd be thought of some sort of a conversion between a radian value and a hyperbolic angle?
Comment: Yes, essentially. The most remarkable thing is probably the amount of ways you can write gd as inverse trig of hyperbolics: there's just something about that particular integral. No doubt someone's written an article about it. It lets you relate them without complex numbers, too.


Issue with raspberry pi and kodi autostart

Question: I installed kodi on my raspberry pi on raspbian. I read the easiest way to auto start kodi when I turn it on it to change the /etc/default/kodi file and set ENABLE = 1.
Whenever I try this both the app I use as remote (flex remote - ios) and the mouse connected to the raspberry won't work. How can I fix it?
Answer: can't remember exactly, but inside /etc/default/kodi you can also specify a user. Default it should be set as kodi but if you haven't edited that user this might be a source of problems. Try changing that user to pi or give the right permissions to the kodi user


If $f(x+iy) = u(x,y) + iv(x,y)$ is entire, and $u^2(x,y) = v^2 (x,y)$ then $f$ is constant

Question: I see that if I considered:
$f^2 (x+iy) = u^2 - v^2 + 2iuv = 2iuv$, then $f^2$ is constant and so the square root of a constant will be constant, hence $f$ is constant.
However, I want to prove it with the following, and I somehow showed that it's the zero function?
Since $f$ is entire, then $u_x = v_y$ and $u_y = -v_x$.
Also, using $u^2 = v^2$, differentiating w.r.t to $x$ and $y$ gives
$u\cdot u_x = v \cdot v_x$
and $u\cdot u_y = v \cdot v_y$.
Multiplying the two equations together, we have
$u^2 \cdot u_x \cdot u_y = v^2 \cdot v_x \cdot v_y$.
Using the CRE, we have that $u^2\frac{u_x}{v_y}= v^2 \frac{v_x}{u_y} \implies u^2 = -v^2$.
But $u^2 = v^2$. Hence, $u \equiv 0 \equiv v$ and so $f$ is the constant zero function?
Comment: Does $u^2(x,y)$ mean $(u(x,y))^2$?
Comment: Consider the real part of $f^2$. Then $\exp(if^2)$ is constant, etc.
Comment: Yes it does, sorry
Comment: @PedroTamaroff I thought that if $f^2 = 0 + 2iuv$, I could immediately conclude that $f$ is constant since $f^2$ will be constant (using CRE)? Why do I have to take the exponential?
Answer: This is the classic case of proving something incorrect by secretly dividing both sides of the equation by $0$. Here $u_y$ and $v_y$ are both $0$ so dividing by them isn't allowed.
With a little care you can modify this to a valid proof by contradiction.
Comment: Ah I see. What if I were to "flip" the sides and then multiply them together similarly? e.g.:  $uv u_x v_y = uv u_y v_x$ so $u_x ^2 = -u_y ^2$ which means $u_x ^2 + u_y ^2$. But sum of two real squares equal to zero means each component equals to zero, so $u_x = 0 = u_y$.
Is this only valid for $uv \neq 0$?
Comment: @Twenty-sixcolours That seems reasonable although you are using $uv \ne 0$. There is a silly case distinction to make here.
Comment: Thank you. A slightly related question - do you know more examples of this type of question where they give some relationship between $\Im (f)$ and $\Re(f)$ which implies that $f$ would be constant?
Comment: @Twenty-sixcolours I don't know a list offhand but several questions like that are showing up in the "related" section to the right


QTip with Fullcalendar on eventMouseover

Question: this is the right way for a qtip? Don't work for me.
<code>eventMouseover: (event, jsEvent, view ) ->
  $(this).qtip
    content:
      text: event.description
    ready: true
    style:
      classes: "custom-class" # Custom class method or...
</code>
We can see the js.coffee -> http://pastebin.com/mNxJmZJe
I use the qTip2 v2.2.0 and jQuery v1.10.2
Answer: Based on FullCalendar documentation qtip is being used the following way:
<code>    $('#calendar').fullCalendar({
    events: [
        {
            title: 'My Event',
            start: '2010-01-01',
            employee: 'name'
        }
        // more events here
    ],
    eventRender: function(event, element) {
        element.qtip({
            content: event.employee
        });
    }
});
</code>
Here's a link to the documentation regarding qtip: http://arshaw.com/fullcalendar/docs/event_rendering/eventRender/
I hope this helps.
Comment: I have this error ( Uncaught TypeError: Property 'employee' of object # is not a function ). See here the code -> http://pastebin.com/Xfa2tnsd
Comment: You should include employee in the event:
Comment: I edited my answer above to reflect your event.employee


MICROSOFT EXCEL 2010: Reference One Cell Value To Get Row #

Question: Is there any possible way to get a certain row value by using the value of different cell?
For example: My current cell information is
<code>=Estimates!R6C12
</code>
It is referencing a different sheet with the value of Row 6 and Column 12.
Now for each month I copy the previous months data, however I would like to be able to change just that single cell based on cell [Like Row# = ? ]
Is there any way to do this? Something like this?
<code>=Estimates!R(R[-21]C])C10
</code>
Comment: Still don't understand. I mean, when you drag the formula down, excel increments row automatically.
Comment: Formula shouldn't change if you insert data?
Comment: It does because i have an estimate of the money I will be making on Sheet 2 (estimates) that is referenced on sheet 1 (summary).

So for instance in sheet 2 (estimates), January Is row 1. It includes the various variables for that specific month.

Now in sheet 1 (summary) I have each month Showing how much money I am gonna be making and how much budget I have based on the variables in Sheet 2. Since each month I am using a different row on sheet 2, the value formula would change.
Answer: INDIRECT is a volatile function and should never be used. INDEX works just as well and is not volatile.
<code>=INDEX(Estimates!$A$1:$Z$25,6,12)
</code>
Answer: Your question isn't totally clear, but it sounds like you might want to use the INDIRECT() formula.
<code>=INDIRECT("Estimates!R"&ROW([reference])&"C10",false)
</code>
Then the row would be the row of a reference cell, and the column would be 10.
Comment: This was exactly what I was looking for! Thank you very much! Never knew about that function. I have been going back and fixing the value of 20 different cells to fix the reference. This is gonna save me a little time each paycheck! Thank you Neil!
Comment: You can use the code formatting options to format your answers to make it easier to stand out.


Howe to edit the first/or second line of a file by powershell?

Question: Now I use get-content to get the file's content, I need to edit some of the lines. For example, change the 2nd line:
before:
line2: hello Everyone!

after:
line2: Hello Mr. Brown!

Which cmdlet can I use?
Answer: $file = Get-Content myfile.txt
$file | ForEach-Object {
    if ($_.ReadCount -eq 2) {
      $_ -replace '\w+','Hello Mr. Brown!'
    } else {
      $_
    }
  } |
  Set-Content myfile.txt

This will alter the second line (specified through ReadCount -eq) to Hello Mr. Brown!. Be sure to use PowerShell 2.0+.
Answer: If the content is sufficiently unique a replace applied to all lines (but will only match the one you are interested in).
Otherwise load the whole file into a collection, and update the second element (index one).
If the file is large enough that loading the whole file into memory at once is an issue, then something more clever will be needed ….


If $A = LU$ and $B = UL$, the $A$ and $B$ have the same eigenvalues

Question:
If $A = LU$ and $B = UL$, where $L$ is a unit lower triangular and $U$ is an upper triangular matrices, then $A$ and $B$ have the same eigenvalues.

The eigenvalues of $A$ are obtained by solving the equation: $\det(A - \lambda I) = 0$. We have
$$\det(A - \lambda I) = \det(LU - \lambda I)= \det(L(U - \lambda L^{-1})) = \det(L)\det(U - \lambda L^{-1}).$$
Now, from the previous equation, we have
$$\det(L)\det(U - \lambda L^{-1}) = \det(U - \lambda L^{-1})\det(L) = \det(UL - \lambda I) = \det(B - \lambda I), $$
thus, we have
$$\det(A - \lambda I) = \det(B - \lambda I).$$
Does this means that they have the same eigenvalues?
Answer: Your argument is fine, but it requires $L$ to be invertible.
In general, the eigenvalues of $AB$ are the same as the eigenvalues of $BA$ for any two square matrices $A,B$.
Comment: I think in this case $L$ is invertible, because the diagonal of $L$ are ones and is lower triangular.
Comment: Ok, I had never seen "unit"  used in that way. So, your argument is fine. But the result is still true without using "unit"  nor "triangular" .
Comment: No problem. Thank you very much, I appreciate it.


Custom context menu not working on HTML Video tag

Question: I was wondering on how to create my own context menu on top of HTML video tag (something like the youtube menu).

I am using a library called rClick.js
Code snippet
<video id="video1" class="videoMenu" width="33.33%"  style="padding: 2px 2px 2px 2px;">
              <source src="./assets/samples/trailer.mp4" type='video/mp4'>
            </video>


Como popular SELECT de um modal criado com JQUERY

Question: Tenho um Modal que crio dinamicamente quando o usuário clica em um link, conforme o link ele abre um modal diferente.
Gostaria de popular um Select que esta dentro desse modal. Já tentei so com um include, mas não esta funcionando.
Quando clico, aciono essa função. Que depois executa as outras duas seguintes.
$(document).on('click', '.abre-modal-aula', function(){

const typeOperation = $(this).attr("type-operation");
const codAula   = $(this).attr("cod-aula");

$.getJSON('config/database/consultaAjax/includes/modalAulas.php', { codAula, typeOperation }, resultado => {
    if(resultado == '999-login'){
        newAuth();
        return false;
    }
    if(resultado != null){
        const modals = modalActionAula(resultado, typeOperation);
        $('#showModal').html(modals);
        $('#aula').modal();
        setTimeout(() => {
            $('input[type="checkbox"], input[type="radio"]').iCheck({
                checkboxClass: 'icheckbox_square-blue',
                radioClass: 'iradio_square-blue'
            });
            // INICIA O CSS E JS DO SELECT2
            $('select.select2').each(function () {
                $(this).select2({
                    dropdownParent: $(this).parent().parent()
                });
            });
            // INICIA CSS E JS DA MASCARA DE FORMATAÇÃO
            $('[data-mask]').inputmask();
        }, 100);
    }
});
return false;

});
const modalActionAula = (resultado, typeOperation) => {

switch (typeOperation) {
    case 'verAula':
        return verAula(resultado);
    case 'cancPgto':
        return cancPgto(resultado);
    case 'pagamento':
        return pagamento(resultado, optionFormaPgto);
    case 'pgtoLote':
        return pgtoLote(optionFormaPgto);
    default:
        return false;
}

}
const verAula = (resultado) => {

return `

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×</button>

Visualização Dados da Aula

                                            Professor
                                            <input type="text" class="form-control" value="${resultado.CPROFESSOR}" disabled>

                                            Tipo Aula
                                            <input type="text" class="form-control" value="${resultado.CTIPOAULA}" disabled>

                                            Selecione o Talento para adicionar na Aula

                                            <select class="select2 form-control" id="selectTalentoAula" required>
                                                <?php include "pages/includes/lista/listClientes.php" ?>
                                            </select>

                                            <button type="button" class="btn btn-primary pull-right addTalentoAula" >Adicionar Talento</button>

                                                    #
                                                    First
                                                    Last
                                                    Handle

                                                    1
                                                    Mark
                                                    Otto
                                                    @mdo

                                                    2
                                                    Jacob
                                                    Thornton
                                                    @fat

                                                    3
                                                    Larry the Bird
                                                    @twitter

                <button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Fechar</button>

`;

}
Esse select não esta puxando nada:

    <select class="select2 form-control" id="selectTalentoAula" required>
        <?php include "pages/includes/lista/listClientes.php" ?>
    </select>

Em outra tela que não é modal ele puxa a lista de clientes normalmente.
Answer: Nesta parte do código a baixo, pode alterar:
$('select.select2').each(function () {
                $(this).select2({
                    dropdownParent: $(this).parent().parent()
                });
            });

Altera para :
   $.each(data, function (index, row) {
                $(".selecao-select").append("<option value='" + row.idMateriaPrima + "'>" + row.nomeMateriaPrima + "</option>");
            });

Obs: data está recendo os dados


Distance measurement between latitude/longiture pairs.

Question: I need to calculate the distance between two lat/lng coordinate pairs. In addition, If given an initial lat/lng coordinate, angle of travel, and distance, I need to calculate the resulting lat/lng coordinate.

$f(lat1, lng1, lat2, lng2) = what (angle, distance)$
$f(lat1, lng1, angle, distance) = what (lat1, lng1)$

I come from a programming background so please bear with my lack of exposure to math notation.
Answer: Here is a jsfiddle which appears to work: as you can see, I tested it by feeding the output of one function into the other. The azimuth ("angle" in your notation) is calculated as described in Wikipedia. The second function assumes that the trajectory of motion is an arc of a great circle (aka geodesic, aka shortest path on the sphere). In particular, this means that starting in London and going initially to the east (azimuth 90 degrees), you will actually be going southeast soon. If one maintained constant azimuth during the travel, the resulting trajectory would not be a geodesic but a loxodromic curve.
In case something happens to jsfiddle, here is the code. (By the way, I am sure that this particular problem has been solved many times, in various languages and in better ways than I did here.)
function f(lat1, lng1, lat2, lng2) {
    // convert angles to radians
    var Lat1 = lat1 * Math.PI / 180;
    var Lng1 = lng1 * Math.PI / 180;
    var Lat2 = lat2 * Math.PI / 180;
    var Lng2 = lng2 * Math.PI / 180;
    // find cartesian coordinates
    var x1 = Math.cos(Lat1) * Math.cos(Lng1);
    var y1 = Math.cos(Lat1) * Math.sin(Lng1);
    var z1 = Math.sin(Lat1);
    var x2 = Math.cos(Lat2) * Math.cos(Lng2);
    var y2 = Math.cos(Lat2) * Math.sin(Lng2);
    var z2 = Math.sin(Lat2);
    // vector from initial to terminal point
    var xv = x2 - x1;
    var yv = y2 - y1;
    var zv = z2 - z1;
    // distance
    var distanceChordal = Math.sqrt(xv * xv + yv * yv + zv * zv);
    var distance = 2 * Math.asin(distanceChordal / 2);
    // magic formula for azimuth from  http://en.wikipedia.org/wiki/Azimuth
    var Azimuth = Math.atan(Math.sin(Lng2 - Lng1) / (Math.cos(Lat1) * Math.tan(Lat2) - Math.sin(Lat1) * Math.cos(Lng2 - Lng1)));
    if (lat2 < lat1) {
        Azimuth = Azimuth + Math.PI;
    }
    // output
    var azimuth = Azimuth * 180 / Math.PI;
    document.write("
From latitude ", lat1, " and longitude ", lng1, ", to latitude ", lat2, " and longitude ", lng2, ":
");
    document.write("
Distance is ", distance, " (times the radius). Azimuth is ", azimuth, " degrees.

");
}

function g(lat1, lng1, azimuth, distance) {
    // convert angles to radians
    var Lat1 = lat1 * Math.PI / 180;
    var Lng1 = lng1 * Math.PI / 180;
    var Azimuth = azimuth * Math.PI / 180;
    // find cartesian coordinates
    var x1 = Math.cos(Lat1) * Math.cos(Lng1);
    var y1 = Math.cos(Lat1) * Math.sin(Lng1);
    var z1 = Math.sin(Lat1);
    // unit vectors pointing East and North
    var xEast = -y1 / Math.sqrt(x1 * x1 + y1 * y1);
    var yEast = x1 / Math.sqrt(x1 * x1 + y1 * y1);
    var zEast = 0;
    var xNorth = -x1 * z1 / Math.sqrt(x1 * x1 + y1 * y1);
    var yNorth = -y1 * z1 / Math.sqrt(x1 * x1 + y1 * y1);
    var zNorth = Math.sqrt(x1 * x1 + y1 * y1);
    // unit vector with the given azimuth angle
    var xv = xNorth * Math.cos(Azimuth) + xEast * Math.sin(Azimuth);
    var yv = yNorth * Math.cos(Azimuth) + yEast * Math.sin(Azimuth);
    var zv = zNorth * Math.cos(Azimuth) + zEast * Math.sin(Azimuth);
    // terminal point in Cartesian coordinates
    var x2 = x1 * Math.cos(distance) + xv * Math.sin(distance);
    var y2 = y1 * Math.cos(distance) + yv * Math.sin(distance);
    var z2 = z1 * Math.cos(distance) + zv * Math.sin(distance);
    // terminal point in spherical coordinates
    var lat2 = Math.asin(z2) * 180 / Math.PI;
    var lng2 = Math.atan2(y2, x2) * 180 / Math.PI;
    // output
    document.write("
From latitude ", lat1, " and longitude ", lng1, ", starting with azimuth ", azimuth, " and going for distance ", distance, " (times the radius):
");
    document.write("
New latitude is ", lat2, " degrees. New longitude is ", lng2, " degrees.
");
}

f(24, 53, -55, 30);
g(24, 53, 193, 1.42);


Geometric transformations in Olympiad problems - Putnam 2001, A-4

Question: I have been reading Pasumarty's article A Fine Use of Transformations in Mathematical Reflections 4 (2016).
The first part of the article deals with question A-4 on Putnam 2001:

Triangle $ABC$ has an area $1$. Points $E$, $F$, $G$ lie, respectively, on $BC$, $CA$,
$AB$ such that $AE$ bisects $BF$ at point $R$, $BF$
bisects $CG$ at point $S$, and $CG$ bisects $AE$ at point $T$. Find the area of the
triangle $RST$.

I have already read the answer to this question, but I don't understand the following sentence in Pasumarty's article:

By symmetry in the equilateral case, we can see that $\dfrac{AG}{AB} = \dfrac{BE}{BC} = \dfrac{CF}{CA}  = r$.

How can I formally prove the equality of these ratios if $ABC$ is an equilateral triangle? I tried to consider the clockwise (or counterclockwise) rotation of $120^{\circ}$ about the center of the triangle, that maps $ABC$ to itself, but I can't prove that the image of $AG$ is $BE$, the image of $BE$ is $CF$ and the image of $CF$ is $AG$, or something similar.
Comment: I think it's a logical flaw in that article. We don't know *a priori* that the resulting picture is symmetric, although by some continuity argument one can "show" that a symmetric solution *exists*. But the whole article (as probably the whole Euclidean geometry) is not really logically rigorous, according to modern standards.
Comment: @WhatsUp The article has some flaws (and the solution is transcribed second-hand, apparently; I have faith that Sam Zbarsky adressed this point) but you shouldn't be that dismissive of Euclidean geometry as a whole. Its logical rigor has been in fine shape at least since Hilbert in 1899.
Comment: @MishaLavrov I did say "according to modern standards". Even Hilbert's axioms have [known issues](https://en.wikipedia.org/wiki/Hilbert%27s_axioms#Application), mostly the reliance on an accurate diagram.
Comment: @WhatsUp If your standards for a lack of issues are "has been verified by computer proof" then 99% of modern mathematics is not really logically rigorous. If one of the many geometric statements Hilbert proved needs some extra thinking to resolve, that's an incredibly minor issue.
Answer: First, look at just one pair of lines with one condition: $G$ is a point on line $AB$, and $BF$ bisects $CG$ at point $S$.
If $\frac{AG}{AB} = r$ and $\frac{CF}{CA} = s$, we can find a relationship between $r$ and $s$. For example, using areas: since $S$ bisects $CG$, $[BFG] = [BFC]$. We have $[BFC] = s \cdot [ABC]$, and $$[BFG] = (1-r) \cdot [BFA] = (1-r) \cdot (1-s) \cdot [ABC],$$ so $s = (1-r)(1-s)$, which is easiest to write as $r = 1- \frac{s}{1-s} = \frac{1-2s}{1-s}$.
The actual algebraic relationship is not super important to this step, but I derive it to give a rigorous proof of an intuitive fact: as $s$ increases, $r$ decreases, and vice versa.
The same relationship must hold between any two of the three ratios, by an identical proof.

Now suppose that (for a fixed equilateral $\triangle ABC$) there are multiple possible ways to draw $AE, BF, CG$ that satisfy the condition. Choose one with the maximum possible value of $\frac{AG}{AB}$. Then it must have the minimum possible value of $\frac{CF}{CA}$. Then it must have the maximum possible value of $\frac{BE}{BC}$, from which we deduce that actually it has the minimum possible value of $\frac{AG}{AB}$. In other words, only one value of $\frac{AG}{AB}$, and similarly only one value of $\frac{CF}{CA}$ and $\frac{BE}{BC}$, is possible.
Having shown uniqueness, we are finally ready to look at what happens when we apply the $120^\circ$ rotation that takes $A$ to $B$, $B$ to $C$, and $C$ to $A$. In general, this takes the points $E,F,G$ to points $E', F', G'$ such that segments $A'E'$, $B'F'$, and $C'G'$ satisfy the condition in the problem; in other words, $BE'$, $CF'$, and $AG'$ have the property we want. But because the solution is unique, we must have $E'=F$, $F'=G$, and $G'=E$. From this, $AG=CF=BE$ in the equilateral case follows.