How do I determine convergence with a comparison test?

Question: $$\sum_{n=2}^\infty \frac{1}{3n^2-2\sqrt{n}}$$
The instructions are to use a comparison test to determine convergence of the series. I thought to compare it to
$$\sum_{n=2}^\infty \frac{1}{3n^2}$$
which converges by the p-series test. But, that series is smaller than the original series, so it doesn't prove that the original series will converge too. Where do I go from here?
Comment: You already get the idea the series is 'roughly' similar to a $2$-series. So if $\dfrac{1}{3n^2}$ is too small, can you find another constant to make the $2$-series larger than $\displaystyle\sum^{+\infty}_{n=2}\dfrac{1}{3n^2-2\sqrt{n}}$?
Comment: What part of the series is the 'constant' and what does it mean to be a '2-series'?
Comment: We call $\displaystyle\sum^{+\infty}_{i=1}\dfrac{1}{n^p}$ be a $p$-series. In the case $p=2$, so we call it a $2$-series. For the constant, I actually mean the $\dfrac{1}{3}$ is making the $2$-series too small, so asking you to suggest a new candidate of $2$-series but not with $\dfrac{1}{3}$.
Comment: Okay, I understand why we call it a 2-series. But I'm struggling to understand the other part. How does choosing a different constant help, and how do I know what to choose?
Comment: For choosing constants, the idea is like, you know you need a constant larger than $\dfrac{1}{3}$, so you can try like $1$, $2$, etc. But how do you prove that?  Usually either by induction, or it maybe quite obvious (like the hints below). So the choice is quite depending on you, because let's say $1$ is suitable choice, then every number greater than $1$ is also suitable.
Answer: Hint: $3n^2-2\sqrt{n}\ge n^2$ for $n\ge 2$.
In case you do not know, I provide more steps below.

 $3n^2-2\sqrt{n}\ge n^2\iff 2n^2\ge 2\sqrt{n}\iff n^4\ge n\iff n\ge1$. So we have $$\sum^m_{n=2}\dfrac{1}{3n^2-2\sqrt{n}}\le\sum^m_{n=2}\dfrac{1}{n^2}$$for each $m\ge2$. By $\cdots$


Strip all non-numeric characters from string in JavaScript

Question: Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.
var myString = 'abc123.8<blah>';

//desired output is 1238

How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.
Answer: Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');

Comment: This is my default regex reference: http://www.regular-expressions.info/reference.html

The built-in character classes each have built-in complements.
\d \D (digits versus everything but digits)
\w \W (word charcters versus everything but word characters)
\s \S (whitespace versus everything but whitespace)
Comment: Thanks csj; anyplace to find more info on `\D` ?
Comment: Just to be clear, here is the syntax for replace: http://www.w3schools.com/jsref/jsref_obj_regexp.asp because the forward slashes and the "g" are part of that command, not part of the RegEx.
Comment: does `replace` work with this exact syntax in all browsers? seems like I remember getting an `object has no method 'replace' ` in an older version of IE when using this with text I grabbed with jQuery... or something like that.
Comment: @cwd I have no idea what has been supported in past or current browsers. The question specified a non-DOM context, so it's likely that the poster was scripting in a non web browser environment.
Comment: This turns `1.2` into `12`
Comment: Great tool to test regular expression online (It's not mine :)).
https://regex101.com
Comment: i tried following but nothing worked

"this.value = this.value.replace(eval(!/^[A-Za-z\d.#-,]$/),'')"

"this.value = this.value.replace(eval(/^[A-Za-z\d.#-,]$/),'')"

"this.value = this.value.replace(eval(specialCharRegex),'')"

what should i do?
Comment: You can use `String(myString).replace(/\D/g,'')` in case they pass only a number this code won't throw an error.
Comment: this works fine for positive integers but goodbye negative numbers.
Comment: @skilleo fair enough, but the OP did eventually edit their question to indicate that they were seeking to preserve the digits themselves. 0-9
Comment: @adamdport The OP's example specifically shows a period being stripped away.
Answer: If you need this to leave the dot for float numbers, use this
var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"

Comment: Any regexp experts? How to make this allow only a single dot (very relevant with numbers). Thanks!
Comment: @Kasperi perhaps:
`parseFloat("-1234.5.50 €".replace(/[^\d.-]/g, ''))`
Comment: Not good: `"aaa 2.9px of bbb.".replace(/[^\d.-]/g, '')` → `2.9.` Should strip any String which might surround a Number..
Comment: @max4ever you saved my life, thanks for handling `-`(negative) number case :)
Comment: what do you mean? give input and output example
Comment: I mean, it currently accepts for example "1..56" and "1.5.28", right? Is it possible to make it accept only numbers with a single dot, such as "1.56"?
Comment: use http://stackoverflow.com/a/16951568/579646 to test it like this: new RegExp(/^-?\d+\.?\d*$/).test("1.5.28")
Comment: Is that possible to change all `,` by `.` in your regex? In some countries, the comma is used as a separator instead of the point. :)
Comment: @max4ever Whats with the "`-`" in the regexp?
Comment: @Mistalis it is, but be aware, in such cases there is possibilty they are both there (Eg. 1,000,000.5) - so you should rather do .replace(/",","."/g) first :)
Comment: Great test! my first idea is [^\d.-]+[^\d]+ should work in this case
Comment: Great answer, if you want a numeric field you mean any number event floats :)
Answer: Use a regular expression, if your script implementation supports them. Something like:
myString.replace(/[^0-9]/g, '');

Comment: For some reason this way seems much more readable than [^\d].
Comment: @NativeCoder https://stackoverflow.com/questions/12993629/what-is-the-meaning-of-the-g-flag-in-regular-expressions
Comment: whats the g for after the regex delimiter??
Comment: will not work for float/decimal values for example, "7.6$" will return 76
Comment: like @SikandarTariq mentioned but also negative values.
Answer: You can use a RegExp to replace all the non-digit characters:
var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238

Answer: Something along the lines of:
yourString = yourString.replace ( /[^0-9]/g, '' );

Comment: Not exactly an answer to the original question, but a version to handle the decimal point: `yourString = yourString.replace ( /[^0-9.]/g, '' );`
Comment: Late to the party but also need dash and comma. In certain regions decimal is done with a comma: `replace(/[^0-9.,-]/g, ''`
Answer: Short function to remove all non-numeric characters but keep the decimal (and return the number):

parseNum = str => +str.replace(/[^.\d]/g, '');
let str = 'a1b2c.d3e';
console.log(parseNum(str));
Comment: You might want to add "-" as well because the number can be negative as well.
Comment: For me, this is better than the accepted answer, because it keeps the decimal.
Comment: ...but only if `-` is the first character
Comment: this does WRONG for the input `my text: 9123.11, okay.?`
Answer: The problem with these answers above, is that it assumes whole numbers.  But if you need a floating point value, then the previous reg string will remove the decimal point.
To correct this you need write a negated character class with ^
var mystring = mystring.replace(/[^0-9.]/g, '');

Comment: this does WRONG for the input `my text: 9123.11 okay.`
Answer: In Angular / Ionic / VueJS -- I just came up with a simple method of:
stripNaN(txt: any) {
    return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
}

Usage on the view:

Answer: Unfortunately none of the answers above worked for me.
I was looking to convert currency numbers from strings like $123,232,122.11 (1232332122.11) or USD 123,122.892 (123122.892) or any currency like ₹ 98,79,112.50 (9879112.5) to give me a number output including the decimal pointer.
Had to make my own regex which looks something like this:
str = str.match(/\d|\./g).join('');

Answer: try
myString.match(/\d/g).join``

var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join`` );
Comment: how does this work?
Comment: @1252748 match will filter all digits and put them into array, join will glue array elements into single string
Comment: i meant the join with the backticks. what's going on there?
Comment: @1252748 read about: `js tagged templates`
Comment: Yeah I've seen tagged templates, just don't understand what is going on with join using them. Is this just saving two characters, invoking join with a single argument `""`?
Answer: This,
.match(/\d|\.|\-/g).join('');

Handles both , and . also -
Example:
"Balance -$100,00.50".match(/\d|\.|\-/g).join('');
Outputs
-10000.50
Answer: we are in 2017 now you can also use ES2016
var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or
console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));

The result is
1238

Comment: This is a very inefficient way to go about this operation.
Comment: It converts the string into an array of single-character strings via a spare method, and then applies filter function over JavaScript on each array item, returning a new string array, to finally join that array back into a string. Regex takes a string and returns a string and the processing is done via native code.


Netlogo, Checking if two agents are connected to the same agent

Question: I have a problem I wish to solve. Lets say there are two type of agents (rabbits and hunters). I want the hunters to find the closest rabbit to them. But if two hunters were to find the same rabbit  (i.e the closest rabbit to hunter 103 and hunter 105 is rabbit 99). I want one of the hunters to find the next closest rabbit. So each hunters need to check which rabbits the other hunters are connected to and if any hunter is connected to same rabbit, find the next closest rabbit. Any ideas how to solve this. Thanks
breed [hunters hunter]
breed [rabbits rabbit]

hunters-own [rab-in-sight]

to setup
  clear-all
  create-hunters 20
  create-rabbits 100

  ask hunters [
  set color red
  setxy random-xcor random-ycor
  ]
  ask rabbits [
    set color white
    setxy random-xcor random-ycor
  ]

end

to connect
  ask hunters [
    set rab-in-sight min-one-of rabbits in-radius 5 [distance myself]
  ]

end

Answer: You could use either a variable that indicates whether a rabbit has been targeted, or use links to accomplish the same thing.
Link approach
Check out this modified version of your setup that has hunters set their rab-in-sight to nobody:
breed [hunters hunter]
breed [rabbits rabbit]

hunters-own [rab-in-sight]

to setup
  clear-all
  create-hunters 20
  create-rabbits 100

  ask hunters [
    set color red
    setxy random-xcor random-ycor
    set rab-in-sight nobody
  ]
  ask rabbits [
    set color white
    setxy random-xcor random-ycor
  ]
  reset-ticks
end

Then, use if or ifelse statements to control hunter behavior based on whether it is currently hunting a rabbit:
to go
  ask hunters [
    connect
  ]
  tick
end

to connect
  ; If a hunter is not already targetting a rabbit
  ifelse rab-in-sight = nobody [
    fd 1

    ; Choose a target rabbit that does not already have a link with other hunters
    set rab-in-sight min-one-of ( rabbits in-radius 5 with [
      not any? my-links ] ) [distance myself]

    ; If that rabbit exists, create a link with it so no other hunters will
    ; target the same rabbit
    if rab-in-sight != nobody [
      create-link-with rab-in-sight
    ]
  ] [
    ; If you're targetting a rabbit, hunt it
    face rab-in-sight
    ifelse distance rab-in-sight > 1 [
      fd 1
    ] [
      move-to rab-in-sight
      ask rab-in-sight [
        die
      ]
      set rab-in-sight nobody
    ]
  ]
end

Variable approach
The flag or semaphore variable approach is similar- a slightly modified setup now sets rab-in-sight to nobody and gives rabbits a targeted? boolean variable that is set to false:
breed [hunters hunter]
breed [rabbits rabbit]

hunters-own [rab-in-sight]
rabbits-own [ targeted? ]

to setup
  clear-all
  create-hunters 20
  create-rabbits 100

  ask hunters [
    set color red
    setxy random-xcor random-ycor
    set rab-in-sight nobody
  ]
  ask rabbits [
    set color white
    setxy random-xcor random-ycor
    set targeted? false
  ]
  reset-ticks
end

Now, when a hunter targets a rabbit it has that rabbit change its targeted? variable to true so that other hunters "know" not to target it as well:
to go
  ask hunters [
    connect
  ]
  tick
end

