text:
Q: Reload Image without Reloading Page? I'm doing this as a learning exercise and I'm still a beginner to PHP. I know even less about javascript:
The script that I'm writing should allow a user to upload an image from their hard drive, allow the user to modify it by way of some controls on the page and then display the modified image.
Currently, I'm only using PHP to do this and it requires the user to set the parameters of the controls and then POST them (requiring a complete page reload). Can someone point me in the direction of a better way to do this? Is there anything like this out there that I could take a look at?
It would be great if I could eventually have the image update in real time as a user slides a control. Am I looking for javascript? AJAX?
Here is a basic version of my code:
<?php session_start(); ?>

        <?php
            if(isset($_SESSION['Modified'])){ // Image has been modified at least once (display modified image. do not display upload form)
                echo("
");
            }elseif(isset($_FILES['file_upload']['name'])) { // Image has been uploaded but not yet modified (do not display upload form)
                echo("
");
            } else { // FIRST State that the form is in when the page is loaded. (No image uploaded so display upload form)
                echo("<form action='index.php' enctype='multipart/form-data' method='POST'>
                    <input type='file' name='file_upload' />
                    <input type='submit' name='upload_submit' value='Upload' />
                </form>");
            }

            echo("<form action='index.php' method='post'>
");  // display form with 4 slider controls (Red, Green, Blue, Alpha) and a submit button
                echo("
");
                    echo (isset($_POST['colred'])) ? "
Red:	 0<input type='range' name='colred' min='0' max='255' value=" . $_POST['colred'] . ">255
"
                        :"
Red:	 0<input type='range' name='colred' min='0' max='255'>255
";
                    echo (isset($_POST['colgreen'])) ? "
Green:	 0<input type='range' name='colgreen' min='0' max='255' value=" . $_POST['colgreen'] . ">255
"
                        : "
Green:	 0<input type='range' name='colgreen' min='0' max='255'>255
";
                    echo (isset($_POST['colblue'])) ? "
Blue:	 0<input type='range' name='colblue' min='0' max='255' value=" . $_POST['colblue'] . ">255
"
                        : "
Blue:	 0<input type='range' name='colblue' min='0' max='255'>255
";
                    echo (isset($_POST['colalpha'])) ? "
Alpha:	 0<input type='range' name='colalpha' min='0' max='255' value=" . $_POST['colalpha'] . ">127
"
                        : "
Alpha:	 0<input type='range' name='colalpha' min='0' max='255' value='127'>255
";
                echo("
");
                echo("<button name='process_submit'>Process</button>");
            echo("</form>");
        ?>

A: Image reloading is not that complicated compared with the uploading process. Forgetting the uploading, you can use javascript to edit the 'src' attribute of an  element to make the image reload.
like:
document.getElementsByTagName("Image1")[0].setAttribute("src", "http://media-cache-ak0.pinimg.com/736x/63/50/59/635059d03e7f3a00219571c767b89c38.jpg");

A: You can probably do everything you want without all the PHP form controls.
HTML5 added a
<canvas></canvas>

element which you can put images to and manipulate image data directly with JavaScript. Then you can send that data in the background to PHP to save the image for storage or downloading or whatever.
See http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ for some examples of image filters written in javascript. You can also easily crop, rotate, scale, ect using javascript and canvas.
http://jsfiddle.net/av01d/FT7a9/


text:
Q: Change from base Shadocks to Base 10 in Python I have a little problem who block me, I've a work where I must to convert a number to Shadocks (base 4 it seems), and I must to make a decrypter.
So I made the first part, but my code won't work on the second.
Here it's :
def Base10toShadocks(n):
    q = n
    r = 0
    Base4=[]
    Shads=["GA","BU","ZO","MEU"]
    if q == 0:
        Base4.append(0)
    else:
         while q > 0:
             q = n//4
             r = n%4
             n = q
             Base4.append(r)
         Base4.reverse()
         VocShad = [Shads[i] for i in Base4]
    print(VocShad)
def ShadockstoBase10(n):
    l=len(n)
    Erc_finale=[]
    for i in range(l):
        Sh=(n[i])
        i=i+1
        if Sh =="a":
            Erc_finale.append(0)
        elif Sh =="b":
            Erc_finale.append(1)
        elif Sh =="o":
            Erc_finale.append(2)
        elif Sh =="e":
            Erc_finale.append(3)
     print(Erc_finale)
     F=str(Erc_finale)
     print(F)
     F=F.replace("[","")
     F=F.replace("]","")
     F=F.replace(",","")
     F=F.replace(" ","")
     L2=len(F)
     F=int(F)
     print(L2)
     print(F)
     r=0
     while f < 4 or F ==4:
        d=(F%4)-1
        F=F//4
        print(d)
        r=r+d*(4**i)
        print(r)

inp = 0
inp2 = 0
print("Tapez \"1\" pour choisir de traduire votre nombre en shadock, ou \"2\" pour inversement")
inp = int(input())
if inp == 1:
    print("Quel est le nombre ?")
    inp2 = int(input())
    if inp2 != None:
        Base10toShadocks(inp2)
elif inp == 2:
    print("Quel est le nombre ?")
    inp2 = str(input())
    if inp2 != None:
        ShadockstoBase10(inp2)

It blocks at the F=int(F), I don't understand why.
Thanks for your help.

A: First, some errors in your code:
for i in range(l):
    Sh=(n[i])
    i=i+1      #### Won't work. range() will override
    ##### Where do "a","b","o","e" come from
    ##### Shouldn't it be "G","B","Z","M" ("GA","BU","ZO","MEU")?
    if Sh =="a":
        Erc_finale.append(0)
    elif Sh =="b":
        Erc_finale.append(1)
    elif Sh =="o":
        Erc_finale.append(2)
    elif Sh =="e":
        Erc_finale.append(3)
 print(Erc_finale)
 F=str(Erc_finale)    ### Not how you join an array into a string

Here's a corrected way:
def ShadockstoBase10(n):
    n = n.upper();    # Convert string to upper case
    l = len(n)
    Erc_finale = ""   # Using a string instead of an array to avoid conversion later
    i = 0
    while i < l:      # while loop so we can modify i in the loop
        Sh = n[i:i+2] # Get next 2 chars
        i += 2        # Skip 2nd char
        if Sh == "GA":
            Erc_finale += "0"
        elif Sh == "BU":
            Erc_finale += "1"
        elif Sh == "ZO":
            Erc_finale += "2"
        elif Sh =="ME" and "U" == n[i]:
            Erc_finale += "3"
            i += 1;      # MEU is 3 chars
        else:
            break;       # bad char
    return int(Erc_finale, 4)  # Let Python do the heavy work

Like everything in Python, there are other ways to do this. I just tried to keep my code similar to yours.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the series: $\frac{-1}{4}+\left(\frac12+\frac14+\frac28+\frac3{16}+\frac5{32}+\cdots\right)$ Find the series: $$\frac{-1}{4}+\left(\frac12+\frac14+\frac28+\frac3{16}+\frac5{32}+\cdots\right)$$
Evidently, this is a Fibonacci Sequence with a Geometric Sequence.
But I don't think there is a formula for the sum of Fibonacci Sequence..
Also, I have heard about Binet's formula, but we can't use these formulas. We just have to use elementary, basic things like $S_n-\frac12S_n$ and all. I tried:
$$S_n=\left(\frac12+\frac14+\frac18+\cdots\right)+\left(\frac18+\frac2{16}+\cdots\right)$$
$$S_n=1+\left(\frac18+\frac2{16}+\cdots\right)$$
I keep on repeating that, but what happens is that the Fibonacci Sequence gets shifted till infinity. So what to do please tell?

A: $$S=\frac{F_1}{2^1}+\frac{F_2}{2^2}+\cdots$$
We want to use the property $F_n+F_{n+1}=F_{n+2}$. Add the sum to itself in such a way that you can use a common denominator:
$$S+\frac{S}{2}=\frac{F_1}{2^1}+\frac{F_1+F_2}{2^2}+\frac{F_2+F_3}{2^3}+\cdots$$
$$\frac{3}{2}S=\frac{F_1}{2}+\underbrace{\frac{F_3}{2^2}+\frac{F_4}{2^3}+\cdots}_{2(S-F_1/2-F_2/4)}$$
Recognize a part of the original sum (with two missing terms and a factor of 2):
$$\frac{3}{2}S=\frac{F_1}{2}+2\left(S-\frac{F_1}{2}-\frac{F_2}{4}\right)$$
Just express $S$, given $F_1=F_2=1$.
$$\frac32S-2S=\frac{1}2-1-\frac12$$
$$\frac{S}{2}=1$$
$$S=2$$
Now your required series will be $$2-\frac14=\frac74$$

A: Let $F_n$ denote the $n^{th}$ Fibonacci number.  So we have the recursion:
$$F_n=F_{n-1}+F_{n-2}\;\;\;F_0=1=F_1$$
Define a power series $$F(x)=\sum F_n\,x^n=1+x +2x^2+3x^3+5x^4+...$$
We want a simple expression for $F(x)$.  But use the recursion and match coefficients of $x^n$...we have $$F(x)=xF(x)+x^2F(x)+1\;\;\Rightarrow\;\;F(x)=\frac{1}{1-x-x^2}$$
Note:  Check this! Easy to drop a term.
Now compare $F(\frac 12)$ to your desired sum.

A: You have the generating function of the Fibonacci sequence:
$$
F_{n + 2} = F_{n + 1} + F_n \qquad F_0 = 0, F_1 = 1
$$
$\begin{align}
F(z)
  &= \sum_{n \ge 0} F_n z^n \\
  &= \frac{z}{1 - z - z^2}
\end{align}$
This series converges for $\lvert z \rvert < (\sqrt{5} - 1)/2 \approx 0.618$.
Your sum is essentially $F(1/2)$.


text:
Q: Would like to have app access from a timed trigger function For the Sample Code below would like to be able to set the label 'statMsg' to a different value(time or a counter or a status) once every minute. But do not have 'app' access from testTrigger():
//Trigger every minute
function createTriggerInvite() {
  ScriptApp.newTrigger('testTrigger')
      .timeBased()
      .everyMinutes(1)
      .create();
}
function testTrigger(){
  //NOT WORKING
  var app=UiApp.getActiveApplication();
  app.getElementById('statMsg').setText('Time');
  return app;
}

function doGet(e) {
  var dbgtime=true;
  dbgtime=false;
  //var dbg=true;
  createTriggerInvite();
  if (dbg==true)log('doget','Starting');
  var app = UiApp.createApplication();
  var stat=app.createLabel('Status...').setWidth(50)
           .setStyleAttribute('color', 'white')
           .setHorizontalAlignment(UiApp.HorizontalAlignment.LEFT)
           .setId('statMsg'));
  app.add(stat);
  return app;
}

A: UiApp widgets can't be updated by anything else than events happening in the UiApp instance, not by triggers or other external app.
There is a way to achieve auto update in UiApp but it uses a different approach.
The idea is to change the state of a widget that will fire an event handler. The timing will be defined in a sleep call.
Here is an example (already published here, the OP explains better the reason I used this) that uses a checkBox to initiate the event that calls the server handler :
function doGet() {
  var app = UiApp.createApplication().setTitle('Counter/Timer');
  var Panel = app.createAbsolutePanel().setStyleAttribute('padding','35');
  var counter = app.createHTML().setId('counter').setHTML('Timer = wait').setStyleAttribute('fontSize','40px');// set start display
  var clo = app.createTextBox().setName('clo').setId('clo').setValue('0').setVisible(false);//set start value in seconds
  var handler1 = app.createServerHandler('doSomething').addCallbackElement(Panel);
  var chk1 = app.createCheckBox('test1').addValueChangeHandler(handler1).setVisible(true).setId('chk1').setVisible(false);
  app.add(Panel.add(chk1).add(counter).add(clo));
  chk1.setValue(true,true);// start the process
  return app}

function doSomething(e) {
  var app = UiApp.getActiveApplication();
  var xx = Number(e.parameter.clo);
  var disp = app.getElementById('counter')
  xx++ ;// replace by xx-- to count downwards
  if(xx>600){ // 10 minutes timeout for example
  disp.setHTML(' GAME OVER ;-)').setStyleAttribute('fontSize','80px').setStyleAttribute('color','RED')
  return app
  }
  var cnt = app.getElementById('clo').setValue(xx)
  disp.setHTML(''+T(xx)+'')
  Utilities.sleep(1000); // instead of sleeping do something !
// below comes the "active" part
  var chk1 = app.getElementById('chk1').setValue(false,false)
  var chk1 = app.getElementById('chk1').setValue(true,true)
  return app;
}

function T(val){
  var min = parseInt(val/60);
  var sec = val-(60*min);
  if(sec<10){sec='0'+sec}
  if(min<10){min='0'+min}
  var st = '>  '+min+':'+sec
  return st
}

demo online here


text:
Q: Satellite Collision Problem I'm stuck on a problem of two satellites going towards each other. The mass of the first satellite is 400kg and the mass of the second satellite is 100kg. The altitude of the satellites is 1000km. I want to know if once the satellites collide, will they continue in orbit or will they crash and burn into the Earth?
I know that you can get the velocity of each satellite by using this equation:
$$v = \sqrt{GM/R}$$
Where $v$ is the velocity, $G$ is $6.67\cdot 10^{-11}$, $M$ is the mass of the planet, and $R$ is the radius.
I can get the velocities, but i don't know where to go from here. Also when I get $R$, do I also have to add the radius of the planet as well? so it would be 1000km + radius of planet?
If you guys would help me with this, it would be amazing.

A: Unless I'm missing an easy way to do this problem it seems a surprisingly hard one. This diagram shows the problem (I've exaggerated the altitude of the satellite to make the diagram clearer):

The satellites are in circular orbits (dotted line) at a distance $r$ from the centre of the Earth, so their orbital velocity as (as you say):
$$ v = \sqrt{\frac{GM}{r}} $$
Assuming the two satellites stick to each other when they collide you end up with a single 500kg mass of twisted metal moving at some velocity $v'$ that is less than $v$. The new orbit will be an ellipse, and the question is whether the new orbit intersects the Earth's surface. If the new orbit does not intersect the Earth then the fused satellites will continue to orbit, while if the new orbit does intersect the Earth obviously the debris will crash into the Earth.
The first step is to calculate v', and this is done simply by conservation of momentum. At the moment before the collision the momentum of the 400kg satellite is $400v$ and the momentum of the 100kg satellite is $-100v$ (I'm taking velocity positive to the right). After the collision the momentum of the wreckage is $500v'$, so:
$$ 400v - 100v = 500 v' $$
and we get:
$$ v' = \frac{3}{5}v \tag{1} $$
The hard bit is working out the new orbit. For this you need to start with the vis viva equation, and with some head scratching you can work out the equation for the perigee distance ($r_p$ in the diagram):
$$ r_p = \frac{r_a}{\frac{2GM}{v'^2r_a} - 1} $$
The question is then simply whether $r_p$ is less than the radius of the Earth.
You know $v'$ from equation (1), and $r_a$ is just the initial orbital radius (measured from the centre of the Earth). I'll leave it up to you you calculate $r_p$ and answer the question.

A: Introducing a side issue to this question:
Using $v$ for the orbital velocity at $1000$ km altitude, the total kinetic energy of the two satellites just before the collision is $$KE_{\text{Before}}=\frac12400v^2+\frac12100v^2=250v^2$$and using the final velocity of John Rennie above, the total kinetic energy of the combined satellites just after the collision is :$$KE_{\text{After}}=\frac12500\left(\frac35v\right)^2=90v^2$$The $160 v^2$ joules of lost energy is distributed as heat over the $500 \text{ kg}$ satellite.  Thus,   each kilogram will absorb $0.320v^2$ joules of energy.
The orbital velocity at an altitude of $1000\text{ km}$ above the surface of the earth is $7.35\text{ km/sec}$, so each kilogram of combined satellite will need to absorb 17.27 Mega joules of energy.
If we assume that the two satellites are made of aluminum, this implies a temperature increase of around $19, 000 \text{ Kelvin}$.  Even if we assume that the two satellites have the same high specific heat as water, we get a temperature increase of over $4, 100 \text{ Kelvin}$

A: We have to make a few assumptions here, because your question as posed is a bit incomplete.
1) collision is inelastic
2) satellites don't disintegrate on collision (see user58220's interesting observation)
3) there is no atmosphere (so drag is not an issue - let's see if the satellites end up in an orbit above the planet's surface)
4) you said "crash into the earth" so I assume R = 6400 km. The value of R does matter
After the collision, the combined velocity of the two satellites (with initial velocity $v$) will be given by conservation of momentum:
$$(m_1 + m_2) v_{final} = m_1 v_{initial} - m_2 v_{initial}\\
v_{final} = v_{initial}\frac{300}{500}$$
You now have satellites at the apogee of an elliptical orbit, and they will approach the earth until their closest point, the perigee. Let us say that the radial distance at apogee was $R+h_a$, and at perigee $R + h_p$.
From orbital mechanics we know there is a relationship between the semimajor axis of the orbit and the orbital energy:
$$-\frac{\mu}{2a}=\epsilon\tag1$$
We know the orbital energy decreased by the collision: the kinetic energy before was
$$KE=\frac12(m_1 + m_2)v^2$$
and afterwards it is
$$KE = \frac12\left(\frac{3}{5}\right)^2(m_1 + m_2)v^2$$
In circular orbit, the kinetic energy is equal to minus half the potential energy; after the collision, the potential energy is unchanged (at the instant of collision) while the kinetic energy was decreased.  So
$$\begin{align}\epsilon_{before}&=\frac{v^2}{2}-\frac{\mu}{r}\\
&= KE_{before} - 2 KE_{before}\\
&= -KE_{before}\end{align}\tag2$$
The kinetic energy afterwards is $\frac{9}{25}^{th}$ of the kinetic energy before, so we can write
$$\begin{align}\\
\epsilon_{after} &= (\frac{9}{25}-2)KE_{before}\\
&= -\frac{41}{25}KE_{before}\\
\end{align}\tag3$$
Combining equations (1), (2) and (3) gets me the ratio of the major axes:
$$\begin{align}\\
\frac{a_{before}}{a_{after}}&=\frac{\epsilon_{after}}{\epsilon_{before}}\\
&=\frac{25}{41}\\
\end{align}$$
For the circular orbit we can say that $a=2r_a$, while for the elliptical orbit it is $r_a+r_p$. So now we have
$$\frac{2r_a}{r_a+r_p}=\frac{41}{25}$$
With a bit of rearranging this gives
$$r_p = \frac{9}{41}r_a$$
So when the radius of the earth is about 6400 km, and you are orbiting 1000 km above the surface, you will surely crash. The largest planet on which this collision would not result in termination of the orbit has a radius of
$$r_{max}=9\frac{1000}{32}=281 km$$
My advice - don't let them collide...