to connect
  ; If a hunter is not already targetting a rabbit
  ifelse rab-in-sight = nobody [
    fd 1

    ; Choose a target rabbit that is not currently being targeted
    set rab-in-sight min-one-of ( rabbits in-radius 5 with [
      not targeted? ] ) [distance myself]

    ; If that rabbit exists, have it set targetted? to true so
    ; no other hunters will target the same rabbit
    if rab-in-sight != nobody [
      ask rab-in-sight [
        set targeted? true
      ]
    ]
  ] [
    ; If you're targetting a rabbit, hunt it
    face rab-in-sight
    ifelse distance rab-in-sight > 1 [
      fd 1
    ] [
      move-to rab-in-sight
      ask rab-in-sight [
        die
      ]
      set rab-in-sight nobody
    ]
  ]
end

Answer: In this case, I recommend creating a seperate agent-set for the rabbits, say rabbits-not-hunted. The hunter selects one of the rabbits close by in this set, while the selected rabbit is removed from this set. Therefore the next hunter cannot select this rabbit as a target anymore and selects the next "free" prey. Please check the code below:
breed [hunters hunter]
breed [rabbits rabbit]

hunters-own [rab-in-sight]

to setup
  clear-all
  create-hunters 20
  create-rabbits 100

  ask hunters [
  set color red
  setxy random-xcor random-ycor
  ]
  ask rabbits [
    set color white
    setxy random-xcor random-ycor
  ]

end

to connect
  ;; a seperate agentset of all rabbits which are not hunted yet. At first, all rabbits can be hunted, therefore it coincides with all rabbits
  let rabbits-not-hunted rabbits

  ask hunters [
    ;; the prospective prey is taken from the set of rabbits-not-hunted yet
    let prospective-prey turtle-set min-one-of rabbits-not-hunted in-radius 5 [distance myself]

    set rab-in-sight prospective-prey

    ;; updates rabbits-not-hunted agentset by removeing the prey selected from the agentset
    set rabbits-not-hunted rabbits-not-hunted with [ not member? self prospective-prey ]
  ]

end

Please note, that the code can produce errors if there is just one rabbit within the radius of hunter while this rabbit is already a target of another hunter. Given the hunter-prey ratio in your code, this is unlikely to happen, nevertheless I wanted to give you a fair warning for this.


Alternately add uppercase and lowercase letters?

Question: I am working on a task for a beginner python course. Task is to take first uppercase letter and then lowercase letter and all over again.
this is input string:
"ifeFemFEkej83FkW"

and this should be output string:
FeFkFkW

friend and I came up with this solution, but it looks a little bit complicated, and I was wondering if there is maybe one-line solution or regular expression for some part of the code? Or maybe some different approach to the task. Thank you for your help.
str_a = "ifeFemFEkej83FkW"
new = ""
upper_case = True

for i in str_a:
    if "A" < i < "Z" and upper_case == True:
        new += i
        upper_case = False
    elif "a" < i < "z" and upper_case == False:
        new += i
        upper_case = True

print(new)

Comment: You could bring up imports and the standard library if you use string.ascii_uppercase and string.ascii_lowercase. You might want to teach it as a function, so you can show a test case. It could be a good time to introduce "in" if they're ready for sets or know big-O, but maybe not. And iterables are pretty important, but might be a bit soon for that, too.
Answer: Here's a way to simplify it, using the isupper() function and the fact that you can always flip a bool to its opposite with not:
str_a = "ifeFemFEkej83FkW"
new = ""
upper_case = True

for i in str_a:
    if i.isupper() == upper_case:
        new += i
        upper_case = not upper_case

print(new)

And here's an approach with itertools.groupby.  This would be a pretty clean one-liner if not for the requirement of dropping initial lowercase letters:
import itertools

str_a = "ifeFemFEkej83FkW"

new = ''.join(next(g) for _, g in itertools.groupby(str_a, str.isupper))
new = new if new[0].isupper() else new[1:]

print(new)

Comment: Pretty good, as long as everything is upper or lower. There might be an issue if e.g. numbers sneak in. Maybe chain a filter (which can remove the initial lowercase as well)?
Comment: `list(g)[0]` == `next(g)`, +1 still, mainly for the first solution :)


Call on data from one dataframe to help sort another

Question: I would like to create a "menu" of items you could find at a grocery store. My goal is to generate every permutation of picking 5 pieces of fruit (with replacement), and find the total cost of the 5 fruit. Here's what I have currently.
fruit = data.frame(c("apple", "banana", "orange", "pear", "strawberry"))
price = data.frame(c(0.99, 1.59, 0.70, 1.29, 2.99))

## Rename column headers
colnames(fruit)[1] = "Fruit"
colnames(price)[1] = "Price"

menu = cbind(fruit, price)

## Turn fruit dataframe into a vector
fruit_vector = as.vector(fruit[[1]])

## Generate all permutations

permutations = data.frame(expand.grid(Fruit_1 = fruit_vector,
                                      Fruit_2 = fruit_vector,
                                      Fruit_3 = fruit_vector,
                                      Fruit_4 = fruit_vector,
                                      Fruit_5 = fruit_vector))

Here's the part that I'm stuck on: I would like to create a 6th column in my dataframe that takes all 5 fruit from a row and sums their prices for a single total price.
Is there a way to call on information from my "menu" data frame that matches the price of an apple to 0.99, the price of a banana to 1.59, etc.?
Thoughts (other than the questionable food prices)?
I thought about making individual columns to have the price of fruit_1, the price of fruit_2, etc, and them sum them up into an 11th column, but I feel like that is less efficient, and that still doesn't solve my issue of seeing an apple and having R automatically identify that as 0.99.
Answer: An option using dplyr:
library(dplyr)

fruit = data.frame(c("apple", "banana", "orange", "pear", "strawberry"))
price = data.frame(c(0.99, 1.59, 0.70, 1.29, 2.99))

## Rename column headers
colnames(fruit)[1] = "Fruit"
colnames(price)[1] = "Price"

menu = cbind(fruit, price)

## Turn fruit dataframe into a vector
fruit_vector = as.vector(fruit[[1]])

## Generate all permutations

permutations = data.frame(expand.grid(Fruit_1 = fruit_vector,
                                      Fruit_2 = fruit_vector,
                                      Fruit_3 = fruit_vector,
                                      Fruit_4 = fruit_vector,
                                      Fruit_5 = fruit_vector)) %>%
  mutate(id = row_number())

permutations %>%
  mutate(across(Fruit_1:Fruit_5, ~case_when(. == "apple" ~ 0.99,
                                         . == "banana" ~ 1.59,
                                         . == "orange" ~ 0.7,
                                         . == "pear" ~ 1.29,
                                         . == "strawberry" ~ 2.99))) %>%
  rowwise() %>%
  mutate(total = sum(c(Fruit_1, Fruit_2, Fruit_3, Fruit_4, Fruit_5))) %>%
  ungroup() %>%
  select(id, total) %>%
  right_join(permutations)
#> Joining, by = "id"
#> # A tibble: 3,125 × 7
#>       id total Fruit_1    Fruit_2 Fruit_3 Fruit_4 Fruit_5
#>    <int> <dbl> <fct>      <fct>   <fct>   <fct>   <fct>
#>  1     1  4.95 apple      apple   apple   apple   apple
#>  2     2  5.55 banana     apple   apple   apple   apple
#>  3     3  4.66 orange     apple   apple   apple   apple
#>  4     4  5.25 pear       apple   apple   apple   apple
#>  5     5  6.95 strawberry apple   apple   apple   apple
#>  6     6  5.55 apple      banana  apple   apple   apple
#>  7     7  6.15 banana     banana  apple   apple   apple
#>  8     8  5.26 orange     banana  apple   apple   apple
#>  9     9  5.85 pear       banana  apple   apple   apple
#> 10    10  7.55 strawberry banana  apple   apple   apple
#> # … with 3,115 more rows

Answer: You can build your menu simply by using a named vector.
fruit_price <- unlist(price)
names(fruit_price) <- unlist(fruit)

fruit_price
     apple     banana     orange       pear strawberry
      0.99       1.59       0.70       1.29       2.99

Then combine it with the existing permutations data frame
head(data.frame(permutations,
                total_price = apply(permutations, 1, function(x)
                  sum(fruit_price[x]))))
     Fruit_1 Fruit_2 Fruit_3 Fruit_4 Fruit_5 total_price
1      apple   apple   apple   apple   apple        4.95
2     banana   apple   apple   apple   apple        5.55
3     orange   apple   apple   apple   apple        4.66
4       pear   apple   apple   apple   apple        5.25
5 strawberry   apple   apple   apple   apple        6.95
6      apple  banana   apple   apple   apple        5.55


Integral $\int_0^{1}\frac{(1+x^2)\ln(1+x^4)}{1+x^4}dx$

Question:
Find: $$I=\int_0^{1}\frac{(1+x^2)\ln(1+x^4)}{1+x^4}\,dx$$

I need to use the definition of do Trigamma function but I don't see how.
My try was as following :
Let $y=x^4$ then $dy=4x^{3}\,dx$ so $\;dx=\frac{dy}{4y^{\frac{3}{4}}}$.
$$I=\int_0^{1}\frac{(1+x^{\frac{3}{4}})\ln(1+x)}{x^{\frac{3}{4}}+x^{\frac{7}{4}}}dx$$
Use : $\ln(1+x)=-\sum_{n=1}^{\infty}\frac{(-1)^{n}x^n}{n}$
We obtain
$$J=\int_0^{1}\frac{x^n+x^{(3+4n)/4}}{x^{3/4}+x^{7/4}}dx$$
Then I use definition of digamma function
$$\int_0^{1}\frac{x^{a-1}\ln x}{1+x}\,dx=\beta'(a)$$
Where:  $$2\beta(a)=\psi\left(\frac{1+a}{2}\right)-\psi\left(\frac{a}{2}\right)$$
But I find sum related with digamma function.
So I don't have other ideas to approach it!
Comment: The result of MMA is very large!
Comment: *Which* definition of the Trigamma Function?
Comment: See now I add soothing !!
Comment: @Dr.SonnhardGraubner. The result of MMA is very small !. MMA code: `-Derivative[0, 1, 0, 0][Hypergeometric2F1][1/4, 1, 5/4, -1] -
 Derivative[0, 1, 0, 0][Hypergeometric2F1][3/4, 1, 7/4, -1]/3`
Comment: Ok, i'm using an older version
Comment: @Dr.SonnhardGraubner. Try: `D[Integrate[(1 + x^2)/(1 + x^4)*(1 + x^4)^t, {x, 0, 1},
   Assumptions -> t >= 0], t] /. t -> 0`
Answer: (Too long for a comment.)
Zacky gave the answer:
$$\small \int_0^1 \frac{(1+x^2)\ln(1+x^4)}{1+x^4}dx=\frac{3\pi}{2\sqrt 2}\ln 2-\frac1{32}\left(\psi_1\left(\frac{1}{8}\right)+\psi_1\left(\frac{3}{8}\right)-\psi_1\left(\frac{5}{8}\right)-\psi_1\left(\frac{7}{8}\right)\right)$$
After my post on Catalan's constant $K = \rm{Cl}_2\big(\tfrac\pi2\big)$ and Gieseking's constant $\kappa =\rm{Cl}_2\big(\tfrac\pi3\big)$, I recognized the four polygammas as involving Catalan's quartic counterpart $\rm{Cl}_2\big(\color{red}{\tfrac\pi4}\big)$, namely,
$$-\small\frac1{32} \left(\psi_1\left(\frac{1}{8}\right)+\psi_1\left(\frac{3}{8}\right)-\psi_1\left(\frac{5}{8}\right)-\psi_1\left(\frac{7}{8}\right)\right) = \frac1{\sqrt2}\Big(K-4\,\rm{Cl}_2\big(\color{red}{\tfrac\pi4}\big)\Big)$$
Hence we have the simple closed-form,
$$\int_0^1 \frac{(1+x^2)\ln(1+x^4)}{1+x^4}dx=\frac{3\pi}{2\sqrt2}\ln 2+ \frac K{\sqrt2} -\frac{4\rm{Cl}_2\big(\color{red}{\tfrac\pi4}\big)}{\sqrt2}$$
where $\rm{Cl}_2\big(\tfrac\pi4\big) = \Im\, \rm{Li}_2(e^{2\pi i/8})$.
Answer: $$\small \boxed{\int_0^1 \frac{(1+x^2)\ln(1+x^4)}{1+x^4}dx=\frac{3\pi}{2\sqrt 2}\ln 2-\frac1{32}\left(\psi_1\left(\frac{1}{8}\right)+\psi_1\left(\frac{3}{8}\right)-\psi_1\left(\frac{5}{8}\right)-\psi_1\left(\frac{7}{8}\right)\right)}$$
To see that write the integral as:
$$I=\int_0^1 \frac{(1+x^2)\ln(1+x^4)}{1+x^4}dx\overset{x\to \frac{1}{x}}=\int_1^\infty \frac{(1+x^2) (\ln(1+x^4)-\ln(x^4))}{1+x^4}dx$$
$$\Rightarrow 2I=\int_0^\infty \frac{(1+x^2)\ln(1+x^4)}{1+x^4}dx-4\int_1^\infty \frac{(1+x^2)\ln x}{1+x^4}dx$$

For the first integral consider:
$$I(a)=\int_0^\infty \frac{(1+x^2)\ln(a+x^4)}{1+x^4}dx\Rightarrow I'(a)=\int_0^\infty \frac{1+x^2}{(a+x^4)(1+x^4)}dx$$
$$=\frac{1}{a-1}\int_0^\infty \frac{1+x^2}{1+x^4}dx-\frac{1}{a-1}\int_0^\infty \frac{1+x^2}{a+x^4}dx$$
$$\int_0^\infty \frac{1+x^2}{1+x^4}dx=\int_0^\infty \frac{1+\frac{1}{x^2}}{\left(x-\frac{1}{x}\right)^2+2}=\frac{1}{\sqrt 2}\arctan\left(\frac{x^2-1}{\sqrt 2 x}\right)\bigg|_0^\infty =\frac{\pi}{\sqrt 2}$$
$$\int_0^\infty \frac{1+x^2}{a+x^4}dx\overset{x=\sqrt[4]at}=\sqrt[4]a\int_0^\infty \frac{1+\sqrt at^2}{a(1+t^4)}dt=a^{-3/4}\int_0^\infty \frac{dt}{1+t^4}+a^{-1/4}\int_0^\infty \frac{t^2dt}{1+t^4}$$
$$\int_0^\infty \frac{1}{1+t^4}dt\overset{t\to \frac{1}{t}}=\int_0^\infty \frac{t^2}{1+t^4}dt=\frac12 \int_0^\infty \frac{1+t^2}{1+t^4}dt=\frac{\pi}{2\sqrt 2}$$
$$\Rightarrow I'(a)= \frac{\pi}{2\sqrt{2}}\left(\frac{2-a^{-1/4}-a^{-3/4}}{a-1}\right) $$
We are looking here for $I(1)$, but $I(0)=0$, (put $x=\frac{1}{x}$ to see that), so:
$$\Rightarrow I(1)= \frac{\pi}{2\sqrt{2}}\int_0^1 \left(\frac{1-a^{-1/4}+1-a^{-3/4}}{a-1}\right)da=\frac{3\pi}{\sqrt 2}\ln 2 $$
Above follows by splitting into two parts and using this.

For the second integral we will use the trigamma function as you mentioned in your question.
$$\int_1^\infty \frac{(1+x^2)\ln x}{1+x^4}dx\overset{x\to \frac{1}{x}}=-\int_0^1 \frac{\ln x}{1+x^4}dx-\int_0^1 \frac{x^2\ln x}{1+x^4}dx$$
$$=\frac1{64} \left(\psi_1\left(\frac{1}{8}\right)+\psi_1\left(\frac{3}{8}\right)-\psi_1\left(\frac{5}{8}\right)-\psi_1\left(\frac{7}{8}\right)\right)$$
One can use trigamma's reflection formula in order to simplify two more terms, but I think it looks nice this way.
Comment: (+1) Feynman; again xD


how to check entered mobile number is exist in device or not?

Question: I have implemented Phone number selector API in my project, now I want to check if entered umber is exist in mobile or not? it should proceed only when the device has that entered number. And also number should be inserted in first slot. How to do that?
Here is my code:
HintRequest hintRequest = new HintRequest.Builder()
    .setHintPickerConfig(
        new CredentialPickerConfig.Builder().setShowCancelButton(true).build()
    )
    .setPhoneNumberIdentifierSupported(true)
    .build();

PendingIntent intent = Credentials.getClient(Register.this).getHintPickerIntent(hintRequest);

try {
    startIntentSenderForResult(intent.getIntentSender(),CREDENTIAL_REQUEST,null,0,0,0,new Bundle());

} catch (IntentSender.SendIntentException e) {
    e.printStackTrace();
}

enterNumber = findViewById(R.id.renter_number);
rback_btn = findViewById(R.id.rback_btn);
rback_btn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view)
    {
        Intent i = new Intent(getApplicationContext(), Welcome.class);
        startActivity(i);
    }
});

next = findViewById(R.id.nextbtn_r);
next.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        strnumber = enterNumber.getText().toString();
        String otp= new DecimalFormat("000000").format(new Random().nextInt(999999));
        Intent intent = new Intent(getApplicationContext(), Verification.class);
        intent.putExtra("Your OTP is:",otp);
        intent.putExtra("Number:",strnumber);
        startActivity(intent);
    }
});

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CREDENTIAL_REQUEST && resultCode == RESULT_OK) {
        //obtain the phone number from the result
        Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
        enterNumber.setText(credential.getId().substring(3));

        Toast
            .makeText(context, "Mob"+credential.getId().substring(3), Toast.LENGTH_SHORT)
            .show();
    } else if (
            requestCode == CREDENTIAL_REQUEST
            && requestCode == CredentialsApi.ACTIVITY_RESULT_NO_HINTS_AVAILABLE
        ) {
        Toast
            .makeText(context, "No Phone Numbers found!", Toast.LENGTH_SHORT)
            .show();
    }
}

Comment: you want to check if entered number is placed in contacts or this is users phone number attached to SIM entered in device?
Comment: @snachmsm I want to check entered number is in device and check if it is in first sim or not if yes then only it should be proceed.
Answer: getting phone number isn't possible on Android. there is a method:
TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = mgr.getLine1Number();

that should work only with permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

but thats not reliable with nowadays SIM cards... in fact most of devices will return null. you can check this in system Settings -> About -> Phone Identinty (or Phone number)
note that SIM card itself does have some identity params, like serial number, but it is NOT storing own number, it is attached to SIM card on network side. thats why most of phone number validation services are asking for entering phone number, then sending SMS and asking for re-writting code (or you can do it programmatically - after requesting validating SMS sending just check incoming SMSes in next few secs/mins, and you will need a permission for that)


Spring Data Neo4J - NotInTransactionException while modifying set of nodeEntity

Question: We are using spring-data-neo4j with repository methods and annotated queries. Formerly, we used SDN with a rest connection to a standalone server. Performance was very poor, though, so we decided to use SDN with an embedded neo4j instance. But that does not work as expected.
Here are some classes
The node entity
import java.util.Set;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedToVia;

import com.xxx.xyz.relationships.UserToAnnotation;
import com.xxx.xyz.relationships.UserToBookmark;
import com.xxx.xyz.relationships.UserToGroup;
import com.xxx.xyz.relationships.UserToLastReadMedia;
import com.xxx.xyz.relationships.UserToLicenseOwner;
import com.xxx.xyz.relationships.UserToLicenseReader;
import com.xxx.xyz.relationships.UserToUser;

/** Simple user class. */
@NodeEntity
public class Neo4jUser {

    @GraphId
    Long id;

    private String type;

    @Indexed(unique=true)
    private String emailAddress;

    @Indexed
    private String nickname;

    private String passwordHash;

    private String givenName;

    private String familyName;

    private Long birthdate;

    @JsonIgnore
    @RelatedToVia(type = "isIn", direction = Direction.OUTGOING)
    private Set<UserToGroup> memberships;

    public Neo4jUser() {
    }

    //constructor

    //getter / setter

    public void isIn(final Neo4jGroup group, final String role) {
        memberships.add(new UserToGroup(this, group, role));
    }

}

One relationship entity
package com.xxx.xyz.relationships;

import org.springframework.data.neo4j.annotation.EndNode;
import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.RelationshipEntity;
import org.springframework.data.neo4j.annotation.StartNode;

import com.xxx.xyz.model.db.Neo4jGroup;
import com.xxx.xyz.model.db.Neo4jUser;

@RelationshipEntity(type="isIn")
public class UserToGroup {

    @GraphId
    Long id;

    @Fetch @StartNode
    private Neo4jUser user;

    @Fetch @EndNode
    private Neo4jGroup group;

    private String role;

    public UserToGroup(){
    }

    public UserToGroup(final Neo4jUser user, final Neo4jGroup group, final String role)
    {
        this.user = user;
        this.group = group;
        this.role = role;
    }

}

The user repository
@Transactional
public interface UserRepository extends GraphRepository<Neo4jUser> {

//annotated cypher queries

}

spring applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/data/neo4j
        http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:annotation-config />
    <context:spring-configured />
    <context:component-scan base-package="com.xxx.xyz.service" />

    <neo4j:config storeDirectory="data/graph.db" />

    <neo4j:repositories base-package="com.xxx.xyz.repository" />

</beans>

maven dependency
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

When trying to modify the set memberships by using the method Neo4JUser.isIn() the following exception is thrown
org.neo4j.graphdb.NotInTransactionException
    at org.neo4j.kernel.impl.persistence.PersistenceManager.getResource(PersistenceManager.java:252)
    at org.neo4j.kernel.impl.persistence.PersistenceManager.relationshipCreate(PersistenceManager.java:161)
    at org.neo4j.kernel.impl.core.NodeManager.createRelationship(NodeManager.java:252)
    at org.neo4j.kernel.impl.core.NodeImpl.createRelationshipTo(NodeImpl.java:578)
    at org.neo4j.kernel.impl.core.NodeProxy.createRelationshipTo(NodeProxy.java:207)
    at org.springframework.data.neo4j.support.DelegatingGraphDatabase.createRelationship(DelegatingGraphDatabase.java:125)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getOrCreateRelationship(EntityStateHandler.java:168)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.useOrCreateState(EntityStateHandler.java:139)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.write(Neo4jEntityConverterImpl.java:146)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.write(Neo4jEntityPersister.java:179)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:249)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:231)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:293)
    at org.springframework.data.neo4j.fieldaccess.RelatedToViaCollectionFieldAccessorFactory$RelatedToViaCollectionFieldAccessor.persistEntities(RelatedToViaCollectionFieldAccessorFactory.java:99)
    at org.springframework.data.neo4j.fieldaccess.RelatedToViaCollectionFieldAccessorFactory$RelatedToViaCollectionFieldAccessor.setValue(RelatedToViaCollectionFieldAccessorFactory.java:93)
    at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.updateValue(ManagedFieldAccessorSet.java:94)
    at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.update(ManagedFieldAccessorSet.java:82)
    at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.add(ManagedFieldAccessorSet.java:108)
    at com.xxx.xyz.model.db.Neo4jUser.isIn(Neo4jUser.java:187)

As I found out doing some research, the rest connection of SDN does not use transactions, the embedded version does, so NotInTransactionException are possible.
Moreover, we didn't expect save() to be triggered, when manipulating a set with relationships. We always called save() manually after. Why is that?
But what is done wrong here?
Any help is appreciated!
Thanks!
Answer: this is indeed a bit confusing and I have had  the same problems. If you are using the sets for relationships in you model, the set will be backed by SDN. So if you make any modifications to the set, SDN will try to change your DB accoringly(ie. creating/deleting relationships).
If you dont want your model to be backed by the database you should use Iterable.
http://static.springsource.org/spring-data/neo4j/docs/current/reference/htmlsingle/#reference:programming_model:relationships:relatedto
Comment: Thank you for the information. How can I avoid the exception, what needs to be changed / configured? How did you solve the problem?
Comment: As I mentioned, the easiest way is to use Iterable in your model classes. Then you cant create/delete relationships unintentionally. If however you want to be able to create/delete relationships directly with your model classes, you need to make sure that it happens in a transaction(use @Transactional).
Comment: For @Tranactional you should also add this to your spring config: .
Comment: Let's say we stick to Sets, where would I place the @Transactional annotation to make the method isIn() exception-safe?
Comment: It depends on how long you want you transaction to last :) At the very least, you will need it on the method where you are manipulating the set. Also note, that @Transactional per default only works on public methods and only when they are called from an outside class( see http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/transaction.html  Section 12.5.6 )
Comment: Finally we managed to solve our issue, because following your advice, we still had problems. That's why the reply is so late. We made some mistakes concerning autowiring, but now we got it running. Performance increase is tremendous compared to REST communication. Thank you so much!
Comment: @AndyB Getting a 404 on that link.