A: I can only assume that the satellites are assumed to meet head-on (rather than at an angle), and that the collision is modeled as inelastic (rather than an explosive collision where pieces fly everywhere).
If so, you have the velocity of each and the mass of each.  You can use the conservation of momentum to find the new velocity of the combined-mass object at what will be apogee.
Are you familiar with the vis-viva equation?  You can then use that to find other specific points in the orbit.  There will be one other point in the orbit that you will want to find.
R will always be from the center of the earth.  However you do need to consider the radius of the earth's surface.  Do you know why?

A: So after a bit of research, i came up with this answer.
As i had said before we know that in orbit, the mass of the satellites does not matter to find the velocity. so if we use:
$$v = \sqrt{GM/R}$$
as M being the mass of earth i can find the final velocity of both satellites after collation.
$$Vf = (m2v2 - m1v1)/ (m1 + m2) $$
I came up with 4407.87 m/s
If i take this final velocity back to the first equation, and try to get r, i can compare with the ra and if r is smaller, it means it will crash on earth.
$$ r = GM / Vf^2$$
So i find r to be 4527 m
according to this, it will definitely will crash to the earth. because the original ra was 7378.1 km
Am i right to assume this?


text:
Q: Actual difference between organization owner and organization administrator in Liferay I am new to liferay and I am exploring User Roles.
I have created an organization and 2 users are associated with it say user1 and user2. User1 is organization owner and user2 is organization administrator.
Now my question is what is the actual difference between organization owner and organization administrator? What are the tasks that an owner can do and admin can't?

A: 1) A Site/Organization Administrator cannot delete the membership of any other Administrator or Owner.
2) A Site/Organization Administrator cannot remove the Site/Organization Administrator or Owner role of other administrators/owners.
3) A Site/Organization Owner can delete the membership or remove the roles from any other administrator or owner.
From this link


text:
Q: How prove this algebraically? Let $a,b,x,y$ be nonnegative integers.  By way of using generating functions, prove that
$$
\begin{pmatrix}
x+b \\
a
\end{pmatrix}
\begin{pmatrix}
y+a \\
b\\
\end{pmatrix}
 = \sum_{i=0}^{\min\{a,b\}}
\begin{pmatrix}
x+y+i \\
i\\
\end{pmatrix}
\begin{pmatrix}
y \\
b-i\\
\end{pmatrix}
\begin{pmatrix}
x \\
a-i\\
\end{pmatrix}\,.
$$

A:
This is a starter. We show OPs claim in the special case:
  \begin{align*}
x&=a\\
y&=b
\end{align*}
The following is valid for $a,b\geq 0$
  \begin{align*}
\sum_{i=0}^{\min\{a,b\}}\binom{a+b+i}{i}\binom{a}{i}\binom{b}{i}=\binom{a+b}{a}\binom{a+b}{b}\tag{1}
\end{align*}

We show the validity by successively using two aspects:

*

*Vandermonde's identity
\begin{align*}
\sum_{j\geq 0}\binom{m}{j}\binom{n}{r-j}=\binom{m+n}{r}\qquad\qquad m,n,r\geq 0
\end{align*}
to separate $m$ and $n$ and

*the identity
\begin{align*}
\binom{n}{k}\binom{k}{r}=\binom{n}{r}\binom{n-r}{n-k}\qquad\qquad\quad n,k,r \geq 0
\end{align*}
since this shuffling reduces the number of occurrences of $k$.

We obtain
  \begin{align*}
\sum_{i\geq 0}&\binom{a+b+i}{a+b}\binom{a}{i}\binom{b}{i}\tag{2}\\
&=\sum_{i\geq 0}\sum_{j\geq 0}\binom{a+b}{a+b-j}\binom{i}{j}\binom{a}{i}\binom{b}{i}\tag{3}\\
&=\sum_{i\geq 0}\sum_{j\geq 0}\binom{a+b}{a+b-j}\binom{a}{j}\binom{a-j}{a-i}\binom{b}{i}\tag{4}\\
&=\sum_{j\geq 0}\binom{a+b-j}{a}\binom{a+b}{a+b-j}\binom{a}{j}\tag{5}\\
&=\binom{a+b}{a}\sum_{j\geq 0}\binom{b}{j}\binom{a}{j}\tag{6}\\
&=\binom{a+b}{a}\binom{a+b}{b}\tag{7}\\
\end{align*}
  and the claim (1) follows.

Comment:

*

*In (2) we simplify things by adding zeros by reindexing ($i\geq 0$)

*In (3) we apply Vandermonde's identity to $\binom{a+b+i}{a+b}$

*In (4) we apply shuffling to $\binom{a}{i}\binom{i}{j}$

*In (5) we apply Vandermonde's identity to $\sum_{i\geq 0}\binom{a-j}{a-i}\binom{b}{i}$

*In (6) we apply shuffling to $\binom{a+b}{a+b-j}\binom{a+b-j}{a}$

*In (7) we apply Vandermonde's identity to $\sum_{j\geq 0}\binom{b}{b-j}\binom{a}{j}$


text:
Q: Correct way of redirecting IP Address in .htaccess I am using shared hosting and was told that I can access my website with my IP address and username like this:
http://12.34.56.789/~username

I would like to redirect this URL for SEO purposes. I found the redirect IP Address code (below) in a tutorial. Is the RewriteCond below correct?
Should the RewriteCond use 12.34.56.789/~username
instead of only 12\.34\.56\.789 ?
If the below is incorrect, can you show me the correct code as I am a beginner with htaccess stuff.
#Redirect IP Address
RewriteCond %{HTTP_HOST} ^12\.34\.56\.789$
RewriteRule ^(.*)$ http://www.domainname.com/$1 [L,R=301]

A: Try:
RewriteCond %{HTTP_HOST} ^12\.34\.56\.789$
RewriteRule ^~username/(.*)$ http://www.domainname.com/$1 [L,R=301]

The condition is correct, the "HTTP_HOST" is the hostname part (no paths) of the URL, so everything after the :// and before the next /


text:
Q: Difference in UITableViewCell willMoveToSuperview: behavior between iOS 5 and iOS 6 Under iOS 5, it seemed that a UITableViewCell subclass's willMoveToSuperview: method was called every time the cell was used or reused, but under iOS 6, it seems that it's only called when the cell is initially created and used, not when a cell gets reused.  Can anyone verify this difference?  Is this a bug?
What method should I be using to do cell setup inside the UITableViewCell subclass that will get called when the cell is reused in both iOS 5 and iOS 6?

A: I've been having the same issue with UICollectionView. It seems you have to implement the method prepareForReuse in the view you are using for display (ex. of type UITableViewCell or a UICollectionViewCell). However, this also gets called even if it is the first time creating a cell (not just when it is being reused) if you are using the new dequeueReusableCellWithReuseIdentifier:forIndexPath: with a registered class with registerClass:forCellWithReuseIdentifier: in iOS6.
Reference: UITableViewCell Class - prepareForReuse

A: 1. How to know if a cell is removed from tableview?
use this method to do something, e.g. cleanup, stop timers or something else...
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

2. how to know if a cell is going to be displayed

*

*(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;

3. how to know if a cell is going to reuse
override this method
UITableViewCell:
 - (void)prepareForReuse();


text:
Q: checked="checked" not rendering as checked radio button in Chrome If I insert some html via js after the doc.ready than checked='checked' radio button doesn't render as checked in Google Chrome
also, I noticed that if I remove the name attribute from the input than it works
here is the whole thing:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"
type="text/javascript"></script>
</head>
<body>

<script type='text/javascript'>
$(function(){
$('body').append('<input type="radio" checked="checked" value="33" name="whatever" id="aeHobby0">');

});
</script>
</body>
</html>

A: It would appear to be a bug in 1.4.4 (live copy). It works fine in 1.6.2 (live copy). Looks like it was fixed between 1.5.2 and 1.6.0 (at least in my tests), which suggests it was probably fixed by the patch that fixed bugs 8060 and 8500.


text:
Q: C++: Convert hex representation of UTF16 char into decimal (like python's int(hex_data, 16)) I found an explanation to decode hex-representations into decimal but only by using Qt:
How to get decimal value of a unicode character in c++
As I am not using Qt and cout << (int)c  does not work (Edit: it actually does work if you use it properly..!):
How to do the following:
I got the hex representation of two chars which were transmitted over some socket (Just figured out how to get the hex repr finally!..) and both combined yield following utf16-representation:
char c = u"\0b7f"

This shall be converted into it's utf16 decimal value of 2943!
(see it at utf-table http://www.fileformat.info/info/unicode/char/0b7f/index.htm)
This should be absolut elementary stuff, but as a designated Python developer compelled to use C++ for a project I am hanging this issue for hours....

A: Use a wider character type (char is only 8 bits, you need at least 16), and also the correct format for UTC literals. This works (live demo):
#include <iostream>

int main()
{
    char16_t c = u'\u0b7f';

    std::cout << (int)c << std::endl;  //output is 2943 as expected

    return 0;
}


text:
Q: Dependency Resolution Exception I am doing Unit Testing  In my Project.When I try to unit test my method a browser pops up and suddenly gets stopped after that I get a long exception I pasted following.
How to fix this mess as I have no idea whats the cause?
Exception:
https://paste.ubuntu.com/24389202/
BrowseHost Class
 public static class BrowserHost
    {
        public static readonly SelenoHost Instance = new SelenoHost();
        public static readonly String RootUrl;
         static BrowserHost()
        {
            Instance.Run("BankingSite", 1468);
            RootUrl= Instance.Application.Browser.Url;
        }
    }

UnitTest Class
namespace BankingSite.FunctionalUITests
{
    [TestFixture]
    public class LoanApplicationTest
    {
        [Test]
        public void ShouldAcceptLoanApplication()
        {
            BrowserHost.Instance
                .Application.Browser
                .Navigate()
                .GoToUrl($@"{BrowserHost.RootUrl}\LoanApplication\Apply");

            var firstNameBox = BrowserHost.Instance.Application
                .Browser
                .FindElement(By.Id("FirstName"));
            firstNameBox.SendKeys("Gentry");

            var lastNameBox = BrowserHost.Instance.
                Application.
                Browser.
                FindElement(By.Id("LastName"));
            lastNameBox.SendKeys("Smith");

            var ageBox = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id("Age"));
            ageBox.SendKeys("40");

            var incomeBox = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id("AnnualIncome"));
            incomeBox.SendKeys("9999999");
            Thread.Sleep(10000);

            var applyButton = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id("Applt"));

            applyButton.Click();
            Thread.Sleep(10000);

            var acceptMessageText = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id("acceptMessage"));

            Assert.That(acceptMessageText, Is.EqualTo("Congratulations Gentry - Your Application was accepted!"));
            Thread.Sleep(10000);

        }
    }

Following is the Screen Shot of URL I am browsing directly.

A: Hard to tell from what you've provided, but there is a clue in the stack trace:

System.TypeInitializationException : The type initializer for 'BankingSite.FunctionalUITests.BrowserHost' threw an exception.
    ----> Autofac.Core.DependencyResolutionException : An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Not a Number (See inner exception for details.)
    ----> System.InvalidOperationException : Not a Number

Check the constructor for BankingSite.FunctionalUITests.BrowserHost and see if you can find the line that is causing the error.  Apparently it is expecting a numeric value but received something else instead.


text:
Q: OCaml - Reverse a list I'm trying to implement my own list module as follows :
type 'a my_list =
    | Item of ('a * 'a my_list)
    | Empty

I've already implemented several functions and am now trying to create a list reversing function for my module which would look like this :
let rec rev = function
    | Empty             -> (*return reversed list*)
    | Item(i, remnant)  -> (*recursive call to rev*)

Moreover, I'm not supposed to use list operators such as '::', '[]' and '@'.
Edit, what I tried :
let rec rev_append l1 l2 = match l1 with
    | Empty             -> l2
    | Item(i, remnant)  -> rev_append remnant Item(i, l2)

let rev l = rev_append l Empty;;

But this is not working, there is an error at the second argument passed to the recursive call : "Item(i, l2)" The error is "The constructor Item expects 1 argument, but is here applied to 0 arguments".

A: Parenthesis man !
let rec rev_append l1 l2 = match l1 with
    | Empty             -> l2
    | Item(i, remnant)  -> rev_append remnant (Item (i, l2))

The compiler understood that rev_append was passed three argument namely remnant Item and (i, l2).