Extending Models in CodeIgniter

Question: I'm receiving this error for some odd reason:
Fatal error: Class 'crud_model' not found in /application/models/shared_model.php on line 3

From this line:
class Shared_model extends crud_model {

Which has worked before in the past. Does anyone know what may be occuring here? The file is the respective folder, it's spelled correctly, and I've event tried the following with no positive results.
class Shared_model extends Crud_model {

and
class Shared_model extends Crud_Model {

Here is crud_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Crud_model extends CI_Model {

public $table_name;
public $pk;

public function __construct()
{
    parent::__construct();
}

Here is shared_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Shared_model extends Crud_model {

public function __construct()
{
    parent::__construct();

    $this->pk = 'id';
    $this->table_name = 'shares';
}

Answer: Make sure all your extended classes extend from the proper parent class, this might be the issue or you can load any dependent models to your parent.
Comment: If you have figured this out please share your solution...
Comment: I did, and still no go. Any thoughts beyond that?
Comment: does your crud_model extend CI_Model, because then you can extend crud_model with shared_model also in your constructor, are you calling `parent::__construct();`
Comment: Yes, my crud_model.php does extend CI_Model, and I am calling my `parent::__construct();` in each model. Still no go.
Comment: I've figured ou the issue on my own. Thank you very much for all of your help!
Comment: @Irussell810 What was your solution? I'm currently having a similar problem. Thanks.
Answer: Shared model should be saved in the codeigniter's core folder because the classes in the core folder are loaded early during execution
Answer: A model's class must being with capital letters.

Extending Models in CodeIgniter


How to display objects related to a specific foreign key object?

Question: I am trying to make a gaming app in which people create their teams and then create players and associate players to a specific team. The problem is how can I only display the players in a team that is connected with it.
Advance Thanks for your help.
Here,s my models.py
class Team(models.Model):
   name = models.CharField(max_length =240)
   captain = models.CharField(max_length = 240)
   v_captain =  models.CharField(max_length = 240)

   def get_absolute_url(self):
    return reverse('games_app:detail',kwargs = {'pk':self.pk})

   def __str__(self):
    return self.name

class Players(models.Model):
 over = models.CharField(max_length = 10)
 batting = models.CharField(max_length = 100)
 player_team = models.ForeignKey(Team,related_name = "teams")

Here,s the views.py
class List_Players(generic.ListView):
 model = models.Players
 template_name = 'games_app/players_list.html'

Here,s the HTML
 <!DOCTYPE html>

<title></title>

{% for i in object_list.player_team %}

Players :{{i.player_name}}
    {% endfor %}

Comment: Your question is unclear. Your view lists `Players` objects, not `Team`s. Also you seem to be confused about the `related_name` argument, it should be the other way around (i.e. `related_name="players"`). As a side note, consider renaming `Players` to `Player` as it will make more sense with Django's naming conventions.
Comment: why do you want teams view
Comment: and how would I address the real problem.
Comment: I don't want teams view, I am saying that your code does not agree with your question. What is the real problem? As I said it is unclear. You wrote that you want to `display the players in a team ` but your code seems irrelevant. Editing your question to include an example of expected output might help.
Comment: I have already written that i only wanna display those players who are connected with that team.
Comment: Do you want to show team member for each player in the `ListView`? That will lead to huge amount of redundant information. You should use `Team`'s `ListView` show members of each team, or show team members on `DetailView` of a `Player`.
Comment: I wanna show the players that are related to the team.For e.g Player1 is the part of team 1 so i want him to show only in team1
Answer: it can be like:--
 class Team(models.Model):
    name = models.CharField(max_length =240)
    captain = models.CharField(max_length = 240)
    v_captain =  models.CharField(max_length = 240)

    def get_absolute_url(self):
       return reverse('games_app:detail',kwargs = {'pk':self.pk})

    def __str__(self):
       return self.name

class Players(models.Model):
   over = models.CharField(max_length = 10)
   batting = models.CharField(max_length = 100)
   player_team = models.ForeignKey(Team,related_name = "teams")

Here,s the views.py
class Team_list(generic.ListView):
  model = models.Team
  template_name = '''make a new template here'''
  context_object_name = 'team_list'

class List_Players(generic.DetailView):
    model = models.Players
    template_name = 'games_app/players_list.html'
    context_object_name = 'team_detail'

Here,s the HTML
   <!DOCTYPE html>

   <title></title>

{{ team_detail.name }}

{{ team_detail.captain }}

{{ team_detail.v_captain }}

   {% for players in team_detail.teams.all %}

Players :{{players.over}}

       {{ players.over }}
        {{ players.batting }}

   {% endfor %}

you have to make new Html file for your ListView of teams through which you can  link ur Detail view of whole team by using the  tag to the name of ur team
<!DOCTYPE html>

   <title></title>

   {% for teams in team_list %}

      {{ teams.name }}

   {% endfor %}

Answer: You need to iterate over each player in the object_list and print out the team members of the team associated with it.
{% for player in object_list %}

 {{player.player_name}}

    {% for i in player.player_team.players %}

Players :{{i.player_name}}
    {% endfor %}
{% endfor %}

But this is not at all recommended.
That will lead to huge amount of redundant information. You should use Team's ListView show members of each team, or show team members on DetailView of a Player. Consider to change the design of your page.
Comment: This doesn,t work . it shows all the players which are in db.
Comment: obviously, since you asked about the `ListView` of `Players`. I told you, you should use the `Team`'s `ListView`.


Delphi synchronizing panels order with table order

Question: I am generating panels at runtime. I have a panel on the form, then I have inside it a scrollBox alClient. Inside that scrollBox I add panels dynamically. They all belong to the Scrollbox, and I align them to bottom after I generate them. So they appear one above the other.
The code I use follows:
Procedure TMain.AdaugaElement(numar:integer; tip:string);
var
  pan:TPanel;
  semn:TShape;
  pos:TPoint;
  lab:TLabel;
  myimg:TImage;
  bmpsep, dest:TBitmap;
begin

  pan:=TPanel.Create(self);
  pan.Parent:=ScrollBox1;
  pan.Align:=alBottom;
  pan.Height:=50;
  pan.Name:='Layeru'+IntToStr(numar);
  pan.Caption:='Elementul '+IntToStr(numar);
  pan.Font.Color:=$00004F4F;
  pan.Font.Quality:=fqAntialiased;
  pan.Color:=$0080FFFF;
  pan.OnMouseDown:=layerRowMouseDown;
  pan.ParentColor:=false;
  pan.ParentBackground:=false;
  pan.Color:=clWhite;

  Pos:= pan.ClientOrigin;

  vt.AppendRecord([vt.RecordCount+1,Pan.name,numar,numar,0 ,0, 20,20,800,600,pan.Caption,tip]);

  lab:=TLabel.Create(self);
  lab.Parent:=pan;
  lab.Left:=54;
  lab.Top:=16;
  lab.Font.Size:=10;
  lab.Font.Color:=clBlack;
  lab.Font.Style:=[];
  lab.Font.Quality:=fqAntialiased;
  lab.Caption:=IntToStr(numar);
  Randomize;
  lab.Name:='Layernumber'+IntToStr(numar);

  semn:=TShape.Create(self);
  semn.Parent:=pan;
  semn.Left:=3;
  semn.Top:=3;
  semn.Height:=44;
  semn.Width:=44;
  semn.Pen.Color:=$00009D9D;
  semn.Brush.Color:=clWhite;

  myimg:=TImage.Create(self);
  myimg.Width:=42;
  myimg.Height:=42;
  myimg.Left:=4;
  myimg.Top:=4;
  myImg.Visible:=true;
  myimg.Proportional:=true;
  myimg.Stretch:=true;
  myImg.Parent:=pan;

  SelectLayerPan(numar);
end;

SelectLayerPan procedure simulates a selected row in a table, so when I add a new panel, it shows as 'selected' (it 'deselects' all panels then it 'selects' the new panel)
vt is a VirtualTable where I input information about the generated panels

So I add panels like this:
AdaugaElement(1,'type1');
AdaugaElement(2,'type1');
AdaugaElement(3,'type1');
AdaugaElement(4,'type1');

Next, I want to move panels among themselves using the mouse. So initially I have added:
- panel5
- panel4
- panel3
- panel2
- panel1

(in this order)
Then using the mouse, I drag panel1 and drop it between panel4 and panel5. So they will appear as:
- panel5
- **panel1**
- panel4
- panel3
- panel2

(in this order)
This drag-drop is done in layerRowMouseDown.
But, since in the virtualTable I have the info about panels (in the original order), so
record1: panel1  pos:1
record2: panel2  pos:2
record3: panel3  pos:3
record4: panel4  pos:4
record5: panel5  pos:5

I must identify the moved panels record and update it so it will reflect its new position, so the VirtualTable must look like this:
record1: panel1  pos:4
record2: panel2  pos:1
record3: panel3  pos:2
record4: panel4  pos:3
record5: panel5  pos:5

How can I do this?
I mean, how do I detect where the panel ended up when I drop it? Or maybe how do I get the order of the panels in their container (ScrollBox1)?
So far I tried using FindVCLWindow(pos) to identify the panels (and their order in the scrollBox) using the starting position and multiples of height of the panels, but when there are more panels, and they are no longer visible directly (without scrolling), it obviously stops working correctly.
So that is not a solution
Answer: The Top property of the panels in the TScrollBox seems to be the only reliable indicator for the order of the panels. To find the order of the panels you could assign the panels temporarily to a list and then sort that list on the Top property. Now you would have them in the same order in the list as they appear in the scrollbox.
The following is just an example of sorting with a temporary list. You will need to modify it to suit your purpose.
procedure TForm6.UpdateRecords;
var
  Comparer: IComparer<TMyPanel>;
  i: integer;
  s: string;
begin
  Comparer := TDelegatedComparer<TMyPanel>.Create(
    function (const A, B: TMyPanel):integer
    begin
      Result := A.Top - B.Top;
    end);
  TempPanelList := TMyPanelList.Create(Comparer);
  try
    for i := 0 to ScrollBox1.ControlCount-1 do
      TempPanelList.Add(TMyPanel(ScrollBox1.Controls[i]));
    TempPanelList.Sort;
    for i := 0 to TempPanelList.Count-1 do
    begin
      // replace this with your own code, something like in next snippet
      s := s + ', ' + inttostr(TempPanelList.items[i].Tag);
      Label1.Caption := s;
      //
    end;
  finally
    TempPanelList.Free;
  end;
end;

Then to get a reference between a panel in the list and corresponding record in vt you could use the tag property at creation of the panels. You seem to pass a parameter numar to the AdaugaElement procedure, so assuming this could work as an index to vt, you could assign this numar to pan.Tag.
Finally to update the pos fields in vt you could assign the new positions of the panels in a loop where you assign the index of the TPanel in the TempPanelList to pos in the vt record. Note! I don't know the proper syntax for working with VirtualTable
for i := 0 to TempPanelList.Count-1 do
begin
  vt[TPanel(TempPanelList[i]).Tag].pos := i;
end;

But your setup seems very fragile on many accounts, and the above doesn't help any of that. You are assigning the TMain instance (a form?) as the owner of all these TPanels, TShapes, TLabels and TImages. It becomes very messy when the user adds and deletes layers. I would instead create a composite class TLayerItem to hold everything related to one layer and a LayerManager class to manage the TLayerItems.
Comment: I did not use exactly your idea, however your answer got me inspired, and I found my solution. It is not using the panel tags, I use a label that is contained in the dynamic panel, and the major stuff that helps is using the vt (table). The spark idea that I used from you was the ordering by Top property of the panels. Thank you a lot
Answer: This seems like an inefficient solution. Also, why reinvent the wheel?
What you're describing is very similar to how a toolbar works, only it's laid out vertically rather than horizontally. I'd look at the source for some toolbars and see if you couldn't use something that's already designed to do what you want. If nothing else, you'll get some good ideas how to implement what you're trying to do.
Alternatively, I'd look into using a TFlowPanel inside the scrollbox where you'd put your panels on the flowpanel rather than directly onto the scrollbox.
EDIT: I apologize to whomever downvoted this, but we're not allowed to point to off-site stuff, and I'm not about to post all of the code for several toolbar components here.
Comment: It's not re-inventing the wheel. There is no 'wheel' (component) that acts and does what I need it to do. So it is `inventing` the wheel rather than re-inventing it
Comment: upvote! TFlowPanel  save lifes if you use bottom positioning in scrollbox


Como atribuir todas as características de um objeto para outro, menos uma em particular?

Question: Eu estou Criando um card game que roda no navegador e preciso que em algumas situações, possam haver as mesmas cartas em mãos diferentes("Computador" ou Jogador). Porem, não quero ter que criar outro objeto para representar as cartas inimigas. Este logo abaixo por exemplo, e um objeto que representa uma carta.
Bherk_tropa = {
  nome: 'Bherk',
  raca: 'Anão',
  classe: 'Clerigo',
  id: 'Bherk',

  corpo_a_corpo: true,
  pesadas: true,
  longo_alcance: true,
  armadadura: true,

  pvInical: 150,
  pontos_de_vida: 150,
  ataque: 70,
  defesa: 80,
  agilidade: 06,
  brutalidade: 13,
  Efeito: function(){

  }
}

Para criar outra carta semelhante a essa na mão do inimigo mudando somente o atributo e id por exemplo, tentei a seguinte linha de código:
Bherk_tropa_Inimigo = Bherk_tropa;
Bherk_tropa_Inimigo.id = "BherInimigo";

Mas o resultado foi que quando alterado o id de Bherk_tropa_Inimigo o id de Bherk_tropa também foi alterado. Espero Conseguir esclarecimento através de alguma boa alma. Agradeço dês de já. XD
Answer: Tente com o Spread operator. Ele irá realizar de fato uma cópia do objeto, e não apontar para a mesma referência:
let Bherk_tropa_Inimigo = {...Bherk_tropa};
Bherk_tropa_Inimigo.id = "BherInimigo";

Outro jeito de fazer:
Object.assign({}, Bherk_tropa);

O funcionamento será o mesmo.
Comment: Vlw, muito obrigado
Comment: Funcionou!! Muito obrigado amigo. Mas o que esse 'let' faz?
Comment: Ele inicializa a variável, no caso a `Bherk_tropa_Inimigo`, o mesmo que `var` porém possui um menor escopo. Caso utilize o código por gentileza aceite como a resposta correta. Obrigado.
Answer:
Se não for um inconveniente, o operador spread não é suportado pelos
  navegadores da Microsoft.

Você pode usar um for...in para inserir as chaves e seus valores de um objeto a outro:

var Bherk_tropa = {
  nome: 'Bherk',
  raca: 'Anão',
  classe: 'Clerigo',
  id: 'Bherk',

  corpo_a_corpo: true,
  pesadas: true,
  longo_alcance: true,
  armadadura: true,

  pvInical: 150,
  pontos_de_vida: 150,
  ataque: 70,
  defesa: 80,
  agilidade: 06,
  brutalidade: 13,
  Efeito: function(){
  }
}

var Bherk_tropa_Inimigo = {}; // cria o novo objeto

for(key in Bherk_tropa){
    Bherk_tropa_Inimigo[key] = Bherk_tropa[key]; // copia as chaves
}

Bherk_tropa_Inimigo.id = "BherInimigo"; // altera a chave "id"

console.log(Bherk_tropa.id); // mostra o valor de "id" no objeto original
console.log(Bherk_tropa_Inimigo.id); // mostra o novo valor de "id" no novo objeto
console.log(Bherk_tropa_Inimigo); // mostra o novo objeto completo
Comment: muito obrigado!


Prove that if $x+5$ is odd, then $x^2$ is even.

Question: I've been working on this for about an hour and cannot figure it out.
Problem: Prove that if $x+5$ is odd, then $x^2$ is even.
I've tried using induction, contrapositive, and contradiction methods. I cannot assume things like $1+\operatorname{even}= \operatorname{odd}$, only that $2k+1$ is odd and $2k$ is even where $k$ = integer.
Comment: First try to prove that x is even.
Comment: When $x+5$ is odd, then $x$ is even and therefore $x^2$ is even.
Comment: I added an answer, but others were faster. However, you could easily take those "intuitive answers" and make it rigorous. Take it as an extra exercise to prove that $1 + \text{even} = \text{odd}$ and $1 + \text{odd} = \text{even}$. The same can be done for $\text{odd} + \text{odd} = \text{even}$, etc.
Comment: No one has answered my question. Is anyone familiar with logic and proofs? I don't need intuitive answers.
Answer: If $x+5$ is odd, then by defintion, $\exists k\in \mathbb{Z}: x+5=2k+1.$
$$x+5 = 2k+1 \implies x=2k+1-5=2k-4$$
$$x=2k-4 = 2(k-2)$$
$$\implies x^2=4(k-2)^2=2(2(k-2)^2)$$
$$p=2(k-2)^2 \in \mathbb{Z} \implies x^2=2p$$
Thus, $x^2$ is even.
Comment: @user2665637 This is the accepted answer, but I'd say you better also use beedge89's answer's second line "Even numbers squared are even". If you are allowed to use the unique prime factorization of natural numbers, you can then skip on the explicit squaring of $x$ above.
Answer: $x+5$ odd implies $x$ is even (odd minus odd) is even.
Even numbers squared are even.
Answer: since " $x+5$ is odd" so "$x$ is even". therefore "$x^2$ is even":
for the last part note that if "$x$ is even" then we can write $x$ as: $x=2k$. so $x^2=4k^2=2\times 2k^2$, which is even.
Answer: To prove $x^2$ is even, you must first prove that $x$ is even.
You must always remember the following rules:
$$odd + odd = even$$
$$odd + even = odd$$
$$even + even = even$$
Given $x+5$ is odd. Since odd + odd can never be odd, $x$ should be even .
EDIT
Continuing from where you left.
Case 1: Let $x$ be even.$$x=2k$$
$$x+5 = 2k+5 = even + odd = odd$$
Case 2: Let $x$ be odd.$$x=2k+1$$
$$x+5 = 2k+1+5 = 2k+6 = 2(k+3) = even$$
Hence $x$ should be even which implies $x^2$ should be even.
Comment: Can you recreate that with only, even = 2k and odd = 2k+1 where k are integers.
Comment: @user2665637 Is this what you wanted ?
Answer: If $x+5$ is odd, then $x+4$ is even, so $x$ is even.
And if $x$ is even, then $x \cdot x = x^2$ must be even, too.
This follows from these statements:

If $n$ is odd, then $n+1$ is even
If $n$ is even, then $n+c$ is even, where $c$ is also even.
An even number multiplied by another even number gives an even number.
Answer: If you would prefer:
$$x+5=2k+1$$ for some $k\in \mathbb{Z}$. Then $$x=2k-4=2(k-2)$$ where we find $$x^2=(2(k-2))^2=4(k-2)^2=2(2(k-2)^2)=2c$$ where $c\in \mathbb{Z}$. Hence $x^2$ is even.
Answer: Let $x+5$ be odd. Then there exists an integer $k$ such that $2k+1 = x+5$, hence $2k = x + 4$, so $x+4$ is even. It follows that $x = 2k-4 = 2(k-2)$. Since $k-2$ is an integer it follows that $x$ is even. Now let $x = 2c$ for an integer $c$, then $x^2 = (2c)^2 = 4c^2 = 2(2c^2)$ is even since $2c^2$ is an integer.
Answer: $$\begin{aligned}x+5&=2k+1,k\in\Bbb{Z}\\
x&=2k-4,k\in\Bbb{Z}\end{aligned}$$Since $2k-4$ is even($4$ is even and even $-$ even $=$ even), $x$ is also even, implying that $x^2$ is also even.


NBA Wingspan-To-Height Ratio

Question: Is there a list where I can see the top NBA wingspan-to-height ratios?
For instance, I read that Dwayne Wade is 6'4" with a 6'11" wingspan. I would like to know other players with wingspans much greater than their height.
Answer:
Is there a list where I can see the top NBA wingspan to height ratios?

The NBA has recorded these stats for the draft combine since 2000. For example, Dwyane Wade's height and wingspan can be found in the draft combine statistics for the 2003 draft.

I would like to know other players with wingspans much longer than their height.

To see if a player's wingspan is longer than their height, I would do the following:

Copy and paste the data into an Excel Spreadsheet (I did not find a way to export the data)
Convert the wingspans and heights into inches (eg, 6'3.75" = 75.75 inches)
Use conditional formatting to compare the wingspan cells to its respective height cells

If you would like to compute a wingspan-to-height ratio, you may divide the wingspan by the height and come up with another column for the wingspan-to-height ratio.
Comment: Is it possible to sort the statistics by (wingspan minus height) or similar? If not, this doesn't really give a way to find *other* players in this state.
Comment: @PhilipKendall The advanced filters do not cover WINGSPAN or HEIGHT W/O SHOES (eg, WINGSPAN > HEIGHT W/O SHOES). I'm afraid this would be a manual check, unless there is a way to export the data to find such characteristics.

NBA Wingspan-To-Height Ratio


Gaussian Marginal Likelihood

Question: I am currently reading the Lawrence 2005 paper "Probabilistic non-linear Principal Component Analysis with Gaussian Process Latent Variable Models" available here. However I am failing to see how the integral in Equation 2 is evaluated in closed form.
The integral in question is a marginalisation over latent variables $\mathbf{x}$
$p(\mathbf{y}_{n} | \mathbf{W}, \beta) = \int p(\mathbf{y}_{n} | \mathbf{x}_{n}, \mathbf{W}, \beta) p(\mathbf{x}_{n}) d\mathbf{x}_{n}$
where the prior over $\mathbf{x}_{i}$ is given by
$p(\mathbf{x}_{n}) = \mathcal{N}(\mathbf{x}_{n} | \mathbf{0}, \mathbf{I})$
The author of the paper provides the closed form solution to this integration as the following
$p(\mathbf{y}_{n} | \mathbf{W}, \beta) = \mathcal{N}(\mathbf{y}_{n} | \mathbf{0}, \mathbf{W}\mathbf{W}^{T} + \beta^{-1} \mathbf{I})$
However it is not clear to me how this result is derived, any insight would be valued.
In general how does one tackle integrals of this form? i.e. computing marginals of continuous distributions? It seems that a lot of arcane matrix and distribution identities are used.
I know that in the case of a Gaussian Liklihood, a variable $\mathbf{x}_{n}$ may be marginalised by simply dropping it from the mean vector and covariance matrix. But what about the case of a distribution multiplied by one of it's conjugate priors?
Answer: We want to solve
$$
\int \mathcal N(y | Wx, \beta^{-1} I) \mathcal N(x | 0, I) dx
$$
$$
= \frac{\beta^{D/2}}{(2\pi)^{D/2}} \cdot \frac{1}{(2\pi)^{q/2}}\int \exp \left(-\frac \beta 2 || y - Wx ||^2 - \frac 12 x^T x\right) dx
$$
$$
\propto e^{-\frac \beta 2 y^T y}\int \exp \left(-\frac 12 \left[x^T(\beta W^T W
 + I)x - 2 \beta y^T W x\right]\right) dx.
$$
Let $C = \beta W^T W + I$ and $u^T = \beta y^T W$, and note that $C$ is positive definite. Then by completing the square we have that this last result is equal to
$$
e^{-\frac \beta 2 y^T y}\int \exp \left(-\frac 12 \left[ (x - C^{-1}u)^T C (x -
 C^{-1}u) - u^T C^{-1} u \right]\right) dx
$$
$$
\propto e^{-\frac 12 \left(\beta y^T y - u^T C^{-1} u\right)} = \exp \left(-\frac 12 y^T\left(\beta I - \beta^2 WC^{-1}W^T \right)y\right)
$$
so this tells us that $\Sigma^{-1} = \beta I - \beta^2 WC^{-1}W^T$ so now we need to decide if
$$
\Sigma = \left(\beta I - \beta^2 W \left(\beta W^T W + I\right)^{-1}W^T\right)^{-1} \stackrel ?= WW^T + \beta^{-1} I.
$$
Recall the Woodbury matrix identity:
$$
A^{-1} - A^{-1} U (B^{-1} + VA^{-1}U)^{-1}V A^{-1} = (A + UBV)^{-1}.
$$
Take $A = \frac 1\beta I$, $B = I$, $U = W$, and $V = W^T$. Then
$$
A^{-1} - A^{-1} U (B^{-1} + VA^{-1}U)^{-1}V A^{-1} = \beta I - \beta^2 W (I + \beta W^T W)^{-1}W^T = \Sigma^{-1} = \left(\frac 1 \beta I + W W^T\right)^{-1}
$$
$$
\implies \Sigma = \frac 1 \beta I + W W^T
$$
as desired.
This means that we have found that the kernel of the distribution is
$$
\exp \left(-\frac 12 y^T\left(WW^T + \beta^{-1} I\right)^{-1}y\right)
$$
which corresponds to $\mathcal N(y | 0, WW^T + \beta^{-1} I)$.

As a general strategy, integrals involving multiple normal pdfs usually require completing the square so that you can factor out some things and are left with a normal density that integrates to 1. While the Woodbury identity looks really ugly at first, it is so useful that very quickly you'll recognize it so this is just practice.
Comment: Thank you for such a wonderfully thorough answer. This is a huge help. I shall try to re-derive this again this evening. I din't even know about the Woodbury identity. Thank you.
Comment: @VisionIncision glad to hear this was helpful!

Gaussian Marginal Likelihood


How to download an Excel file

Question: I want to download an Excel sheet to my specific location not to Download folder.
I tried below code. Then the file is download to the "Download" folder. I need to download this file to a given file path.
<code>string filepath = "D:\";
string strDownloadableFilename = "Test.xlsx"
Using (MemoryStream stream = ExportExcel()){
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", strDownloadableFilename));
  stream.WriteTo(Response.OutPutStream); ;
  Response.End();
}
</code>
The file is download to "Download" folder.
Comment: It's up to the browser where to save the file, not the server-side code.  The server-side code has no knowledge of the client-side file system.  How is your browser configured to handle file downloads?  If it's configured to automatically save them to a common downloads folder then, well, that's what it's going to do.
Comment: To expand on David's excellent answer, consider the security risks if the server-side code *could* arbitrarily pick a download location on the client.  Big no-no.
Comment: Possible duplicate of [Download an Excel file](https://stackoverflow.com/questions/9603151/download-an-excel-file)
Answer: Well there are two things
first of all what you want to achieve can't be done by downoad option it means we can read file and write in system memory as per our desired location but in that case No download popup will see so you have to decide if you need download popup and no desired location or vice versa.

How to download an Excel file


Cloud Run PubSub high latency

Question: I'm building a microservice application consisting of many microservices build with Node.js and running on Cloud Run. I use PubSub in several different ways:

For streaming data daily. The microservices responsible for gathering analytical data from different advertising services (Facebook Ads, LinkedIn Ads, etc.) use PubSub to stream data to a microservice responsible for uploading data to Google BigQuery. There also are services that stream a higher load of data (> 1 Gb) from CRMs and other services by splitting it into smaller chunks.
For messaging among microservices about different events that don't require an immediate response.

Earlier, I experienced some insignificant latency with PubSub. I know it's an open issue considering up to several seconds latency with low messages throughput. But in my case, we are talking about several minutes latency.
Also, I occasionally get an error message

Received error while publishing: Total timeout of API google.pubsub.v1.Publisher exceeded 60000 milliseconds before any response was received.

I this case a message is not sent at all or is highly delayed.
This is how my code looks like.
<code>const subscriptions = new Map<string, Subscription>();
const topics = new Map<string, Topic>();

const listenForMessages = async (
  subscriptionName: string,
  func: ListenerCallback,
  secInit = 300,
  secInter = 300
) => {
  let logger = new TestLogger("LISTEN_FOR_MSG");
  let init = true;
  const _setTimeout = () => {
    let timer = setTimeout(() => {
      console.log(`Subscription to ${subscriptionName} cancelled`);
      subscription.removeListener("message", messageHandler);
    }, (init ? secInit : secInter) * 1000);
    init = false;
    return timer;
  };

  const messageHandler = async (msg: Message) => {
    msg.ack();
    await func(JSON.parse(msg.data.toString()));
    // wait for next message
    timeout = _setTimeout();
  };

  let subscription: Subscription;

  if (subscriptions.has(subscriptionName)) {
    subscription = subscriptions.get(subscriptionName);
  } else {
    subscription = pubSubClient.subscription(subscriptionName);
    subscriptions.set(subscriptionName, subscription);
  }

  let timeout = _setTimeout();

  subscription.on("message", messageHandler);
  console.log(`Listening for messages: ${subscriptionName}`);
};

const publishMessage = async (
  data: WithAnyProps,
  topicName: string,
  options?: PubOpt
) => {
  const serializedData = JSON.stringify(data);
  const dataBuffer = Buffer.from(serializedData);
  try {
    let topic: Topic;
    if (topics.has(topicName)) {
      topic = topics.get(topicName);
    } else {
      topic = pubSubClient.topic(topicName, {
        batching: {
          maxMessages: options?.batchingMaxMessages,
          maxMilliseconds: options?.batchingMaxMilliseconds,
        },
      });
      topics.set(topicName, topic);
    }
    let msg = {
      data: dataBuffer,
      attributes: options.attributes,
    };

    await topic.publishMessage(msg);
    console.log(`Publishing to ${topicName}`);
  } catch (err) {
    console.error(`Received error while publishing: ${err.message}`);
  }
};
</code>
A listenerForMessage function is triggered by an HTTP request.
What I have already checked

PubSub client is created only once outside the function.
Topics and Subscriptions are reused.
I made at least one instance of each container running to eliminate the possibility of delays triggered by cold start.
I tried to increase the CPU and Memory capacity of containers.
batchingMaxMessages and batchingMaxMilliseconds are set to 1
I checked that the latest version of @google-cloud/pubsub is installed.

Notes

High latency problem occurs only in the cloud environment. With local tests, everything works well.
Timeout error sometimes occurs in both environments.
Comment: Can you share how you run your code? Your webserver and the overall logic.
Comment: @guillaumeblaquiere, I'm not sure I got your question exactly, but I'll try to provide you with relevant information.
All the code is running in Node.js on fully managed Cloud Run containers.

I have a service, let's call it PipelineService, containing information about existing data pipelines: source and destination types, connection ids, the status of the pipeline (active/paused), last data transfer date, etc. I also have multiple services, let's say FacebookService, etc., containing holding information about source connection, access tokens, etc.
Comment: @guillaumeblaquiere, There are also a GBQService holding google access tokens and addresses of destination tables.

Once a day a Cloud Scheduler invokes a PipelineService. In turn, PipelineService wakes up source and destination services and activates a PubSub listener. They start to perform some warm-up operations and to listen for PubSub messages containing instructions about the time frame and addresses of data to retrieve. After the data is retrieved, it's sent via messages to  GBQService, which in turn uploads data to Google BigQuery.
Comment: @guillaumeblaquiere, if at any given point the process fails and can't be automatically recovered, the message about the failure reason is sent back to the PipelineService and saved into the database. Otherwise, success confirmation is sent.  Each service removes a listener after a certain time without new messages and shuts down.
Comment: Ok, excuse my lack of precision: I would like to know what is the piece of code that invoke the message publish part. With Cloud Run you must have a webserver. An endpoint should be invoked on it, and, in that endpoint, your publish function call. I would like to understand that chain of call.
Answer: The problem was in my understanding of Cloud Run Container's lifecycle. I used to send HTTP response 202 while having PubSub working in the background. After sending the response, the container switched to the idling state, what looked like high latency in my logs.

Cloud Run PubSub high latency


ngMock not injecting factory

Question: I have been stuck on this problem for the past 24 hrs and cannot see what is wrong with my code here. I am getting an injector error from Angular and cannot understand why. Here is my code:
<code>(function (){
  'use strict';
  angular.module('Test', []).factory('stats', factory);

  function factory() {
    return {
      dummy: 'Dummy Text'
    };
  }
})

describe('Test', function() {
  var stats;
  beforeEach(module('Test'));

  beforeEach(inject(function(_stats_) {
    stats = _stats_;
  }));

  it('Should be defined', function() {
    expect(stats).toBeDefined();
  })
})
</code>
I have checked my karma.conf.js file and all the files needed are being included in the test. I have another service that belongs to the same module and when I try to inject it instead of 'test' it works as expected.
Any help on this would be greatly appreciated.
Answer: You're defining a function, which defines a Test module and adds a service stats, but you never call that function.
The code should be:
<code>(function (){
  ...
})();
</code>
Note the additional pair of parentheses used to call the function.
Comment: Thank you so much. I did not know the trailing parentheses were required; I thought those were only for extending classes on the file.

ngMock not injecting factory


Estimate daily network IO between 2 servers

Question: I have 2 servers : a database server (SQL Server 2008, called server A) and an application server (called server B) which send SQL queries to the first one.
They are actually in the same LAN, but we planned to separate them in 2 different geographical sites.
I try to estimate the minimum bandwidth required between the 2 servers, so that my application doesn't suffer from performance issues.
How can I estimate the amount data that are exchanged between the two servers ?
I'd like to have, for example : for day xx/xx/xxxx, there was approximately 1.5 GB of data send from A to B and 750 MB from B to A.
Is there a diagnostic tool on SQL Server to measure that ? Or just a network tool ?
I have no access to any physical hardware device, but I'm admin of both servers.
Thanks.
Comment: Why are you putting the app and SQL servers in different locations? You usually want to keep them close, for this sort of reason. You might want to leave them where they are and add a light-weight third tier, like a web app that talks to the existing app server, or a new TS/Citrix server near the existing servers.
Comment: You're doing it wrong.
Comment: @hobodave - me, or JYL?
Comment: @mfinni: The OP. Comments by default notify only the OP. In the absence of an @mfinni, assume I'm not directing it to you.
Comment: @hobodave - Just checking :-)
Comment: @all : I totally agree with you. Separate them is a REALLY bad decision. This decision is a decision from my managers. I'm trying to prove them that they're wrong. But I need metrics for that !
Comment: JYL - the biggest problem isn't necessarily bandwidth, although it might be the second-biggest problem. Lag, and how your application handles it, will probably be the biggest problem. Ask your developers if they think the app can handle WAN-introduced lag. Or if it's a 3rd-party product, ask them if they support putting the SQL server across a link with average lag of however-may milliseconds. Then go to management with that info.
Comment: You probably speak about latency... you're right. I finally think that the best and fastest prof will be a real test on site...
Comment: @mfinni and all: thank you for taking time to answer and guide me !
Answer: If you don't have access to the switch, you can use a network analysis tool like Microsoft Netmon or Wireshark. There are probably easier tools to just measure data throughput, but since I am comfortable with Wireshark I usally use it. I would set up a capture on the relevant network interface using this capture filter on the SQL Server:
<code>host 10.10.10.10 and port 1433
</code>
Replace ip adress of server B's actual ip adress, change the port if it is not a default instance, uncheck 'promiscuous mode' and start the capture, and then view the size captured in Statistics->Summary.
I agree with the other posters that it might not be a good idea to split the servers, depending on the architecture of the application. A slight increase in response time between the servers could degrade the performance a lot, especially if there are many sequential SQL queries. That is also something you can observe in your Wireshark capture (but might be easier in SQL Profiler).
Comment: Thanks for your post. Wireshark usually keep in memory the captured packets. Am I wrong ? Is there an option to prevent this and just store stats ? Otherwise it will probably exlode just 10 minutes after it started...
Comment: @JYL Yes, by default it captures to memory, but if I do a longer capture of several gigabytes I set it to capture to files of a few hundred megabytes each in the 'multiple files'-dialog, I have never tried importing files of more than around 1 GB. If you expect that your application consumes more than a few GB a day I would probably find another tool.
Comment: The network card status shows an average of 14GB sent in a day... perhaps too much for Wireshark.
Comment: Seems to be the nearest answer for the question. Measure on a short delay (2 hours for ex.) can give a idea of the total amount of the day... Thanks.
Comment: FYI : Wireshark has been running for 1 hour, generating a 2.5 GB file. Loading the captured file crashed after 20 min, I had a "Visual C++ Runtime Error"... I split it with "editcap" and after I was able to analyze some small periods of 10 min.
Answer: You would want to enable netflow on the switchports the two servers are connected to and analyze that flow.
Comment: Ok. Thanks for your post. I don't know netflow. Can you confirm that I don't need access on any network physical device ? (like switch...)
Comment: No, you most definitely need access to the network devices to enable netflow, and you need a server running the appropriate software to act as a collector.
Answer: You could run Perfmon and capture bytes sent/received/sec; you'd have to capture to a file to aggregate the data, but it will show you your peaks. It will include all traffic, not just SQL.
Comment: And it would show all traffic, not only that between these two hosts, right? If so, not a good answer for the question.
Comment: Thanks for your post, all traffic will be Ok. But won't perfmon explode if I keep it running for hours ?
Comment: Didn't found the appropriate counters...
Comment: Should be under Performance Object: Network Interface, then make sure you select the right instance, there will be one for each nic.
Comment: like I said, this will show *all* traffic on those NICs, between all hosts. If the SQL server get a big update via WSUS ,that will show up in these graphs. This methodology will not show what @JYL is asking for, and if management knows that, they will demolish what might be a good argument.


obtain parity check matrix in different ways

Question: We have the code words 111000, 100110, 110101 which result in the following generator matrix.
$G=\begin{bmatrix}1&1&1&0&0&0\\1&0&0&1&1&0 \\ 1&1&0&1&0&1\end{bmatrix}$
According to my book, the rows of the control matrix are solution vectors of the system of equations whose rows are formed by the base of the given code, i.e.
\begin{eqnarray}
y_1 + y_2 + y_3 = 0\\
y_1 + y_4 + y_5      = 0 \\
y_1 + y_2 + y_4 + y_6 = 0 \\
\end{eqnarray}
If we choose $y_1$, $y_2$ und $y_4$ as free variables, we get the rows of the following matrix as the basis of the solution space:
$H=\begin{bmatrix}1&0&1&0&1&1\\0&1&1&0&0&1 \\ 0&0&0&1&1&1\end{bmatrix}$
where columns 1, 2 and 4 are the identity matrix.

Why are the colums 1, 2 and 4 the identity matrix?
How did he use the generator matrix to obtain the parity check matrix?
Why did he choose $y_1$, $y_2$ und $y_4$ and what does this mean?

I thought the way to get the parity check matrix is the following:
If the generator matrix is in the form $G = [I_k | P]$, then its parity check matrix is $H = [P^T | I_{n-k}]$
So we swap columns 1&3, 2&5 and 3&6
$G'=\begin{bmatrix}1&0&0&0&1&1\\0&1&0&1&0&1 \\ 0&0&1&1&1&1\end{bmatrix}$
$H'=\begin{bmatrix}0&1&1&1&0&0\\1&0&1&0&1&0 \\ 1&1&1&0&0&1\end{bmatrix}$
Then we permutate it back (3&6, 2&5 and 1&3) and obtain:
$H= \begin{bmatrix}0&0&0&1&1&1\\0&1&1&0&0&1 \\ 1&0&1&0&1&1\end{bmatrix}$
Does it matter in which order the identity matrix appears?
Answer: Having the generator matrix in systematic form, that is $G=[I_k|P]$, has of course the advantage as stated, which is the easy construction of the parity check matrix $H=[P^T|I_{n-k}]$.
Consider any word $x$ as a row vector, then the syndrome $s=Hx^T=0$ if and only if $x$ is a codeword of the given linear code. Since $H$ is a $(n-k)\times n$ matrix, $x^T$ is a $n \times 1$ vector. It is easy to see, that swapping rows does not have any effect, but swapping columns changes the code, since bit positions are permuted.
Consider the valid codeword $100011$ (first row of $G'$). Using $H$ to check: $H\cdot \begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \\ 1 \\1\end{pmatrix}=\begin{pmatrix} 0 \\ 1 \\ 1\end{pmatrix}$, hence the syndrome is not equal to the zero vector. However, performing the same for $H'$ yields to $H'\cdot \begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \\ 1 \\ 1\end{pmatrix}=\begin{pmatrix} 0 \\ 0 \\ 0\end{pmatrix}$ as intended.


Shewing that a group is elementarily equivalent to a torsion group

Question: Suppose that every nonempty definable (without parameters) subset of the group $G$ contains an element of finite order.
Must $G$ be elementary equivalent to a countable torsion group?
My first idea is to take the set of definable elements of finite order but the product of two finite order elements need not be of finite order.
Comment: Regarding your attempt: Actually, for your group $G$, the product of any two finite order definable elements *does* have finite order! This is because if $a$ is definable, then $\{a\}$ is a definable set, and hence $a$ has finite order. So the set of definable elements is equal to the set of definable elements with finite order, and since the product of two definable elements is definable, this set is a subgroup. The problem is that there's no reason to expect this subgroup to be elementarily equivalent to $G$.
Comment: For example, $(\mathbb{Z}/2\mathbb{Z})^\omega$ is a torsion group, so it satisfies your hypotheses, but the only definable element is $e$, since any two non-identity element of this group are conjugate by an automorphism.
Comment: You could try to get around this problem (that the definable elements don't necessarily form an elementary substructure) by Skolemizing your theory. But adding Skolem functions adds new definable sets, and you might lose your hypothesis about definable sets containing elements of finite order. Thus, you would have to be careful to make sure that the Skolem functions always output elements of finite order. These sorts of careful choices are exactly what's accomplished by the Henkin construction proof of omitting types, and you're essentially led to the strategy in my answer after all.
Answer: This is a nice application of the omitting types theorem.
Let $\varphi_n(x)$ be the formula $x^n = e$ (where of course $x^n$ is an abbreviation for the $n$-fold product of $x$). Let $\Sigma(x) = \{\lnot \varphi_n(x)\mid n\in \omega\}$. An element satisfies the partial type $\Sigma(x)$ if and only if it has infinite order. So we seek a countable model of $\text{Th}(G)$ in which no element satisfies $\Sigma(x)$.
By the omitting types theorem, such a model exists as long as there is no formula $\psi(x)$ such that $\text{Th}(G)\models \exists x\, \psi(x)$ and $\text{Th}(G)\models \forall x\, \psi(x)\rightarrow \lnot\varphi_n(x)$ for all $n\in \omega$. This is exactly the hypothesis you're given: no nonempty definable subset of $G$ contains only elements of infinite order.
Comment: Nice! +1. ${}{}{}{}$


How to know which script or executable is linked with a metric in ganglia?

Question: I have just started to explore ganglia and my question is "How to know which script or executable is linked with a metric in ganglia?"
The fact is that I don't know much about ganglia. I have good experience in zabbix and I want to link a graph in zabbix which is already working in ganglia.
I have browsed a lot on the Internet but none of the answers was relevant.
Suppose, the metric is:
"hbase.RegionServerDynamicStatistics.tbl.SUBSCRIBER.cf.M_T_V"
Beneath this, 2 graphs are shown as "hbase.RegionServerDynamicStatistics.tbl.SUBSCRIBER.cf.M_T_V.get__avg_time"
and
"hbase.RegionServerDynamicStatistics.tbl.SUBSCRIBER.cf.M_T_V.get__num_ops"
As far as I understand, this metric is not inbuilt. Correct me if I am wrong.
There must be some script or executable collecting these values.
So, please help me to find the script?
I have also tried to find such metrics in the configuration files, such as, /etc/ganglia/gmond.conf and /etc/ganglia/gmetad.conf files, but not any such entry was there.
I read somewhere that some custom metric command line could be formed based on gmetric. And that could be attached in cron job, which would send data to the ganglia server periodically. If this is the way it happens then is there any way to find the gmetric based command line formed to do so?
Answer: Ok, I got the answer of this question. This could be helpful for others too.
Actually, hadoop has a class named as GangliaContext31.java which emits all hadoop related metrics to the ganglia server based on the IP or FQDN of the ganglia server, provided in the configuration file of hadoop known as hadoop-metrics2.properties.
A short excerpt of this configuration file is shown as:
namenode.sink.ganglia.class=org.apache.hadoop.metrics2.sink.ganglia.GangliaSink31
namenode.sink.ganglia.period=10
namenode.sink.ganglia.servers=ganglia-server:8649

Here ganglia-server is the said FQDN.
gmond daemon installed on ganglia-server collects these metrics and forward them to gmetad daemon installed on the ganlia-server. gmetad daemon stores these metrics in the rrdtool . In this way, graphs are built based on these values stored in the rrdtool.


Convert Html to XML

Question: My assignment is to convert an html file to XML format. I'm working with C#/.NET. Any suggestions? Thanks heaps
Comment: HTML -> XML? HTML basically already is XML isn't it?
Comment: HTML isn't always (hardly ever?) well formed, hence why #Johan is probably trying to convert to XHTML
Comment: Do you mean convert it to XHTML? Or some other XML format? Either way, did you try Googling - why couldn't you use an answer you found on Google?
Answer: I would try using the Html Agility Pack to parse the Html. This would allow me to build either an object graph that I could output as Xml or I could use the parsed Html to output the Xml directly.
Alternatively, if you have full control of the Html and know it is XHtml compliant, you could do a simple XSL-transform on the Html to get the Xml you want. But is most cases you cannot do this.
Answer: Try SgmlReader, I personally used it couple of times and the results are impressive.
You can add it to your project as a NuGet package as well.
Answer: try this:
http://www.w3.org/TR/xhtml1/#diffs
Answer:
The Post
Google Link
Hope this helped..
Answer: I ran into a situation where I was writing out xml via Response.Write(...); with c#.  I simply needed to convert the html to an xml file.  I was able convert the file using the following:
Response.ContentType = "text/xml";
Hope this helps someone.

Convert Html to XML


Every integer is congruent to the sum of its digits mod 9

Question: This is a question from the free Harvard online abstract algebra lectures.  I'm posting my solutions here to get some feedback on them.  For a fuller explanation, see this post.
This problem is from assignment 6.  The notes from this lecture can be found here.

Prove that every integer $a$ is congruent to the sum of its decimal digits modulo 9.

Let $s$ be an $(n+1)$-digit integer given by $s=a_n\cdot10^n+\dots+a_2\cdot10^2+a_1\cdot10^1+a_0\cdot10^0$ with $a_i\in\mathbb{Z}$ such that $0\leq a_i\leq9$.  Then
$
\begin{align}
s\,\mathrm{mod}\,9&=\bar{s}\\
&=\overline{a_n\cdot10^n+\cdots+a_2\cdot10^2+a_1\cdot10^1+a_0\cdot10^0}\\
&=\overline{a_n\cdot10^n}+\overline{\cdots}+\overline{a_2\cdot10^2}+\overline{a_1\cdot10^1}+\overline{a_0\cdot10^0}\\
&=\overline{\overline{a_n}\cdot\overline{10^n}}+\overline{\cdots}+\overline{\overline{a_2}\cdot\overline{10^2}}+\overline{\overline{a_1}\cdot\overline{10^1}}+\overline{\overline{a_0}\cdot\overline{10^0}}\\
&=\overline{\overline{a_n}\cdot1}+\overline{\cdots}+\overline{\overline{a_2}\cdot1}+\overline{\overline{a_1}\cdot1}+\overline{\overline{a_0}\cdot1}\\
&=\overline{a_n}+\overline{\cdots}+\overline{a_2}+\overline{a_1}+\overline{a_0}\\
&=a_n\,\mathrm{mod}\,9+\cdots+a_2\,\mathrm{mod}\,9+a_1\,\mathrm{mod}\,9+a_0\,\mathrm{mod}\,9
\end{align}
$
Again, I welcome any critique of my reasoning and/or my style as well as alternative solutions to the problem.
Thanks.
Comment: Reasoning is sound, although you should point out somewhere that $\overline{10^n}=\overline{10}^n=\overline{1}^n=\overline{1}$. Also, it looks weird to have $\overline{\cdots}$, just $\cdots$ suffices. And if you aren't going to distinguish between the regular + and its modular version then you need to carry that really long \overline through until the last line.
Comment: I second @AlexBecker's comments.
Answer: Just another way.
Clearly $9\vert (10-1)$. Suppose that $9\vert (10^n - 1)$, $n\gt 1$. Then
$$10^{n+1}-1 =10\cdot 10^{n}-1=9\cdot 10^n + (10^n - 1)$$
thus $9\vert (10^{n+1}-1)$. Therefore $9\vert (10^n-1)$ for any $n\in\mathbb{N}$.
Now take an integer
$$a=\sum_{i=0}^n a_i10^{i},$$
where $a_i\in \{0,1,\ldots,9\}$. Then
$$a-\sum_{i=0}^na_i=\sum_{i=0}^n a_i10^{i}-\sum_{i=0}^na_i=\sum_{i=1}^n a_i(10^{i}-1),$$
therefore, by the established above
$$a\equiv \sum_{i=0}^na_i \pmod 9$$
Comment: This is an elegant proof I must say!
Answer: Your suggestion works if you are satisfied $\overline{a_n\cdot10^n} \equiv \overline{\overline{a_n}\cdot\overline{10^n}} \equiv \overline{\overline{a_n}\cdot1} \equiv \overline{a_n} \mod 9$, which is indeed true.
Another way is
$$\begin{align}
s&={a_n\cdot10^n+\cdots+a_2\cdot10^2+a_1\cdot10^1+a_0\cdot10^0}\\
&={a_n\cdot 99\ldots99+\cdots+a_2\cdot 99+a_1\cdot 9 +a_0\cdot 0 }+\sum_{i=0}^n a_i\\
&=9({a_n\cdot 11\ldots11+\cdots+a_2\cdot 11+a_1\cdot 1 +a_0\cdot 0 )}+\sum_{i=0}^n a_i
\end{align}$$
so $s \equiv \sum_{i=0}^n a_i \mod 9.$
Answer: HINT $\rm\ mod\ 9\!:\ 10\:\equiv\: 1\ \Rightarrow\ f(10)\:\equiv\: f(1)\ $ for all polynomials $\rm\:f(x)\:$ with integer coefficients.
The above applies to radix notation since it clearly has polynomial form in the radix.
Alternatively put $\rm\ x\: =\: 10\ $ in $\rm\ x-1\ |\ f(x)-f(1)\ $ by the Factor Theorem.
Answer: I write this answer in keeping with my comment:
You need to prove that $\overline {ab}=\overline{\bar a\bar b}$. There are many ways of looking at this, for instance see, Benjamin Lim's answer, here. I shall write a number theoretic proof here:
Suppose $\bar k$ denotes the remainder obtained when $k$ is divided by$q$, we have, $a=b_1q+\bar a; b=b_2q+\bar b$ . So, you have $$ab=(b_1b_2q+b_1\bar b+b_2\bar a)q+\bar a \bar b$$ and this proves that, $\overline{ab}=\overline{\bar a \bar b}$.
Further, on the same line, you'll need to prove for the sum and the fact that $10^n \cong 1 (mod~~9)$
There are very minor gaps which you can still fill as a beginner, as others have pointed out.
Sorry for the late edits!!
Answer: $n \equiv \sum\limits_{k=1}^{\lceil log_{10} n\rceil} 10^{k-1} d_{k} \;(mod \; 9) \quad$  (Here $n = d_{\lceil log_{10} n\rceil}\ldots d_2 d_1$, being decimal representation of $n$)
$\equiv \sum\limits_{k=1}^{\lceil log_{10} n\rceil} (9+1)^{k-1} d_{k} \; (mod \; 9)$
$\equiv \sum\limits_{k=1}^{\lceil log_{10} n\rceil} d_k \; (mod \; 9), \quad$ by binomial expansion.


Nuget misbehaving with newtonsoft.json package

Question: Why Nuget producing an error when I install a package after Newtonsoft.Json v11.0.2 is installed. Whenever I try to install another package I get the following error
Install-Package : An error occurred while retrieving package metadata for 'Newtonsoft.Json.11.0.2'
from source 'C:\Users\yusuf\Documents\Visual Studio 2015\Projects\Eman\packages'.
At line:1 char:1
+ Install-Package MaterialDesignThemes
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.
   InstallPackageCommand

Whenever i remove the line with the Newtonsoft.json package defined in packages.config the package installs successfully. Is it something wrong with json package itself or is it my package manager that's messed up, anyway can someone show me how i can fix this.
P.S. This happens with whichever package i try to install while json package is already installed.
EDIT I tried deleting the package line in packages.config and also deleting the downloaded package files and reinstalled the package several times, i keep getting the same problem
Comment: https://stackoverflow.com/questions/33617584/nuget-retrieving-package-metadata
Comment: I tried  that solution several times, didn't work @torsan
Comment: @SF1Dev has a very good answer for this issue, please refer. https://stackoverflow.com/a/45225236/5448364
Answer: First, downgrade Newtonsoft.Json v11.0.2 to Newtonsoft.Json v6.0.4. Second, install another nuget package.
If the package successfully installs, upgrade Newtonsoft.Json v6.0.4 back to Newtonsoft.Json v11.0.2.


Real and Imaginary

Question: $$Re\Big(({\frac{1+i\sqrt{3}}{1-i})^4\Big)} = 2$$
$$Im\Big(({\frac{1+i}{1-i})^5\Big)} = 1$$
I got that $Re\Big(({\frac{1+i\sqrt{3}}{1-i})^4\Big)} = 1 \ne 2$
And, that $\Big(({\frac{1+i}{1-i})^5\Big)} = i $ , which means that $Im\Big(({\frac{1+i}{1-i})^5\Big)} = 1$
Can you guys confirm that it's true? Thanks in advance!
In this image I got to$(\frac{1−\sqrt3+i+i\sqrt3}{2})^4$ and then, I'm not sure how to continue.
Comment: @IlanAizelmanWS, it is considered improper here to repost your question just because you didn't like the outcome the first time.  You should edit your first question, and wait.
Comment: Oh no! Nobody posted an answer for two whole hours, so you posted the question again? How inconsiderate of us... :|
Comment: $r\mathrm{e}^{i\theta}  = r\left[\cos\theta +i\sin\theta\right]$ and compare terms.
Comment: Because no1 helped me, I opened a new one.
Comment: @Chinny84 I can't do that. you can't find the angle and you can't find the r
Comment: Yes you can, you can use $r=0.5$ and you should be able to determine an expression for $\tan \theta$  In terms of the real and imaginary component of the term in the bracket. I apologise that I didn't explain that we are using only the terms in the bracket, for which we can then raise to the 4th power.
Comment: For the question number 2
\begin{align}
\text{Im}\left(\frac{1+i}{1-i}\right)^5&=\text{Im}\left(\frac{1+i}{1-i}\cdot \frac{1+i}{1+i}\right)^5\\
&=\text{Im}\left(\frac{(1+i)^2}{1^2-i^2}\right)^5\\
&=\text{Im}\left(\frac{1+2i+i^2}{2}\right)^5\\
&=\text{Im}\left(\frac{2i}{2}\right)^5\\
\end{align}
Comment: I managed to get to that @V-Moy, as you can see in the image that I've added in my post. but I couldn't get to 2 in the first question.
Comment: @AsafKaragila: to be fair, he posted the duplicate to meta and it was migrated here >8( I didn't know about the previous post before I came up for air after answering.
Comment: It's easy Sir. I'll give you a hint:
$$
1+\sqrt{3}i=2e^{\Large\frac{\pi}{3}i}
$$
and
$$
1-i=\sqrt{2}e^{-\Large\frac{\pi}{4}i}
$$
It's not difficult to find the $\text{abs}(z)$ and $\arg(z)$. Check Wiki. I hope this helps you. (ô‿ô)
Comment: Mr. @robjohn, for me it's not fair since I can't post my answer. (╥﹏╥)
Comment: Still didn't get it.
Comment: How did u go from $ 1 + \sqrt3*i =$ to $2e^/sqrt pai/3*i$?
Comment: @IlanAizelmanWS Are you kidding me? How come you learn complex number without knowing that thing?? If $z=x+iy$, then it can also be written as:
$$
z=re^{i\theta}
$$
where $r=\text{abs}(z)=\sqrt{x^2+y^2}$ and $\theta=\arg(z)=\arctan\left(\cfrac{y}{x}\right)$. Check Wiki or you can google about complex number for more detail explanation.
Comment: @V-Moy: sorry about that. I answered before it was closed.
Comment: Mr. @robjohn: It's okay Sir. It's not your fault, no need to say sorry to me. ヅ
Comment: @robjohn you should either move your answer (and other's comment) to the other question and hard delete this question or reopen this and hard delete the other question.
Comment: @achillehui: I answered this question as how to compute $$\mathrm{Re}\left[\, \left(\frac{1-\sqrt3+i+i\sqrt3}2\right)^{\large4} \,\right]$$ I had not seen the original question (the one showing no work) before I answered this one, but nonetheless, to me, this is a different question than the other question, and my answer would not make sense as an answer to the original question.
Answer: Hint: Brute force works:
$$
\begin{align}
&\frac1{16}\mathrm{Re}\left[((1-\sqrt3)+i(1+\sqrt3))^4\right]\tag{1}\\
&=\frac1{16}\left(\color{#C00000}{(1-\sqrt3)^4}-\color{#00A000}{6(1-\sqrt3)^2(1+\sqrt3)^2}+\color{#C00000}{(1+\sqrt3)^4}\right)\tag{2}\\
&=\frac1{16}\left(\color{#C00000}{2(1+6\cdot3+9)}-\color{#00A000}{6(-2)^2}\right)\tag{3}\\[6pt]
&=2\tag{4}
\end{align}
$$
where we have used the binomial theorem a few times
$$
(x+y)^4=x^4+4x^3y+6x^2y^2+4xy^3+y^4\tag{5}
$$
Explanation:
$(1)$: copy problem
$(2)$: expand using $(5)$ and drop the terms with an $i$
$(3)$: expand the red terms using $(5)$ and drop the odd exponents ($-\sqrt3$ will cancel $+\sqrt3$)
$(3)$: also use that $(1-\sqrt3)(1+\sqrt3)=1-3=-2$
$(4)$: arithmetic
Comment: How did u get $\frac{1}{16}$? Actually, didn't understand anything. Feeling stupid.
Comment: @IlanAizelmanWS Sir, it's $2^4$ in the denominator. (─‿‿─)
Comment: @IlanAizelmanWS: I have added some explanation that may help.
Comment: How did u get (1)?
Comment: Whats what I did: [link](https://scontent-a-cdg.xx.fbcdn.net/hphotos-prn2/t1.0-9/10155946_459428150826874_6969747818414687259_n.jpg)
Comment: @IlanAizelmanWS: I copied $(1)$ from the point where you said you got $\left(\frac{1−\sqrt3+i+i\sqrt3}{2}\right)^4$ but didn't know how to proceed.
Comment: Well,l you go way far @robjohn. But thx!

Real and Imaginary