text:
Q: A live stream updating system like facebook i am really stuck on this one , i got the system to work , but it actually refreshes the whole update stream per second ,this is my ajax request ,
setInterval(function(){
          $.ajax({type:"GET",url:"read_new_post.php?account_id="+currentuser,success:function(response){

                            $(".new_update").html(response);
            }
        });
        },1000);

and this is my php script,imean that the echo part gets returned as response
if($i==0)
            {
                echo "

";
            }
        echo "

  ".$poster_details[0]["firstname"]." ".$poster_details[0]["lastname"]."

                    ".nl2br($posts[$i]["post_content"])."

10

                        SHARE

                         ".$posts[$i]["post_date"]."

                        <textarea name='your_comment' placeholder='Say Something'></textarea>

                        <input type='submit' value='Comment' id='comment_submit' />

";

my question is that is there any way i can just add the returned ajax data from the php page to the div "center",so that my update stream won't get refreshed ?

A: You should use WebSockets to fetch data dynamically. Making ajax requests every 1000ms is rather inefficient.  Here is a plugin which makes implementing WebSockets hassle free and it works with many environments php, nodejs, ruby etc:
http://socket.io/


text:
Q: datagrid mouse double click event wpf I have created an application using WPF. I have shown some data in the data grid. Currently, I have used selection changed event for getting the data from the data grid. I have following code
private void datagrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataGrid dg = sender as DataGrid;
            DataRowView dr = dg.SelectedItem as DataRowView;
            if (dr != null)
            {
                int id = Convert.ToInt32(dr["Id"].ToString());
           }
}

I need to get data only when the user doubles click on the data grid. how is it possible?

A: XAML:
<DataGrid MouseDown="datagrid1_MouseDown"></DataGrid>

Code behind:
private void datagrid1_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2)
    {
        DataGrid dg = sender as DataGrid;
        DataRowView dr = dg.SelectedItem as DataRowView;
        if (dr != null)
        {
            int id = Convert.ToInt32(dr["Id"].ToString());
        }
    }
}

P.S. You can use null propagation to make your code more robust:
var idStr = ((sender as DataGrid)?.SelectedItem as DataRowView)?["Id"]?.ToString();
if (idStr != null)
{
    int id = Convert.ToInt32(idStr);
}

A: In XAML:
<datagrid name="datagrid1" ... mousedoubleclick="datagrid1_MouseDoubleClick"></datagrid>

And use this code:
private void datagrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DataGrid dg = sender as DataGrid;

   if (dg!= null && dg.SelectedItems != null && dg.SelectedItems.Count == 1)
   {
       DataRowView dr = dg.SelectedItem as DataRowView;
       int id = Convert.ToInt32(dr["Id"].ToString());
   }
}

I hope it helps you.


text:
Q: zf2 doctrine 2 - Output OnetoOne Unidirectional After annotating an OneToOne Unidirectional, i want to output the joined column, without using a form.
One People Entity has got a column to store the id of Country Entity.
What i can do: I can store the id of the country into the People Entity using a form with a dropdown select, which is bound to the Country Entity.
Problem: I can not enter the value country of the, hopefully correct, joined table.
People Entity:
<?php
namespace People\Entity;

use Doctrine\ORM\Mapping as ORM;
// ...

/**
* A people entity.
*
* @ORM\Entity
* @ORM\Table(name="icd_people")
* @property int $id
// ...
* @property string $ic_hq_country
*/
class People implements InputFilterAwareInterface
{
protected $inputFilter;

/**
* @ORM\Id
* @ORM\Column(type="integer");
*/
protected $id;

/**
* @ORM\Column(type="integer")
* @ORM\OneToOne(targetEntity="Country")
* @ORM\JoinColumn(name="ic_hq_country", referencedColumnName="id")
*/
protected $ic_hq_country;

// getter and setter
}

The Country Entity:
<?php
namespace People\Entity;

use Doctrine\ORM\Mapping as ORM;
//...

/**
* A Country entity.
*
* @ORM\Entity
* @ORM\Table(name="pre_country")
* @property int $id
* @property string $country
*/
class Country implements InputFilterAwareInterface
{
protected $inputFilter;

 /**
 * @ORM\Id
 * @ORM\Column(type="integer");
 */
protected $id;

/**
* @ORM\Column(type="string")
*/
protected $country;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set country
 *
 * @param string $country
 * @return Country
 */
public function setCountry($country)
{
    $this->country = $country;

    return $this;
}

/**
 * Get country
 *
 * @return string
 */
public function getCountry()
{
    return $this->country;
}

/**
* Convert the object to an array.
*
* @return array
*/
public function getArrayCopy()
{
    return get_object_vars($this);
}

public function setInputFilter(InputFilterInterface $inputFilter)
{
    throw new \Exception("Not used");
}

public function getInputFilter()
{
    throw new \Exception("Not used");
}
}

The Controller Action:
public function indexAction()
{

    $userid =  $this->zfcUserAuthentication()->getIdentity()->getId();

     return new ViewModel(array(
        'pea' => $this->getEntityManager()->find('People\Entity\People', $userid),
));
}

The View giving the id of the country, but not the name:
<?php echo $this->escapeHtml($pea->ic_hq_country);?>
I actually expected something like this being possible, to output the country name and not the id:
<?php echo $this->escapeHtml($pea->country);?>
Thank you for reading, and for any help, which could lead me into the right direction!

A: You should not use the @Column anotation in the $ic_hq_country field of the Peopleentity.
/**
* @ORM\OneToOne(targetEntity="Country")
* @ORM\JoinColumn(name="ic_hq_country", referencedColumnName="id")
*/
protected $ic_hq_country;

like this, hopefully ic_hq_country will be a proxy to the entity instead of the id.
so in your view you can use:
<?php echo $pea->ic_hq_country->getId();?>

and also
<?php echo $this->escapeHtml($pea->ic_hq_country->getCountry());?>


text:
Q: club / closure points I have a question concerning set theory and I would really appreciate anyone's help.
Namely, I am supposed to show that if $C$ is club in $κ$, then there is a function
$f : κ → κ$ with $C_f ⊆ C$.
Here $C_f$ stands for the set of closure points of $f$, i.e.
$$C_f = \{α < κ | f[α] ⊆ α, α > 0\}.$$
And of course, for $κ$ I suppose that it is regular, uncountable cardinal.
Thanks in advance for all the possible hints.

A: HINT: Use the natural enumeration surjection $f:\kappa\to C$, so that $f(\alpha)<f(\beta)$ whenever $\alpha<\beta<\kappa$. You may find it helpful to show that $\alpha\le f(\alpha)$ for each $\alpha<\kappa$.


text:
Q: Django based marketplace, creating a transaction history I'm trying to create a transaction history for each transaction on a Django based marketplace.
I thought the best way of keeping track of this data was to override the save() function and create a Transaction record.
class Transaction(models.Model):
    item = models.ManyToManyField(Item, blank=True)
    buyer = models.ManyToManyField(User, related_name='buyer')
    seller = models.ManyToManyField(User, related_name='seller')
    description = models.CharField(max_length=500)
    purchase_date = models.DateField(auto_now_add=True)
    value = models.DecimalField(max_digits=7, decimal_places=2)
    def save(self, *args, **kwargs):
        self.buyer.money+=self.value
        self.seller.money-=self.value
        super(Transaction, self).save(*args, **kwargs)

Am I going about this all wrong? Currenlty I get...
'Transaction' instance needs to have a primary key value before a many-to-many relationship can be used.

A: *

*You have to save your object before you can go through many-to-many relationships.

*Please explain how you can have multiple buyers and sellers on a single transaction.  (For the rest of this answer, I'm assuming that there aren't and you meant for these to be ForeignKey fields.)

*The related names for buyer and seller are not clear.  See below.

*I'm not sure what description is for.  Is it different from the item list?

*item should be called items, since it can be plural, and you might want to create a custom junction table (using the "through" parameter) with a quantity field.

*You forgot to save the related objects.
Modified version:
class Transaction(models.Model):
    items = models.ManyToManyField(Item, through='TransactionItem', blank=True)
    buyer = models.ForeignKey(User, related_name='transactions_as_buyer')
    seller = models.ForeignKey(User, related_name='transactions_as_seller')
    description = models.CharField(max_length=500)
    purchase_date = models.DateField(auto_now_add=True)
    value = models.DecimalField(max_digits=7, decimal_places=2)

    def save(self, *args, **kwargs):
        super(Transaction, self).save(*args, **kwargs)
        self.buyer.money += self.value
        self.buyer.save()
        self.seller.money -= self.value
        self.seller.save()

class TransactionItem(models.Model):
    transaction = models.ForeignKey(Transaction)
    item = models.ForeignKey(Item)
    quantity = models.IntegerField()

A: The buyer and seller fields are many to many fields so self.buyer will never work, I think you were meaning to use ForeignKey instead of ManyToManyField.


text:
Q: Typescript issue with Next.js and getStaticProps I'm having an issue "typing" this implementation of getStaticProps.
As you notice the result can either return a null data return or something.
So, because of the typings in the getStaticProps, this is also getting messed up.
I tried conditional props, but not working for me, any ideas?
type ProductType = {
     props:
         | {
             product: null;
             page: string,
             status: number
          }
        | {
            product: Product;
          }
 }

function ProductPage(props: ProductType): Children  {
  const { product, status, page } = props; // errors here
  if (!product) {
    return (
      <ErrorPage statusCode={status} page={page}  />
    )
  }

  return (
    <ProductPage { ...props } />
  )
}

export default ProductPage;

interface StaticParams extends ParsedUrlQuery {
  id: string
}

type StaticProps = {
  props: {
      product: ProductType;
    }
}
// I get a very long error message here "StaticProps".
// Its like I can't do either "error" values or valid values.
export const getStaticProps: GetStaticProps<StaticProps, StaticParams> = async (context) => {
  const params = context.params!

  const response = await fetch(`${process.env.NEXT_PUBLIC_HOST}/products/${params.id}`);
  const product = await response.json();

  if (!product || product.errors) {
    return {
      props: {
        product: null,
        page: 'error page',
        status: 404
      }
    }
  }

  return {
    props: {
      product: { ...product },
    },
    revalidate: 10
  }
}

A: I think you confused yourself here by nesting your ProductType type inside your StaticProps type. As it is written, the full definition of your StaticProps type is:
type StaticProps = {
  props: {
    product: {
      props:
        | {
            product: null
            page: string
            status: number
          }
        | {
            product: Product
          }
    }
  }
}

To fix the compiler error, you need to change the first return statement in your getStaticProps function to be assignable to the type of StaticProps:
return {
  props: {
    product: {
      props: {
        product: null,
        page: 'error page',
        status: 404,
      },
    },
  },
}

While that may allow your code to at least compile, I suspect that you should actually change the definition for the StaticProps type. Also, you will need to make sure the response from your /products/{productId} endpoint also conforms to the StaticProps type to avoid runtime TypeErrors which typescript won't be able to save you from.


text:
Q: Sending XML Files via Flume (Using curl) I'm using Apache Flume to move data, I have set up an agent with an HTTP Source. I want this source to receive XML files, and these files will eventually be read by a sink which will push to Cassandra (My own sink). So i have added an HTTPSourceXMLHandler which handles xml files the way I want to.
I have the following configuration file:
# Name the components on this agent
a1.sources = r1
a1.sinks = k1
a1.channels = c1

# Describe/configure the source
a1.sources.r1.type = http
a1.sources.r1.bind = localhost
a1.sources.r1.port = 44444
a1.sources.r1.handler = org.apache.flume.source.http.HTTPSourceXMLHandler

# Describe the sink
a1.sinks.k1.type = file_roll
a1.sinks.k1.sink.directory = /home/admin/Desktop/XMLs
a1.sinks.k1.rollInterval = 5

# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100

# Bind the source and sink to the channel
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1

I have a source on localhost port 44444, a channel, and a file sink (for now, I just want Flume sink to save the xml in my local machine for performance testing).
When I use curl to send an example xml file (ex.xml), the operation succeeds, however the sink does not save it as a file on the specified location:
curl -X POST -d @ex.xml http://localhost:44444
Am I doing something wrong? The XMLHandler is working well and was tested.
Thanks.


text:
Q: Showing dates on HTML on option select I am working on an HTML file that has a drop-down list of months. When I select a month, I want the function to show the dates of the month on the page in this format:

1st of December 2020
2nd of December 2020
.
.
.
31st of December 2020

Below is my html:
I cannot get the function to execute on option select. Could you help me what is wrong with the script? I am no expert in javascript yet but I am continuously exploring and experimenting with HTML and javascript.
Please note that I will be add the codes for the other months when I get the function to execute for these two months.

var ord = "";
var i;
var fulldate;
var y = "";
var m = document.getElementById("month");
var mv = m.value;

function showdates() {
  if (mv == "December") {
    fulldate = "";
    y = "2020";
    for (i = 1; i < 32; i++) {
      if (i > 3 && i < 21) {
        ord = "th";
      } else if (i == 1 || i == 21 || i == 31) {
        ord = "st";
      } else if (i == 2 || i == 22) {
        ord = "nd";
      } else if (i == 3 || i == 23) {
        ord = "rd";
      } else {
        ord = "th";
      }
      fulldate += i + ord + " of " + mv + "" + y + "
";
    }
  } else if (mv == "January") {
    fulldate = "";
    y = "2021";
    for (i = 1; i < 32; i++) {
      if (i > 3 && i < 21) {
        ord = "th";
      } else if (i == 1 || i == 21 || i == 31) {
        ord = "st";
      } else if (i == 2 || i == 22) {
        ord = "nd";
      } else if (i == 3 || i == 23) {
        ord = "rd";
      } else {
        ord = "th";
      }
      fulldate += i + ord + " of " + mv + "" + y + "
";
    }
  }
  document.getElementById("dates").innerHTML = fulldate;
}
SELECT MONTH

<select id="month" name="month" oninput="showdates()">
  <option value="December">December</option>
  <option value="January">January</option>
</select>

A: var mv = m.value;

I think this line should be inside the showdates() function
function showdates(){
var mv = m.value;
...
...
}

A: *

*In your script you need to move the mv inside the function BUT

*Add "please select"

*DRY Do not repeat yourself

Here is a better script

const nth = d => {
  if (d > 3 && d < 21) return 'th';
  switch (d % 10) {
    case 1:  return "st";
    case 2:  return "nd";
    case 3:  return "rd";
    default: return "th";
  }
};

const showdates = function() {
  const mv = this.value;
  const monthName = this.options[this.selectedIndex].text;
  document.getElementById("dates").innerHTML = "";
  if (!mv) return; // stop
  const now = new Date()
  let yyyy = now.getFullYear();
  if (mv <= now.getMonth())  yyyy++; // next year
  const d = new Date(yyyy, mv - 1, 1, 15, 0, 0); // normalising at 15:00
  const lastDay = new Date(yyyy, mv, 0, 15, 0, 0, 0).getDate() // the 0th of next month
  fullDate = [];
  for (let i = 1; i <= lastDay; i++) {
    fullDate.push(i + nth(i) + " of " + monthName + " " + yyyy);
  }

  document.getElementById("dates").innerHTML = fullDate.join("
");
}
document.getElementById("month").addEventListener("change", showdates);
SELECT MONTH

<select id="month" name="month">
  <option value="">Please select</option>
  <option value="12">December</option>
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
</select>


text:
Q: Handling Exceptions in Python 3.6 I am trying to handle exceptions in Python 3.6. I want to handle every possible exception and print the exception. When i do
try:
    raise RuntimeError("Test")

except:
    e = sys.exc_info()[0]
    print(e)

it just prints

class '_mysql_exceptions.OperationalError'

How do i get the message of the Exception? In this case i would like the output to be "Test".

A: You can catch and print the Exception as follows:
try:
    raise RuntimeError("Test")
except Exception as e:
    print(e)
    # Test

I'm not quite sure why you're trying to catch every Exception though, it would seem more prudent to let Python handle and raise these for you in general. Normally you would only catch specific Exceptions.
This behavior is not specific to Python 3.6.


text:
Q: How to change the appearance of the file picker title on Android? I want to show a file picker to open an image using this code:
Intent intent = new Intent();

intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);

startActivityForResult(Intent.createChooser(intent, "choose from"), PICK_FROM_FILE);

How can I change the font and gravity of the file picker title ("choose from")?

A: This is what I found by digging in the Android source code:
createChooser creates an intent with an ACTION_CHOOSER action.
When you launch your intent, a ChooserActivity is created (not sure how exactly) which extends ResolverActivity. The layout applied to ResolverActivity is resolver_list or resolver_list_with_default. In there you can find the title in question.
So, no, it doesn't seem to be possible to change the appearance of the file picker title. But you could create your custom file chooser based on the original source code.

A: I dont think you can change the color/font/gravity of this chooser dialog as this is invoked/managed by system and not by your app, except the attributes like what title to show (talking specifically about chooser dialog).


text:
Q: Bootstrap Form-Group with Dropdown Problem Screen Shot ImageWith below code, an unwanted button is coming with default dropdownlist. please help me to remove this button.

Nationality

                            @Html.DropDownListFor(m => m.DESelectedNationality, Model.Nationalities, new { @class = "form-control" })

i expect dropdownlist with out button, but the actual result is dropdownlist with button. Screenshot attached.


text:
Q: why stat() does not show correct value of mtime? I have created simple testing function with a loop. It has a lot of echos because I want to know what exactly happens. Notice, there is a die command on the end of the loop, so it is not real loop. I call the function with test("523",$p);. This creates variable $fname = "523.txt" and $p may be set to 1; I found out that when I touch the file and set it some mtime, atime, values like 10, 1... the stat() does not return proper value. But if I remove the function (just the inner code stayes) so the stat() will return correct values 10 1; ... Any ideas what may went wrong in my function?
function test($n, $p){
  $fname = "$n.txt";
  echo "
$n at ".time()."
";
  for ($i = 0; $i<50; $i++ ){
    $start = microtime(true);

    $st = stat("$fname");
    echo "; 1) previous access by ".$st['mtime']." ".$st['atime']."; ";

    $fsize = filesize($fname);
    if ($fsize === 0)
     echo "! The fsize is 0; ";
    else
      {
      $fp = fopen($fname, "r");
      $locked = flock($fp, LOCK_SH);
       $s = fread($fp, $fsize );
       $success = flock($fp, LOCK_UN);
       if ( $success === false  )
         die("; r flock release failed; ");
       $success = fclose($fp);
       if ( $success === false  )
         die("; fclose failed; ");
       // 10 - data načtená , $p - prohlížeč
       if ( $success )
         {
         $result = touch("$fname",10,$p);
         echo "; TOUCH: $result;";
         }
       if ( strlen($s)<60 )
          echo "*$s LENGTH:".strlen($s)."
";
      }
    $st = stat("$fname");
    echo "; 2) previous access by ".$st['mtime']." ".$st['atime']."; ";
die;
  }
}

See the lines:
$result = touch("$fname",10,$p);

and
$st = stat("$fname");

Result ; 1) previous access by 1570715111 1570715111; ; TOUCH: 1;; 2) previous access by 1570715111 1570715111;

A: Quote from here: https://www.php.net/manual/en/function.stat.php
    Note: The results of this function are cached. See clearstatcache() for more details.

Just add clearstatcache(); before calling stat for the second time


text:
Q: Why can the .exe file under the Release folder be used to debug in VC++? I'm using Visual C++ 2010 to develop a Win32 application (without MFC). When I pressed F5 to debug my application, a new .exe file was produced under the Release folder rather than the Debug folder, because the project configuration in the current active solution configuration(which was Debug) was Release for some reason.
I was wondering why the .exe under Release folder, which seemed to be of a smaller size than the one under the Debug folder, could also be debugged.

A: Debug and Release are just a configuration names and a debugger knows nothing about which one is intended for debugging purposes right now.
Internally they are equal. The default property values is the only difference. You can easily swap them manually in order to debug optimized code, for example.

A: 1) In Debug mode there are no optimizations performed by the compiler, while in Release mode there are optimizations. In release mode compiler performs some low-level changes to the code ,so that some pieces of code gets modified to achieve optimization.
2)In debug mode we have few settings enabled by default with help in generation of  debug symbols and files related to it like Map file, PDB  etc .These files are essential in debugging a crash dump .


text:
Q: Cauchy-Riemann and Analytic Functions Using the Cauchy-Riemann conditions, tell if $f(z) = z^{*}$ is analytic
I have tried this:
$Z = x + iy$
$f(x + iy) = Z^{*} = x - iy$
$U(x,y) = x$
$V(x,y) = -y$
$U_x = 1$ Deriving respect to $x$
$V_x = 0$ Deriving respect to $x$
$U_y = 0$ Deriving respect to $y$
$V_y = -1$ Deriving respect to $y$
Then $U_x <> V_y$ and I suppose that $f(z) = z^{*}$ is not analytic.
But I'm not sure, I think I'm wrong. Could you help me, please?

A: We have that $V_y = -1$.  Since $U_x \not = V_y$, the Cauchy Riemann equations are not satisfied.


text:
Q: SimpleDateFormat not parsing date correctly I'm confused why the following input data is not parsed correctly by SimpleDateFormat.
I was trying to test various possible allowed date formats on a String to see if it would parse correctly with one of the formats.
Note: Other incorrect date formats that I've used report a parsing error.  That's what I expect to see.
What am I doing wrong?  Or, what can I do as a workaround?
String dformat = "MM-dd-yyyy";
String cDate = "2013-12-28";
SimpleDateFormat f = new SimpleDateFormat(dformat);
Date dd = f.parse(cDate);

The result is success.  And the date that is parsed is:

Date Fri Sep 12 00:00:00 PST 195

Well, the date should be December 28th, 2013.
In this case, I expected to see (like what I see for other invalid formats):
java.text.ParseException: Unparseable date: "2013-12-28"

A: You should really consider using the new java 8 version of java.util.Date which is java.time.LocalDate and java.time.LocalDateTime as part of the SDK.  These Date API's are considered more stable for exactly the reason you are having issues.  Here is one example.
String armisticeDate = "2013-12-28";

LocalDate aLD = LocalDate.parse(armisticeDate);
System.out.println("Date: " + aLD);

String armisticeDateTime = "2013-12-28T11:50";

LocalDateTime aLDT = LocalDateTime.parse(armisticeDateTime);
System.out.println("Date/Time: " + aLDT);

If you want to create a different format you can do the below.
String anotherDate = "04 Apr 2016";

DateTimeFormatter df = DateTimeFormatter.ofPattern("dd MMM yyyy");
LocalDate random = LocalDate.parse(anotherDate, df);

System.out.println(anotherDate + " parses as " + random);

For full documentation check out the Oracle page.
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

A: To get the error message:
java.text.ParseException: Unparseable date: "2013-12-28"

you need to call:
f.setLenient(false);

As the javadoc of parse(String source, ParsePosition pos) says:

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

A: You code should be like that:
  String dformat = "yyyy-MM-dd";
  String cDate = "2013-12-28";
  SimpleDateFormat f = new SimpleDateFormat(dformat);
  Date dd = f.parse(cDate);

The date format is wrong in your question.

A: Well the dformat do not meet the cDate format. So you have to give either cDate in dformat or you have to change the dformat in ""yyyy-MM-dd"

A: Your format pattern and date string does not much.
Change to:
String dformat = "yyyy-MM-dd";

A: Well, SimpleDateFormat is known to be a problematic and bugged class, with lots of strange behaviours.
What's probably happening is something similar to the issue described in this article. Considering your pattern and the input:
MM-dd-yyyy
2013-12-28

It's probably reading the month as "20", day as "3" and year as "-28"? (or some other value because I'm not sure how it interprets 2-28 as a 4-digit number). And the final result of this mess is a completely wrong, bizarre date - and don't ask me how it gets to the final result, it's a mistery to me.
Anyway, that can happen when the pattern doesn't match the input format, and the actual values that SimpleDateFormat reads will be something not so predictable and somewhat counter-intuitive. But what really matters is the fact that this class has lots of issues and design flaws, and it's lenient by default, so it tries to be "smart" and does lots of strange things before giving an error.
If you want to validate the input, just turn off the lenient mode, by calling f.setLenient(false) as Andreas suggested. This will throw an exception when the input doesn't match the pattern.
But if you're using Java 8, then you should use the java.time API, which is far superior and it solves lots of problems that SimpleDateFormat has.
To check if a string contains a date in a specific format, use a java.time.format.DateTimeFormatter. This class is not lenient by default as SimpleDateFormat, so it should work as expected:
// use the format "month-day-year"
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd-yyyy");
// try to parse a string in a different format (year-month-day)
LocalDate dt = LocalDate.parse("2013-12-28", fmt); // exception

The code above tries to create a LocalDate, a class that represents a date (only day, month and year). But if you want to just validate the input (without assigning it to any variable), you can just use the formatter:
fmt.parse("2013-12-28"); // exception


text:
Q: Installed j2cli and jinja2 with pip3 but can not find out how to run j2cli I installed on MacOS python, pip, upgraded it to pip3, then installed jinja2 and j2cli.
How should I run j2cli?
$ pip3 show jinja2
Name: Jinja2
Version: 2.11.2
Summary: A very fast and expressive template engine.
Home-page: https://palletsprojects.com/p/jinja/
Author: Armin Ronacher
Author-email: armin.ronacher@active-4.com
License: BSD-3-Clause
Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages
Requires: MarkupSafe
Required-by: j2cli

$ pip3 show j2cli
Name: j2cli
Version: 0.3.10
Summary: Command-line interface to Jinja2 for templating in shell scripts.
Home-page: https://github.com/kolypto/j2cli
Author: Mark Vartanyan
Author-email: kolypto@gmail.com
License: BSD
Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages
Requires: jinja2
Required-by:

A: Solution is NOT to install jinja2 prior to j2cli.
I did it because of excessive thinking: since j2cli is interface to the language jinja2, the latter should be installed first. It was wrong.
I uninstall them both with 'pip3 uninstall' command and then installed just j2cli
with 'pip3 install j2cli'. Immediately 'j2' command became available.


text:
Q: Cambiar valor de 'meta' en  css despues de onload tengo un problema.
Estoy tratando de usar carga CSS asincrona para optimizar mis elementos graficos.
En el <head> de mi html tengo varios links de .css (ejemplo:)
<link id="cs1" rel="stylesheet" href="css/ZooCss.css" media="none" onload="cambiarMedia()"/>

La función cambiarMedia() esta mas arriba de los links:
<script type="text/javascript">
    function cambiarMedia() {
        if (document.getElementById("cs1").getAttribute('media') === 'none') {
            document.getElementById("cs1").setAttribute('media', 'all');
        }
    }
</script>

Basicamente lo que quiero que haga es cambiar el valor de meta a all.
Los problemas con los que me choque:

*

*Asi como esta la funcion cambiarMedia Visual Studio me tira el siguente error:

'ASP.default_aspx' no contiene una definición de cambiarMedia ni se
   encontró ningún método de extensión cambiarMedia que acepte un
   primer argumento de tipo 'ASP.default_aspx' (¿falta una directiva
   using o una referencia de ensamblado?)

*Si llego a solucionar este error, también me gustaría transformar la función cambiarMedia para que sea reutilizable para todos los CSS's.
Para no volver a escribirla por cada ID del CSS.

Me pueden dar una mano con eso por favor?

A:

<link href="

window.addEventListener("DOMContentLoaded", c);
function c(){
 var css = Array.from(document.getElementsByTagName("link"));
 css.forEach(e => {e.media = "all";});
 console.log(document.getElementById("paraprobar").media); // probando que todos se hayan cambiado..
}
<link rel="stylesheet" href="" media="none"/>
<link rel="stylesheet" href="" media="none"/>
<link id="paraprobar" rel="stylesheet" href="" media="none"/>


text:
Q: Ubuntu 14.04: setting environment variables I need set environment variables for Android Studio project EVERY TIME when reboot or close terminal. (Ubuntu 14.04) For setting variables I use:
export KEYSTORE_NAME=/home/anna/Documents/keys/NAME.keystore
export KEYSTORE_NAME_PASSWORD=PASSWORD
export KEY_NAME_ALIAS=NAME
export KEY_NAME_PASSWORD=PASSWORD

How can I set there variables forever?

A: Add the exports to your ~/.profile, that way they are loaded on every login.
Relevant: https://help.ubuntu.com/community/EnvironmentVariables


text:
Q: How to retrieve GOPATH from Docker container? My objective is to have a self contained Go Workspace per project.
Is it possible to retrieve a Go workspace and Go environment variables from a running Docker container to be used by an IDE or Text Editor for development?
I have already tried mapping a volume to the container with the go tools and dependencies. But that requires always setting the GOPATH to the current workspace, and requires to have the go tools and dependencies on the host.

A: You can at least set and pass those environment variable when launching your container:
docker run -e "GOPATH=/a/mounted/path" -v [host-src:]container-dest --rm -it <yourImage>

By using -v, you allow your host to share a folder with your container.


text:
Q: What's the proper way to setup routes to get a model through another model? I have 2 models that I would like to setup routes for: Apps and Issues
Apps have many issues and each issue belongs to an App.
I want the URL to represent the fact that issues never come without its app. So something like this:
website.com/app-name/issues/2

But i'm not sure how to set that up properly in the routes. I also validate the uniqueness of app names, so I won't have any overlap issue.

A: try this
scope :app_name, :as => '' do
  resources :issues
end

then rake routes to see what methods generated

A: You'd like to use rails nested resources: http://guides.rubyonrails.org/routing.html#nested-resources
Basically:
resources :app do
  resources :issues
end

More info on customizing your route to cater to the app name here:
Routing nested resources in Rails 3


text:
Q: What's the largest universe we use? I know that the notion of a Grothendieck universe is used to deal with the fact that sometimes the categories of category theory are "too large". In general, how large of a universe is worked in?
If I say $U_1$ is the Grothendieck universe containing all the usual sets, and $U_2$ is the smallest universe containing $U_1$, and similar for general $U_n$, then how far up do we go?


text:
Q: Why is my sent email delayed 30 seconds? Why is my sent email delayed 30 seconds? Suspect DNS server.

A: Some email companies use to send emails in batches, so maybe every 5 minutes they send all emails, that were 'sent' in those last 5 minutes, or here 30 seconds.
But almost no one does that anymore
gmail was a way to undo send, if the feature is enabled, where it just waits, 3 to 30 seconds, before sending the email. In that time you can hit a cancel button if you realized you've made a mistake.
Whats the domain (@applemail.com or what?), the mail client your using, are you sending the email to yourself, and anything you can tell us about your setup that might be buggered.


text:
Q: how to write vertica trigger Am new to vertica. My need is to write a trigger to insert into the history table whenever table update occurs.
It is simply possible in MSSQL. like vise is my need and can any body suggest some direct links or details the steps am there is less time for me to investigate into and the searches didn't resulted productive.
Thanks

A: Vertica doesn't support triggers. This may seem strange if you're coming from another database platform, but the fact is Vertica was designed for analytical reporting applications, while triggers are more about transaction processing.
It is my impression that most Vertica users (including my company) process transactional updates to data in a more traditional Relation Database or other system and periodically batch-load Vertica with any updates. Any business rules or data validation requiring a trigger or other procedural logic should occur on this other, primary database system.

A: I think you should look into external UDF.
sky's the limit !

A: Vertica is  of no use if your requirement needs Analytical Functions creations. Its meant for acting as Front schema from where you can select and show faster then oracle and other DB's.


text:
Q: Stored procedure not giving the results of multiple out parameters I'm not good in writing stored procedures. Please help me on this. I use mysql workbench. I created stored procedure to get two outputs with two select statements. But it gives only the out put of one select statement which is written last in the stored procedure. Following is the procedure.
  CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`(IN date_x DATE,   OUT emplist3 varchar(200), OUT emplist4 varchar(200))
  BEGIN
  select employee.name as emplist3
  from employee
  where employee.id IN (
    select emp_position.employee_id
    from emp_position
    where emp_position.employee_id NOT IN (
       select emp_event.employee_id
       from emp_event
       where emp_event.date = date_x
    )
    AND emp_position.position = "Cameraman"
   );

  select employee.name as emplist4
  from employee
  where employee.id IN (
     select emp_position.employee_id
     from emp_position
     where emp_position.employee_id NOT IN (
        select emp_event.employee_id
        from emp_event
        where emp_event.date = date_x
     )
     AND emp_position.position = "Camera_Assistant"
     );
    END

Please help me to get the result of both emplist3 and emplist4 from the above procedure.
Thank U.

A: Adjust and modify the following example according to your need.
mysql> DELIMITER //

mysql> DROP PROCEDURE IF EXISTS `new_procedure`//
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`(
    ->   IN `date_x` DATE,
    ->   OUT `emplist3` VARCHAR(200),
    ->   OUT `emplist4` VARCHAR(200)
    -> )
    -> BEGIN
    ->   SELECT 'EMPLOYEE.NAME 1' INTO `emplist3`
    ->   FROM DUAL
    ->   WHERE `date_x` = `date_x`;
    ->
    ->   SELECT 'EMPLOYEE.NAME 2' INTO `emplist4`
    ->   FROM DUAL
    ->   WHERE `date_x` = `date_x`;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> SET @`NAME1` := NULL,
    ->     @`NAME2` := NULL;
Query OK, 0 rows affected (0.00 sec)

mysql> CALL `new_procedure`(DATE('2000-01-01'), @`NAME1`, @`NAME2`);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @`NAME1`, @`NAME2`;
+-----------------+-----------------+
| @`NAME1`        | @`NAME2`        |
+-----------------+-----------------+
| EMPLOYEE.NAME 1 | EMPLOYEE.NAME 2 |
+-----------------+-----------------+
1 row in set (0.00 sec)

A: You need to Select into the two parameters because that is what an out parameter is there for.
You also need to make sure that the return values are scalar,
You cannot return a whole resultset in an out parameter.
The main benefit to using output parameters is that you can do some manipulation to the data inside the procedure before returning it,
If you do not have any intention of doing that and/or you might return multiple rows then you cant really use out parameters.
Also you have not changed the delimiter in your code, you need to change the delimiter inside a stored procedure so MYSQL treats the whole procedure as a block of code.
try this:
DELIMITER //
CREATE PROCEDURE new_procedure(date_x DATE,OUT emplist3 varchar(200),
OUT emplist4 varchar(200)
)
BEGIN
      select employee.name INTO emplist3
      from employee
      where employee.id IN (
          select emp_position.employee_id
          from emp_position
          where emp_position.employee_id NOT IN (
              select emp_event.employee_id
              from emp_event
              where emp_event.date = date_x
          )
      AND emp_position.position = "Cameraman"
      );

     select employee.name INTO emplist4
     from employee
     where employee.id IN (
         select emp_position.employee_id
         from emp_position
         where emp_position.employee_id NOT IN (
             select emp_event.employee_id
             from emp_event
             where emp_event.date = date_x
         )
     AND emp_position.position = "Camera_Assistant"
     );
END //
DELIMITER ;

After creating the procedure you need to call a select statement on the parameters like so:
SELECT @emplist3,@emplist4;

Or if you are calling the procedure later:
CALL new_procedure(@myout1,@myout2);
SELECT @myout1,@myout2;


text:
Q: Equilibrium of simple SIS model I have a simple SIS model with a non-constant population size due to disease-related mortality:
\begin{aligned}
  \frac{dS}{dt} &= a I - b S I\\\\
  \frac{dI}{dt} &= b S I - a I - c I
\end{aligned}
where $S$ and $I$ are the susceptible and infected classes, $a$ is the rate of transition back to the susceptible class after being infected, $b$ is the per-capita transmission rate, and $c$ is the disease-related mortality for infecteds.
Finding the equilibria of this model is stumping me for some reason. First, I factor the second equation to get:
\begin{equation}
  I ( bS - a - c ) = 0
\end{equation}
so $\hat{I} = 0$ or $\hat{S} = \frac{a+c}{b}$ must be accord with $\dot{I} = 0$. The first means that:
\begin{equation}
  \dot{S} = a(0) - b S (0) = 0
\end{equation}
and so $\hat{S}$ must be its initial condition, $S_0$.
However, there is another equilibrium where the disease spreads and dies out, meaning $\hat{S} < S_0$, which I assumed is equal to $\hat{S} = \frac{a+c}{b}$.
However, using simultation in $R$, this equilibrium isn't correct - $\frac{a+c}{b}$ is still off by a fair amount.
Can anyone see where I'm going wrong? Thanks!

A: For $I=0$ you can have any value of $S$ to get an equilibrium position, the equilibrium equations do not impose further conditions on $S$. If you add the stability at $I=0$, then you have to add the condition $bS−a−c<0$. Outside that region the values for $I$ will increase.

If you divide both equations, you find that
$$
\frac{dS}{dI}=\frac{a-bS}{bS-a-c}
$$
is a separable equation, so that
$$
I+S-\frac{c}{b}\ln|bS-a|
$$
is a conserved quantity. That is, for the limit with $\hat I=0$ you get the equation
$$
\hat S-\frac{c}{b}\ln|b\hat S-a|=I_0+S_0-\frac{c}{b}\ln|bS_0-a|
\\~\\
e^{b\hat S-a}(b\hat S-a)=e^{b(I_0+S_0)-a}(bS_0-a)
\\~\\
\hat S=\frac1b\left(a+W_0(e^{b(I_0+S_0)-a}(bS_0-a))\right)
$$
for the limit value $\hat S$. The sign of $bS-a$ has to stay constant, $W_0$ is the Lambert-W function.
This only works for the simplest of models, more complex models will usually not give rise to conserved quantities/constants of motion.


text:
Q: NGINX in between load balance and Apache? I have recently joined the company where I see below stack to handle the http request

CDN ->  LVS(Load balancer) -> NGINX -> Apache

My question is about using advantage of NGINX b/w Load balancer and Apache. Folks who took this decision left and most of the team is new.
I read couple of articles on google where most says NGINX and apache are used together where NGINX can work for caching static content(but
we are using CDN here). Another reason is where NGINX can be used as Load balancer(but I see LVS is used for this).
So what are the other good reason to use Nginx in front of apache in general apart from caching and load balacing(reverse proxy) ?


text:
Q: An inequality of determinant $A_i \in M_n(\mathbb{R}), 1 \leq i \leq k, \ A_i A_j = A_j A_i, 1 \leq i,j \leq k$,
Prove that $$\det(\sum_{i=1}^k A_i^2) \geq 0$$
When $k=2$, let $\widetilde{A_2}=A_2 + \epsilon I $ s.t $ \widetilde{A_2}$ is invertible, then $ A_1 , \widetilde{A_2}$ can commute too.
So $ \det(A_1^2+\widetilde{A_2}^2) \geq 0 \Leftrightarrow \det((A_1 \widetilde{A_2}^{-1})^2+I) \geq 0 $.
So we only need to prove that $\det(A^2+I) \geq 0$.
Let $ \lambda_1,\lambda_2 \dots \lambda_n$ be the eigenvalues of $A$, then the eigenvalues of $A^2+1$ are $ \lambda_1^2+1,\lambda_2^2+1 \dots \lambda_n^2+1$. Since the product of conjugate eigenvalues are nonnegative and $\lambda_i^2+1 \geq 0, \ \lambda_i \in \mathbb{R}$, so it is true. Then let $\epsilon\to 0$ and we can get the conclusion.
But I don't know how to generalize it. I also know that $ A_i$ can be upper-diagonalized by the same matrice and have a idea that sees the $\det(A^2+I)$ as a function $f(t)=\det(A^2+tI)$, but I don't know how to continue. Thank you!


text:
Q: Why is equals slow in this Immutable JS test? I'm doing some sanity testing on a personal project before updating some state to use ImmutableJS. I have a small test I wrote to make sure that Immutable.List.equals performs like I expect it should -- O(1).
https://github.com/naddeoa/immutablejs-slow-equals.git
The important part is below
function compareImmutableMany(l1, l2) {
  let result = false;
  for (let i = 0; i < iterations; i++) {
    result = l1.equals(l2);
  }
  return result;
}

i1 = createImmutableList();
i2 = createImmutableList();
console.log("immutable lists are equal", compareImmutableMany(i1, i2));

The test is comparing two native js lists of size 100,000 and then two Immutable.List of size 100,000, each 1000 times. I must be missing something. I'm seeing the Immutable.List sample perform very bad relative to the native list sample.
starting
immutable lists are equal true
Seconds: 11.423
starting
normal lists are equal: true
Seconds: 0.109

You can run this locally with the following.
git clone https://github.com/naddeoa/immutablejs-slow-equals.git
cd immutablejs-slow-equals
npm i
node main.js

If I'm making a simple mistake then I'd appreciate some eyes to let me know where it is. I definitely expected this to be very fast. Especially because replacing l1.equals(l2) with a call to l1.hashCode() is really fast.

A: According to the docs:

Two immutable collections are considered value equal (via .equals() or is()) if they represent the same collection of values. This differs from JavaScript's typical reference equal (via === or ==) for Objects and Arrays which only determines if two variables represent references to the same object instance.

This means that it can't be O(1) because it needs to check the equality of all the values in the list. This is going to be substantially slower (as you have found).
The performance tradeoff is also documented:

When comparing two collections, value equality may require considering every item in each collection, on an O(N) time complexity. For large collections of values, this could become a costly operation. Though if the two are not equal and hardly similar, the inequality is determined very quickly. In contrast, when comparing two collections with reference equality, only the initial references to memory need to be compared which is not based on the size of the collections, which has an O(1) time complexity. Checking reference equality is always very fast, however just because two collections are not reference-equal does not rule out the possibility that they may be value-equal.

A: I think this could be classified as user error on my part. I was used to immutability in languages where it's a first class citizen and it didn't map will onto JS with ImmutableJS. My mistakes were (at least) as follows.
First, .equals() is a deep equal by design and it isn't what you should be relying on to implement performant equality checks in something like a shouldComponentUpdate call in React.
Second, to get the most out of ImmutableJS, you need to use its API correctly. Here is an example.
const Foo = Immutable.Record({a:1})

const foo1 = Foo({a:2})
const foo2 = Foo({a:2})

const cache = Immutable.Map({'key': foo1})

// Doing it this way will force you to either use .equals() or .hashCode()
// to check for changes later
const wrongWay = cache.set('key', foo2)
console.log('This is false', wrongWay === cache)
console.log('This is true', wrongWay.hashCode() === cache.hashCode())
console.log('This is true and slow', wrongWay.equals(cache))

// Doing it this way will let you rely in reference equality
const rightWay = cache.mergeDeep({'key': foo2})
console.log('This is true', rightWay === cache)
console.log('This is true, but not needed', rightWay.hashCode() === cache.hashCode())
console.log('This is true and slow, but not needed', rightWay.equals(cache))

Third, when using this with React with the intention of using PureComponent which does a shallow, reference equality check, you need to make sure that you're going to end up with reference equality (like in the example above).
Finally, sometimes you need to execute expensive functions on your app state in React just to be able to get the props for your component. In order to avoid doing that for no reason you can use something like Lodash's memoize in combination with reference equality on immutable objects like in the following contrived example.
const myFunction = _.memoize((immutableAppState) => {
    return immutableAppState.immutableList.map(/* really expensive stuff returning new immutable objects based on other selectors */)
}, (immutableAppState) => immutableAppState.specificRecordThatChanges )

If someone spots some errors here (or missing errors) then please point them out and I'll update the explanation.


text:
Q: Select items from different lists at the same time This is the HTML I got to do a button click event to control selected items in more than one list.

$('#button').click(function(){
    var $next = $('.section.selected').removeClass('selected').next('.section')
    if ($next.length) {
        $next.addClass('selected');
    }
    else {
        $(".section:first").addClass('selected');
    }
});

//On click I select next div with same class and remove selected from previous.
//How to loop? After 3 is selected, I want it to go to one again.
.selected { background:red }

ONE

TWO

THREE

ONE

TWO

THREE

CLICK

However, because the items are using the same class name, at the end, the script can't decide which one is first / last item.
Can anyone give me an idea?

A: Use this instead $(".section:first-child").addClass('selected') in your else condition

A: To get the items, use Queries like first-child, last-child and so on.
For more detals, Check jQuery API Documentation


text:
Q: Spring data rest deleting using id in url is not calling deleteById method I am implementing Spring Data Rest and my resource has the default delete endpoint of /table/{id} when called with the DELETE method. My repository interface extends PagingAndSortingRepository and QuerydslPredicateExecutor and thus has the following overriden methods for delete:

*

*deleteById(@NonNull ID id);

*delete(@NonNull T entity);

*deleteAll(@NonNull Iterable entities);

*deleteAll();

On calling the above mentioned endpoint I find that Spring is making a call to findById and then calling delete(entity) somehow passing entity as the result of findById. This is causing me trouble with security as this requires the user to have permission over findById, which is permitted to only certain roles, and delete, which is permitted by different roles.
What can I do to tell spring to use deleteById instead when a DELETE method call is made to the deafult endpoint with ID in the path?


text:
Q: "Last modified by" (user name, not time) attribute for xlsx using Python I need to be able to view the "last modified by" attribute for xlsx files using Python. I've been able to do for docx files, and was hoping that the architecture would be similar enough to use on other Office applications, but unfortunately not. Does anybody know of a similar module for xlsx?
This is the script to view the field using python-docx:
from docx import Document
import docx

document = Document('mine.docx')
core_properties = document.core_properties
print(core_properties.last_modified_by)

I'm using Python 3.4 and docx 0.8.6 here.

A: For .xlsx files, you can use this (set filename to the name of your .xlsx file):
import xml.etree.ElementTree
import xml.etree.cElementTree as ET
import zipfile

corePropNS = '{http://schemas.openxmlformats.org/package/2006/metadata/core-properties}'

zf = zipfile.ZipFile(filename, 'r')
part = zf.open('docProps/core.xml', 'r')
tree = ET.XML(part.read())
lastModifiedBy = tree.find(corePropNS+'lastModifiedBy').text

print(lastModifiedBy)

I haven't tested it, but I'd expect the same code to work for other OOXML files too (e.g. .docx)

A: Sorry I'm late, but here is what I got to work.
    import xlrd
    wb = xlrd.open_workbook(a_file)
    worksheet =  wb.sheet_by_index(0)
    mod_by = worksheet.book.props['last_modified_by']

A: import os
filename = "C:\\test.xlsx"
statsbuf = os.stat(filename)
print "modified:",statsbuf.st_mtime

f = os.path.getmtime('C:\\test.xlsx')
print f

since the beginning


text:
Q: Programmatically access activity of a specified Google Sheet Google Sheets has a really useful activity dashboard that shows you who has accessed a given file, and when. I'd like to build a python script to enable me to enumerate these access logs, or any other type of access logs, for a list of ~100 Sheets.
I found this article, which I thought would help, but it only has guides to retrieve events for a domain, user, shared drive, or event type. I don't want to do this—I just want to supply a list of Sheet IDs (by which I mean the bits that come after the base URL in the link, so e.g. ABCDEF in https://docs.google.com/spreadsheets/d/ABCDEF), and get the access logs back.
Would anybody be able to point me in the right direction, ideally with a python example? Thanks in advance!


text:
Q: Computing density of particles and distances from microscopic images I am analysing microscopic particles images of the kind shown below, and primarily I am interested in learning whether in Mathematica one can extract structural properties of the particles using the built-in image analysis tools.
More precisely,

*

*is it for instance possible to compute the nearest-neighbour distance distribution?

*Or more importantly, measuring the density of particles from the image? (that is, number of particles per area when binning the image).
I admit there might be similar questions previously asked but I could not pinpoint one that tackled such problem, so any help would be much appreciated.
Image example (source):

The kind of analysis I have learned so far is to use the ridge lines separating the particles in order to detect them and find their centres of mass based on the point of maximum distance to a ridge line (per particle). Here's an example
img = Import["https://i.stack.imgur.com/rUnvs.jpg"]
ridgelines = RidgeFilter[-img, 4];
distanceRidges =
 DistanceTransform@
  ColorNegate@
   MorphologicalBinarize[
    ridgelines] (*distance transform image based on the ridge filter*)
\
distMaximum =
 MaxDetect[distanceRidges,
  4] (*find centre of masses using max ridge dists*)

which yields:

A: I think you're going in the right direction. You could also attempt a segmentation from your ridge filtering and extract the centroids of the components. This is a bit sensitive to the "MinimumSaliency" value so it needs some manual intervention:
wsh = WatershedComponents[ridgelines, Method -> {"MinimumSaliency", 0.2}];
wsh // Colorize
centroids = Values[Select[ComponentMeasurements[wsh, "Centroid"], #[[1]] > 1 &]];

The advantage of ComponentMeasurements is you can get the "Area" and "EquivalentDiskRadius" if those things interest you too.
You can use the centroids and compute a DistanceMatrix:
dmtx = DistanceMatrix[centroids];

... or create a Nearest function and get the distance to the closest component centroid:
nf = Nearest[centroids];
BoxWhiskerChart[
 EuclideanDistance[#, Last[nf[#, 2]]] & /@ centroids
]

So the median distance between centroids of the cells is about 42 pixels.

Here's how you could get a density map based on the dots method I proposed in the question comments, but you could alternatively use the centroids I calculated above in place of positions:
img = Import["https://i.stack.imgur.com/rUnvs.jpg"];
ridgelines = RidgeFilter[-img, 4];
distanceRidges =
 DistanceTransform@
  ColorNegate@
   MorphologicalBinarize[
    ridgelines];

distMaximum = MaxDetect[distanceRidges, 4];
dots = SelectComponents[Pruning[Thinning@distMaximum], #Count == 1 &];
positions = PixelValuePositions[dots, 1];
Blend[{
  Image[SmoothDensityHistogram[positions, 60,
    PlotRangePadding -> None, Frame -> None, ColorFunction -> Hue]],
  img}, .5]

Note that the density is fairly uniform and that I needed to manually provide the width as the automatic width was inadequate and didn't capture the lower density near the holes.


text:
Q: Multiplying three matrices together (example formulae included) If you take a look at the following URL and do ctrl+f for "w' is the transpose vector of w":
https://www.jpmorgan.com/tss/General/email/1159360877242
You should see three matrices are being multiplied together. I am a little unsure how I should proceed with this?
Could somebody please provide a simple example, say a 3x1 matrix, multiplied by a 3x3 matrix, multiplied by a 1x3 matrix (similar to the one in the link I provided)? I can then extend that to whatever value of n I require.
(I weren't sure how to represent the formulae in the web link in this question, if anyone could edit my question to include it- would be appreciated)

A: If:
$$\sigma_p^2 =
\begin{matrix}(w_1 \ w_2 \ \ldots w_n)\end{matrix}\cdot
\left(\begin{matrix}\sigma_{11} \ \sigma_{12} \ \ldots \ \sigma_{1n} \\ \ldots \\\sigma_{n1} \ \sigma_{n2} \ \ldots \ \sigma_{1n}
\end{matrix}\right)\cdot
\left(\begin{matrix}w_1 \\ w_2 \\ \ldots \\ w_n\end{matrix}\right)$$
Then by the laws of matrix multiplication you have:
$$\sigma_p^2 = \sum_{i=1}^n w_i\left(\sum_{j=1}^n \sigma_{ji} w_j\right) = w_1(\sigma_{11} w_1 + \sigma_{21} w_2 + \ldots + \sigma_{n1} w_n) + \ldots + w_n(\sigma_{1n} w_1  + \ldots +  \sigma_{nn} w_n)$$


text: Q: import "hcaptcha_field" could not be resolved Django I'm trying to add hCaptcha to my project but I can't get it to work, I've tried several versions of this library but I can't get it to work. Every time i tried importing 'hcaptcha_field' or 'hcaptcha_fields' it gives me the error import "hcaptcha_field" could not be resolved Django. Any solution?