bug on the box problem

Question: A bug walks on the surface of a box ($L=B=1$, $H=2$), starting at a corner, $A$. You want to feed the bug but you also want the bug to walk the longest distance.  The bug takes the shortest path possible.  Where do you put the food to make it walk the longest?
The box floats in the air and the bug can walk on any face of box it wants.
Hint: its not $B$ Refer the image
Comment: Are you *sure* it isn't $B$?
Comment: Have you tried drawing a net of the box?
Comment: What have you tried? What is the shortest distance from $A$ to $B,$ for example?
Comment: i did try the net thing, but we have to make the bug walk the longest distance
Comment: Yes it isn't B, it is mentioned with the problem
Comment: OK, I am pretty sure now that the maximum distance is $\dfrac{\sqrt{130}}{4}$ after correcting an error.
Comment: @OscarLanzi: Batominovski is right; see my answer.
Answer: The two existing answers provide good intuition with their net diagrams and go a long way towards a solution, but they can be improved by combining them.
Oscar Lanzi's answer is wrong in that the golden path should travel along the face, as in David G. Stork's answer, not along the edge.
David G. Stork's answer is missing the symmetry argument from Oscar Lanzi's answer that reduces the number of coordinates to be optimized from $2$ to $1$.
Combining the two, we can consider a point on the diagonal of the opposite square face with coordinates $(x,x)$ measured from $B$. The path that uses one rectangular face has squared length
$$
(2+(1-x))^2+(1-x)^2=2x^2-8x+10\;,
$$
whereas the path that uses two rectangular faces has squared length
$$
(2+x)^2+(2-x)^2=2x^2+8\;.
$$
These are equal for $-8x+10=8$, that is, for $x=\frac14$. Their derivatives have opposite sign, so increasing one will decrease the other; thus this point $\frac14$ along the diagonal from $B$ towards the corner above $A$ is the point at maximal distance. The maximal distance is
$$
\sqrt{2\left(\frac 14\right)^2+8}=\frac{\sqrt{130}}4\approx2.850\;,
$$
compared to the distance $\sqrt8\approx2.828$ to $B$, a difference of less than one percent.
We can also find the minimal height of the box at which this phenomenon appears. Replacing $2$ by $h$ above, we have
$$
(h+(1-x))^2+(1-x)^2=2x^2-4x-2hx+(h+1)^2+1
$$
and
$$
(h+x)^2+(2-x)^2=2x^2-4x+2hx+h^2+4\;.
$$
These are equal for
$$
-2hx+(h+1)^2+1=2hx+h^2+4
$$
and thus
$$
x=\frac{h-1}{2h}\;.
$$
Thus, for $h\lt1$ there is no solution, so $B$ is the point at maximal distance. For $h=1$, the two paths to $B$ have the same length, which makes sense, since in this case they are related by symmetry. For $h\gt1$ the point $D$ at equal distance along the two paths is on the diagonal of the square face, and as $h\to\infty$ it goes to the centre of the square face, which also makes sense, since in this limit the distance on the rectangular faces is $h$ no matter where you enter the square face. For $h\ge1$ the distance to $D$ is
$$
\sqrt{2\left(\frac{h-1}{2h}\right)^2-4\left(\frac{h-1}{2h}\right)+2h\left(\frac{h-1}{2h}\right)+h^2+4}=\sqrt{\frac{\left(h^2+1\right)\left(2h^2+2h+1\right)}{2h^2}}\;.
$$
Interestingly, this distance is less than the distance $\sqrt{h^2+4}$ to $B$ for $h\lt h^*=\frac{3+\sqrt{17}}4\approx1.781$ and only becomes the maximal distance as $h$ increases beyond $h^*$. This is possible because for $h\lt2$ the angle between the path $AB$ and the face diagonal $BC$ is acute after unfolding, so that a displacement of the food from $B$ along the face diagonal initially shortens the path. (Thanks to Oscar Lanzi for pointing this out.) At $h=h^*$ the triangle formed by the unfolded paths from $A$ to $B$ and to $D$ and the face diagonal is isosceles, and beyond that the distance to $D$ is greater than the distance to $B$ even though the angle at $B$ remains acute up to $h=2$.
The largest relative difference between the maximal distance and the distance to $B$ occurs at $h\approx5.083$, at which point $x\approx0.4016$ and the relative difference is about $4.6\%$.
Comment: Yup, I got "rolled" on this one (referring to the operation of rolling the top square in my net to the left, which would have revealed that my beautifully symmetric golden path is not geodesic).  But hey, my colors worked :-S +1.
Comment: @OscarLanzi: Your colours are the gold standard :-)
Comment: @OscarLanzi: Ah, yes, I maximized without the square root because it doesn't make a difference for the maximizing value of $h$, and then I forgot that I'd dropped it when I calculated the function value. Thanks, I've fixed the answer.
Comment: @OscarLanzi: Interesting, thanks for pointing out the behaviour for $h$ near $\gtrsim1$! I should have noticed that; I actually calculated the distance mainly in order to find out at which height $B$ is no longer at maximal distance, but then I forgot to actually compare the two distances :-). I've rephrased your edit a bit. It's not quite right that this happens because the angle is acute; it's still acute up to $h=2$, since as you rightly pointed out in your original answer in that case it's a right angle.
Comment: Thanks.  The angle being acute is sufficient to prevent the maximum as $h\to1^+$ with the displacement from $B$ infinitesimal.  Away from this limit you can still have the maximum with the acute angle  if the displacement from $B$ is long enough.
Comment: (1) I think you swapped the descriptions of two main formulas.  The first one uses ONE rectangular face and the second one uses TWO.  (2) I have been wondering about the symmetry argument. While I think it is true, I cannot see any simple way to prove that e.g. there might not be two max-distance points, being mirror images of each other across BC. What are your thoughts on how to rule that out?  I'm not quite convinced by Oscar's reply to my comment (when I raised this in his Answer).
Comment: @antkam: Thanks, you're right, I fixed that. Regarding the symmetry, I did find Oscar's reply convincing. I agree that this is the sort of thing where intuition can lead one astray (after all, the entire point of the question is that our intuition that $B$ must be the furthest point is wrong :-), but it does seem that any geodesic coming from $A$ and entering the upper square face crosses the diagonal at some point, so no point it reaches before that can be the furthest along that geodesic; and points it reaches after the diagonal can more quickly be reached the other way around. I think :-)
Answer: Consider the net given below.

By symmetry considerations $X$, where the food lies, should lie on the diagonal $\overline {BC}$ of the square face opposite $A$, where $B$ is the vertex opposite $A$ and $C$ is at the other end of the lateral edge containing $A$.
And the rest of what I had, I have learned, is wrong, therefore deleted.
Comment: I have been wondering about the symmetry argument.  While I think it is true, I cannot see any simple way to prove that e.g. there might not be two max-distance points, being mirror images of each other across BC.  What are your thoughts on how to rule that out?
Comment: Suppose you try to identify $X$ off the symmetry axis.  Then there exists a reflection of $X$ through the axis, call it $X'$.  If you draw the symmetrically equivalent geodesics from $A$ to both of these points they intersect on the axis at a point beyond both making this point on the axis more distant.  So, you need only match that greater distance with the one along the symmetry axis.
Answer: The longest distance cannot lie on any of the pink sides:

After all, the greatest distance here is $\sqrt{5}$, and the shortest distance to $B$ is $\sqrt{10}$ over the pink then to the "top," but $\sqrt{8}$ on only the sides.
By symmetry, for any point on the top white rectangle, there is an equivalent point on the bottom white rectangle, so if some longest-distance point occurs on one, it must occur on the other.
Thus we need only consider points on one of these white rectangles (say, the bottom, now yellow).

The distance to the furthest point on the yellow rectangle is of course to the point $B$, which is $\sqrt{8}$.  So we can eliminate the yellow rectangle.
The "farthest point" must lie on the top square (now green).  It must be a point farther than to $B$....

Consider some red point on the top face, at coordinates $(x,y)$ measured with respect to $B$, where $\{ x,y \} \leq 1$.  The "straight" distance to it (from $A$) is $d = \sqrt{(3-x)^2 + (1-y)^2}$. The distance "around the back" is illustrated by the dashed line:

This is the same distance as the "straight" distance to the blue point, noting that the yellow square is rotated $90^\circ$ with respect to the green one.
So now one plugs in the formula for total distance and optimizes over $x$ and $y$.
Comment: The shortest distance to $B$ is $\sqrt8$, though.
Comment: Of course...  I'm getting to that!
Comment: One of my friends sent me solution for this, but I can't make much sense out of it, can I share it here?
Comment: @CaesarJ_889:  No... not yet.
Comment: Ok, anyway the solution here seems better and clear, and it is headed in the right direction. Thanks.
Answer: If a curve gives the shortest path between two points then it is a geodesic. But any running line between two arbitrary points is  geodesic then the path length need not be the shortest. We can choose one among the many longer geodesics that are not unique on $\mathbb R^2$ including surfaces with discontinuous folds.
I assume we choose a corner $A$ and a farther off point from where to give the ant a run for food as start and target points but the logic holds for any point-pair, wlog. The shortest distance is along straight line whose path is has a directions inclined at
$$ \tan^{-1} \dfrac{2}{4}$$
to base square developed length $=4.$
There is a mathematical  definition of a minimum distance but none for maximum in unconstrained maximization.  Any arbitrarily longer path is a candidate when  inclined progressively less at
$$ \tan^{-1} \dfrac{2}{4n}$$
for arbitrarily large $n$.
The concept is from  Helix of a cylinder.
You can wind a thread between two points along helical geodesics in an infinite number of ways following progressively reducing pitch angles.
Shown are paths on development of a square box 2 units high.

The modeling however in this way is constrained as stated to be along one or many of path minimizing geodesics.
Answer: Given that the 2D topology of the 3D box is as shown in the figures in this answer and previous answers, there is a simple geometric solution that clearly shows the max distance is the distance to B if you can only put food in one location of the box. If you draw a circle centered at A that completely encloses the 2D topology of the box, the only place that circle touches the box is at B. The radius is the longest straight line distance within the circle and that radius is the $sqrt{10}$Box inscribe in a circle
Comment: welcome to MSE!  :)  the issue is that the bug, being smart, found the $\sqrt{8}$-length shorter path to $B$.  the OP asked for the point with the longest possible shortest-path.

bug on the box problem


Knowing that $A^2+B^2=\sqrt{2+\sqrt{2}}\cdot AB$, prove that $n$ is a multiple of $16$

Question:
Let $A,B \in \mathcal{M}_{n}(\mathbb{R})$ such that $$A^2+B^2=\sqrt{2+\sqrt{2}}\cdot AB$$
  Knowing that $\det(AB-BA)>0$, prove that $n$ is multiple of $16$.

I know that for this type of problems, one usually uses some identities such as $$(A+iB)(A-iB)=c(AB-BA)$$ and its conjugate, where $c$ is a complex number and since $A,B$ are real matrices, their determinants will be positive real numbers. Since $\det(AB-BA)>0$, that will lead to $c^n=0$ and with the help of some trigonometry it would follow that $n$ is the multiple of something.
Here, however, I couldn't obatain the identity I described. That square root points, though, exactly to this method and some trigonometry.
Comment: This question has two small but important differences from [q2682360](https://math.stackexchange.com/q/2682360). Where does it come from?
Comment: It is from Romania's shortlist from 2015.
Answer: We show that if $A,B\in M_n(\mathbb{C})$ satisfy the above equation and are s.t. $\det(AB-BA)\not= 0$, then $n=0 \;mod(8)$.
Proof. Let $\alpha=\sqrt{2+\sqrt{2}},\beta=\sqrt{2-\sqrt{2}}$. Using the method I described in my post in $\det(AB-BA)=0$?
or in
$A^2-B^2=\alpha(AB-BA)$
we put $A=uX+vY,B=wX+xY$ where $w=x=2,u=\alpha+i\beta,v=\alpha-i\beta$. Then $AB-BA=(ux-wv)(XY-YX)$, where $ux-wv=4i\beta$. Thus $\det(XY-YX)\not= 0$.
The considered equation becomes $XY=-e^{3i\pi/4}YX$. Consequently $\det(XY-YX)=\det((-e^{3i\pi/4}-1)YX)$ and $\det(YX)=\det(XY)\not= 0$.
Since $\det(XY)=(-1)^ne^{3in\pi/4}\det(XY)$, we deduce that $(-1)^ne^{3in\pi/4}=1$ and $n=0\; mod(8)$.


NullPointerException

Question: \  Problem is about the NullPointerException that appears in the WifiScanner class while detecting bestsignal.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{project.e.wifiactivity/project.e.wifiactivity.WifiConnector}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.net.wifi.ScanResult.toString()'

\
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.net.wifi.ScanResult.toString()' on a null object reference
        at
project.e.wifiactivity.WifiScanner.bestReturn(WifiScanner.java:46)
        at
project.e.wifiactivity.WifiConnector.onCreate(WifiConnector.java:23)

\Logcat
03-30 04:26:07.351  26037-26037/? I/art﹕ Late-enabling -Xcheck:jni
03-30 04:26:07.522  26037-26059/project.e.wifiactivity D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-30 04:26:07.525  26037-26037/project.e.wifiactivity D/﹕ HostConnection::get() New Host Connection established 0xf3e5c7b0, tid 26037
03-30 04:26:07.536  26037-26037/project.e.wifiactivity D/Atlas﹕ Validating map...
03-30 04:26:07.573  26037-26059/project.e.wifiactivity D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so
03-30 04:26:07.574  26037-26059/project.e.wifiactivity D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so
03-30 04:26:07.596  26037-26059/project.e.wifiactivity D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so
03-30 04:26:07.607  26037-26059/project.e.wifiactivity D/﹕ HostConnection::get() New Host Connection established 0xeec393f0, tid 26059
03-30 04:26:07.628  26037-26059/project.e.wifiactivity I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-30 04:26:07.672  26037-26059/project.e.wifiactivity D/OpenGLRenderer﹕ Enabling debug mode 0
03-30 04:26:07.692  26037-26059/project.e.wifiactivity W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-30 04:26:07.692  26037-26059/project.e.wifiactivity W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xeec38740, error=EGL_SUCCESS
03-30 04:26:09.662  26037-26059/project.e.wifiactivity W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-30 04:26:09.662  26037-26059/project.e.wifiactivity W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3d0cc60, error=EGL_SUCCESS
03-30 04:26:27.858  26037-26037/project.e.wifiactivity D/WifiDemo﹕ onCreate()
03-30 04:26:27.936  26037-26059/project.e.wifiactivity W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-30 04:26:27.936  26037-26059/project.e.wifiactivity W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3e840a0, error=EGL_SUCCESS
03-30 04:26:28.130  26037-26037/project.e.wifiactivity D/AndroidRuntime﹕ Shutting down VM
03-30 04:26:28.130  26037-26037/project.e.wifiactivity E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: project.e.wifiactivity, PID: 26037
    java.lang.RuntimeException: Unable to start activity ComponentInfo{project.e.wifiactivity/project.e.wifiactivity.WifiConnector}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.wifi.ScanResult.toString()' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     **strong text**Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.wifi.ScanResult.toString()' on a null object reference**
            at project.e.wifiactivity.WifiScanner.bestReturn(WifiScanner.java:46)
            at project.e.wifiactivity.WifiConnector.onCreate(WifiConnector.java:23)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

\MainActivity class
        /package project.e.wifiactivity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.wifi.WifiConfiguration;
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiManager;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.List;

    public class MainActivity extends AppCompatActivity implements View.lickListener {

    private static final String TAG="WifiDemo";
    WifiManager wifi;
    BroadcastReceiver receiver;
    public Login login = new Login();

    TextView text;
    Button btn;
    Button buttonp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text=(TextView)findViewById(R.id.text);
        btn=(Button)findViewById(R.id.btn);
        Button enb = (Button) findViewById(R.id.enb);    v

        final  WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

           enb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(true);
                    Toast.makeText(MainActivity.this, "Wifi Enabled", Toast.LENGTH_LONG).show();

                }
            }

        });

        buttonp = (Button) findViewById(R.id.buttonp);
        buttonp.setOnClickListener(this);
        Intent l = new Intent(this, WifiConnector.class);
        startActivity(l);

        btn.setOnClickListener(this);
        //get wifi status
        wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
        WifiInfo info=wifi.getConnectionInfo();
        String name = info.getSSID();
        String macid = info.getMacAddress();
        text.append("\n\nWifi Name :"+ name +"\nMac Id :"+ macid);
        //list available network

        List<WifiConfiguration> configurations= wifi.getConfiguredNetworks();
        for(WifiConfiguration configuration : configurations){
            text.append("\n\n" +configuration.SSID+"\n"+configuration.BSSID);
        }

        //register broadcast receiver

        if(receiver==null) {
            receiver = new WifiScanner();
            registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            Log.d(TAG, "onCreate()");
        }

    }

    @Override
    protected void onStop() {
        try {
            this.unregisterReceiver(receiver);
            super.onStop();
        } catch (IllegalArgumentException f) {
            f.printStackTrace();
        }
    }

    @Override
    protected void onPause() {

        try {
            super.onPause();
            unregisterReceiver(receiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onResume() {

        super.onResume();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(receiver, intentFilter);

        int f = login.resultp();

        if (f == 1) {
            Intent l = new Intent(this, MainActivity.class);
            startActivity(l);

        }
    }

    @Override
    public void onClick(View view) {
    Toast.makeText(getApplicationContext(), "All Network Searched!!", 0).show();
        if (R.id.btn == view.getId()){
             Log.d(TAG, "onCreate() wifi.startScan()");
             wifi.startScan();

        }
    }
}

\Wifi Scanner Class
package project.e.wifiactivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

import java.util.List;

public class WifiScanner extends BroadcastReceiver {

public ScanResult bestsignal ;
private static final String TAG="WifiScanReceiver";
MainActivity main;

@Override
public void onReceive(Context arg0, Intent arg1) {

     List<ScanResult> results = main.wifi.getScanResults();

    for(ScanResult result : results) {
        if(bestsignal == null || WifiManager.compareSignalLevel(bestsignal.level, result.level)<0)
        bestsignal = result;
        bestReturn();

    }
     String message=String.format("%s networks found.%s is the strongest.", results.size(), bestsignal.SSID);
    Toast.makeText(main, message, 0).show();
    Log.d(TAG, "onReceive() message :"+message);

}

public String bestReturn() {

    return bestsignal.toString();

}

}
\Wifi Best Signal Connector Class
package project.e.wifiactivity;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;

import java.util.List;

public class WifiConnector extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WifiScanner wifiscannner = new WifiScanner();
        String bestnetSSID = wifiscannner.bestReturn();
        String networkPass = "pass";

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + bestnetSSID + "\"";

        conf.preSharedKey = "\"" + networkPass + "\"";

        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.addNetwork(conf);

        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals("\"" + bestnetSSID + "\"")) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();

                break;
            }
        }

    }

}

\Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="project.e.wifiactivity" >
<uses-feature android:name="android.hardware.wifi" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

<application
    android:debuggable="true"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".Display"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Login"></activity>
    <activity android:name=".MainActivity"></activity>
    <activity android:name=".WifiConnector"></activity>

</application>

</manifest>

Comment: the error is because of null object...your ScanResult is null
Comment: I understand that but what could be the proper way of initializing ScanResult, I want to know that.
Answer: Quick fix:
public String bestReturn() {
  if(bestsignal!=null)
    return bestsignal.toString();
  else{
    return null;
  }
}

Problem:
You are calling this
String bestnetSSID = wifiscannner.bestReturn();
which creates an instance of BroadcastReceiver and thus it's onReceive callback hasn't been called yet. Thus bestsignal remains null.
Answer: Intent l = new Intent(this, MainActivity.class);
        startActivity(l);
" this = MainActivity.this "

MainActivity not start to MainActivity .. :D
Comment: was testing around, must have happened in the confusion... :-)
anyways thanks,, :-)

NullPointerException


How do I load a Media entity from a File entity?

Question: I have a File entity loaded programmatically. I want to load a Media entity from it. Is there a way to achieve this?
Comment: Do you mean you want to load the Media entity the File entity belongs to? Or you want to create a new Media entity and add the File entity you've created to that File entity?
Comment: Yes exactly i want to load the Media entity the File belongs to.
Answer: Example - if your File entity is loaded in a variable named $file, and the field name on the Media entity is field_media_image:
$media_entities = \Drupal::entityTypeManager()->getStorage('media')->loadByProperties([
  'field_media_image' => $file->id(),
]);

$media_entity = is_array($media_entities) ? array_pop($media_entities) : NULL;

Note1 : If the File object belongs to more than a single Media entity, you will need to loop through $media_entities to find the one you want.
Note 2: $media_entity will either contain the Media entity the File entity belongs to, or be NULL if the File entity doesn't belong to a Media entity.
Answer: Actually i found a good answer, i used :
$result = \Drupal::service('file.usage')->listUsage($file);
and then in the $result i am checking if any keys called media exist. If so, i can then load my Media :)
Comment: There is an API for doing what you want, where you don't have to do the same checks you noted. Please see my answer to this question.


Different logo on different pages

Question: I want to switch my site logo for different pages. Actually there are two site logo's that need to appear on different set of pages on my drupal 6 website.
What is the easiest way of doing this? Is there any module available for doing this or some other easy steps??
Comment: What differentiates these pages?  Content type, taxonomy, Organic Groups?
Comment: I must strongly recommend that you don't implement anything that is "logo-specific", to solve this problem. You could use the [Logo tool](http://drupal.org/project/logotool) module as someone has suggested, but such super-localized modules are to be avoided in my opinion. If you instead wield good tools, such as [Views](http://drupal.org/project/views), [Panels](http://drupal.org/project/panels) [Context](http://drupal.org/project/context), or similar, you will learn to solve 100 _other_ problems while you solve this one.
Comment: I agree with you Latherion, but vies and panel contexts have been used by me only with ctools. Can views help in redering conditional site logo as per requirements???? Please tell me if you have any such experience. I would love to do it this way.
Comment: If it were me I'd ditch Logo and use a two different blocks that simply contain an image.  Configure one to show up on all pages except a few certain sections, and another block that shows up on those sections.
Answer: This module appears to have helped many: Logo Tool
From the Logo Tool page:

A simple tool to display either a random logo on every page refresh, else display a specific logo on specified pages and a default set logo on all unspecified ones.

Different logo on different pages


Como mostrar o dado repetido somente uma vez?

Question: Bem, estou com o seguinte problema no MySQL: Criei duas tabelas uma tabela de livros e outra tabela de autores. Pois bem, eu preciso mostrar o nome do livro com os seus respectivos autores, porém tem alguns livros que possuem mais de 1 autor ou seja usando o seguinte SQL:
select l.titulo_livro, a.nome_autor, a.id_autor from tb_livros as l
join tb_autores as a
where l.id_livro = a.id_livro_escrito;

Obtenho o seguinte resultado:

Tem alguma forma de fazer com que não se repita o nome do livro e que os nomes do autores de um mesmo livro se juntem?
Answer: Acredito que você esteja procurando pela função GROUP_CONCAT:
select l.id_livro,
    MIN(l.titulo_livro),
    GROUP_CONCAT(a.nome_autor),
    GROUP_CONCAT(a.id_autor)
from tb_livros as l join tb_autores as a
    on (l.id_livro = a.id_livro_escrito)
group by l.id_livro

Também é possível agrupar por titulo_livro se seu modelo garantir que não existam livros com o mesmo título (i.e., titulo_livro é uma chave única em tb_livro), mas a solução com o identificador é mais robusta.
A função MIN não é estritamente necessária no MySQL já que titulo_livro é  funcionalmente dependente de id_livro. Dito isso, por questões de compatibilidade com outros bancos optei por não usar diretamente uma coluna que não foi listada na cláusula group by. Versões mais recentes do MySQL expõem inclusive uma função ANY_VALUE para lidar com esse típo de situação.
Comment: Nossa cara, muito obrigado.
Comment: Pq foi necessário usar o MIN ?
Comment: Atualizei a resposta para comentar sobre o uso de `MIN`.
Comment: Se a resposta resolveu adequadamente seu problema por favor não se esqueça de aceitá-la.
Comment: Acho que esqueceu! rsrs
Answer: Com um distinct ele vai eliminar os resultados iguais:
   select distinct l.titulo_livro, a.nome_autor, a.id_autor from tb_livros as l
join tb_autores as a
where l.id_livro = a.id_livro_escrito;

Comment: Um livro pode ter diversos autores. Ele quer que os autores sejam concatenados para cada linha de livro.
Comment: Eu já havia testado com o distinct, mas o resultado continua sendo o mesmo
Comment: o identificador da tabela autores é id_autor ou id_livro_escrito?
Tem como postar a estrutura das tabelas?
Comment: Já deu certo, Obrigado pela ajuda C:


Unable to embed fonts in PowerPoint

Question: I'm trying to embed fonts on a PowerPoint template I'm working on, but every time I try to save it, I get an error saying that the font cannot be embedded because it's not truetype. I've looked through every slide and made sure that the troublesome font isn't there, but I still get the error. I've also tried deleting the font from my system via the registry. It's possible this issue comes from the fact that the font in question was previously used in the template, but if it's hidden or embedded already, I'm not sure how to remove it. Any help or advice would be wonderful! Thank you!
Comment: This site is for programming questions. Please post your query at answers.microsoft.com or Super User.
Answer: Have you tried replacing the font?

Unable to embed fonts in PowerPoint


How can I add an BCC or CC email with programmatically?

Question: I am sending email programmatically and I am using plugin.manager.mail to send email, I want to add a CC ó BCC.
Do you know the way to achieve it?
Answer: What you want to do is ensure you are defining a message type in your custom module, you can then target the message within a hook_mail_alter() to add the desired CC or BCC.
<code>function MYMODULE_mail_alter(array &$message) {
  $bccEmail = 'firstname.lastname@example.com';

  if ($message['xxx'] == 'xxx') {
    $existingBcc = isset($message['headers']['Bcc']) ? $message['headers']['Bcc'] : '';
    $message['headers']['Bcc'] = implode(' ', array_merge(
      explode(' ', $existingBcc), [$bccEmail])
    );
  }
}
</code>
https://git.drupalcode.org/project/bcc/-/blob/8.x-3.x/bcc.module has an example of adding a bcc.


How to properly covert timestamp to ISO 8601 in PHP?

Question: I'm getting the timestamp from http://www.unixtimestamp.com/index.php
So for 2016/1/1 @ 1:1:1 the timestamp should be 1451610061 which is equivalent to 2016-01-01T01:01:01+00:00 in ISO 8601 (from the site), but when I run the code below I would get the output of 2016-01-01T02:01:01+01:00 instead. Am I missing something?
$ts = 1451610061;
echo date('c', $ts);

Comment: According to [this](http://www.onlineconversion.com/unix_time.htm) site, `1451610061` results in `Fri, 01 Jan 2016 01:01:01 GMT` so its a server issue. Perhaps add a `timezone` to the `datetime`.
Comment: Works fine here too https://eval.in/725142 too
Answer: This is clearly a timezone issue, as can be seen from "+00:00" vs "+01:00".
You can also verify this by setting the default timezone before with date_default_timezone_set
date_default_timezone_set("UTC");

2016-01-01T01:01:01+00:00

See eval.in - UTC
vs
date_default_timezone_set("Europe/Berlin");

2016-01-01T02:01:01+01:00

See eval.in - Berlin

You can also find out about your local timezone with date_default_timezone_get
echo date_default_timezone_get();

eval.in - local timezone

UTC

Which also explains why http://eval.in shows the expected output.

Of course, you can set the timezone on a DateTime object individually
$ts = 1451610061;
$dt = new DateTime("@$ts");

$utc = new DateTimeZone("UTC");
$dt->setTimezone($utc);
echo "UTC=", $dt->format('c'), "\n";

$berlin = new DateTimeZone("Europe/Berlin");
$dt->setTimezone($berlin);
echo "Berlin=", $dt->format('c'), "\n";

This will show

UTC=2016-01-01T01:01:01+00:00
  Berlin=2016-01-01T02:01:01+01:00

eval.in - setTimezone

To finally answer your question: there's nothing wrong with your code. 2016-01-01T02:01:01+01:00 is a perfectly valid representation of this timestamp according to ISO 8601 - Wikipedia.


compare_exchange_strong failing despite data matching expected value

Question: The issue is with a compare_exchange_strong returning false, despite the underlying data being equal to expected. e.g.:
std::atomic<data> ptr;
...
auto ptr_data = ptr.load();
bool cmp_result = memcmp(&ptr_data, &expected, sizeof(ptr_data));
bool cas_result = ptr.compare_exchange_strong(expected, desired);
assert(cas_result || !cmp_result);

data is a 128-bit POD. ptr.is_lock_free() returns true. This is tested in a single-threaded fashion. cas_result is always false, cmp_results always true.
Compilation is done with Intel's C++ compiler, version 16 update 2. On Linux, libstdc++ version 5.3.1. 64-bit binary. Exactly the same code used to work correctly when compiled on Windows, with same ICC16 but as 32-bit code. This makes me believe it is the stdlib implementation quirk.
Thank you
Comment: That's my bad, please ignore that. The example is written from memory. The values were compared by the debugger before the CAS. Updated.
Comment: I think you're calling `memcmp` wrongly - the argments are already pointers to the compared data, why are you passing them as pointers to pointers?
Comment: Hmm, OK. The library's implementation just defers to a compiler intrinsic, `__atomic_compare_exchange`, so I doubt that it's a library issue.
Answer: I've had this situation as well on a struct I was using. I think it was caused by padding bits inserted due to alignment issues and the fact that compare_exchange does a bitwise comparison of the two values.
On my machine, the word/pointer size is 8 bytes and the struct I had was something like this:
struct s {
    int i;
    void *ptr;

};

which used only 12 bytes to represent its contents (ptr was 8 bytes, int was 4), but it's size was of 16 bytes (sizeof(s) == 16). What I did was change the struct into:
struct s {
    long long i;
    void *ptr;
};

Because long long is 8 bytes on my machine, this version had a 16 bytes size and they were all used to represent the actual value (no padding bits).
I saw the problem after reading this answer, which might be more detailed.
Comment: memcmp is *supposed* to also be a bitwise compare of the full object representation, including padding, I think.  But I assume the problem is that ICC optimizes the memcmp into just comparing the values for equality.  Suggestion: use `intptr_t` or `ptrdiff_t` to get an int that's as wide as a pointer, for either 32 or 64-bit mode.  So it's always two equal-sized members, and can be only 8 bytes if you ever compile as 32-bit or for a 64-bit ILP32 ABI like Linux x32 or AArch64's ILP32.


Exposing inherited members of a COM vb.net class

Question: I have two vb.net class:
<code>Public MustInherit Class Class1
    Private m_sProperty1 As String = ""
    Public Property sProperty1() As String
        Get
            Return m_sProperty1
        End Get
        Set(ByVal value As String)
            m_sProperty1 = value
        End Set
    End Property
End Class

<ComClass("classid","interfaceid","eventid")> _
Public Class Class2
    Inherits Class1

    Private m_sProperty2 As String = ""
    Public Property sProperty2() As String
        Get
            Return m_sProperty2
        End Get
        Set(ByVal value As String)
            m_sProperty2 = value
        End Set
    End Property
End Class
</code>
When I reference the compiled DLL through VB6, Class2 only exposes sProperty2.  How can I access the inherited property of the base class (sProperty1) through COM?
Answer: This seems to answer your question:
Exporting Inheritance Hierarchies
Managed class hierarchies flatten out when exposed as COM objects. For example, if you define a base class with a member, and then inherit the base class in a derived class that is exposed as a COM object, clients that use the derived class in the COM object will not be able to use the inherited members. Base class members are accessible from COM objects only as instances of a base class, and then only if the base class is also created as a COM object.
Taken from here:  Troubleshooting Interoperability
Answer: I'll take a guess as I'm not up to speed on .NET
I would imagine your declaration is taking your public methods of Class2 and creating a COM interface out of them.  It will only take methods (and properties) on Class2 and not inherited ones (otherwise you would get all public methods all the way down to your base class).
The solution would probably be to declare Class1 as a COM class also (it may be possible to mark it as private) then specify that the COM interfaceid of Class2 descends from the COM interfaceid of Class1.
Some thing like that shoudl do the trick.


atribuir um value a variavel javascript

Question: O problema é o seguinte o php me retorna vários botoes com um input escondido para identificar o botão.
$nome = $mysqli->query("SELECT * FROM menbros ORDER BY id");
while ($row = $nome->fetch_assoc()) {
$nome = $row['identifier'];
$i    = $row['id'];
<input type='hidden' value='".$i."' id='troca'/>
<button type='button' onclick='troca()'>
}

eu preciso que a variavel javascript pegue o value do input do botão q foi clicado.
essa forma a baixo me retorna o primeiro input da pagina mas como tenho varios preciso que minha variavel pegue o valor do input acima do botão clicado.

    var troca = $("#troca").val();

Comment: Descreva melhor pois está passível a fechamento. Faça um tour para entender melhor: http://pt.stackoverflow.com/tour
Answer: Não uses a mesma ID para elementos diferentes, ou seja IDs têm de ser únicas e só pode haver uma por página, sem repetições.
Uma alternativa seria assim:
$nome = $mysqli->query("SELECT * FROM menbros ORDER BY id");
while ($row = $nome->fetch_assoc()) {
    $nome = $row['identifier'];
    $i    = $row['id'];
    echo "<button type='button' onclick='troca(this)' value='".$i."'>";
}

sem input e sem id. Assim podes pegar o value do botão diretamente...
e no JavaScript:
function troca(btn) {
    alert('Botão nr: ' + btn.value);
}

jsFiddle: https://jsfiddle.net/occd1upa/

atribuir um value a variavel javascript


How prove this $(x_{1}+x_{2})(x_{2}+x_{3})\cdot (x_{n}+x_{1})\ge 2^n-n^2+n\sum_{i=1}^{n}x_{i}$

Question:
Let $x_{i}>0,i=1,2,\ldots,n$ and such
  $\prod_{i=1}^{n}x_{i}=x_{1}x_{2}\cdots x_{n}=1$. Show that this inequality
  $$(x_{1}+x_{2})(x_{2}+x_{3})\cdots (x_{n}+x_{1})\ge 2^n-n^2+n\sum_{i=1}^{n}x_{i}$$
  and
  this inequality
  $$(1+\dfrac{x_{2}}{x_{1}})(1+\dfrac{x_{3}}{x_{2}})\cdots(1+\dfrac{x_{1}}{x_{n}})\ge 2^n-n^2+\dfrac{n\sum_{i=1}^{n}x_{i}}{\sqrt[n]{\prod_{i=1}^{n}x_{i}}}$$
  are the same.
Comment: Should that be $\cdots$ in your expression?
Answer: The title of this question is different from the actual question asked. IF the question given is the intended one, the answer is self-evident:

The left-hand sides of the inequalities are equal to each other; the second one is simply obtained by dividing the first term in the product by $x_1$, second term by $x_2$ and so on, all the way until $x_n$, and we know that dividing by all these actually doesn't change anything (since the product $x_1x_2\ldots x_n$ is equal to $1$).
The right-hand sides are almost identical, only differing in the the sum on the right-hand side being divided by $n$-th root of the same product... which is clearly equal to $1$ too.


Como adicionar um QPushButton para o QTableWidget?

Question: Estou criando uma aplicação em PyQt5 com uma tabela, utilizando as classes QTableWidget e QTableWidgetItem. A tabela possui três colunas — as duas primeiras são apenas textos e a última é um botão, que será usado para remover o item da tabela. Meu código abaixo:
def set_items(self, data):
    self.table.setRowCount(len(data))
    self.table.setColumnCount(3)

    current_row = 0

    for title, info in data.items():
        button = QPushButton("Remove")
        button.clicked.connect(self.__remove_item)

        self.table.setItem(current_row, 0, QTableWidgetItem(title))
        self.table.setItem(current_row, 1, QTableWidgetItem(info))
        self.table.setItem(current_row, 2, QTableWidgetItem(button))
        current_row += 1

O problema é que eu não consigo adicionar o botão à tabela porque o seguinte erro é lançado:
TypeError: arguments did not match any overloaded call:
  QTableWidgetItem(type: int = QTableWidgetItem.ItemType.Type): argument 1 has unexpected type 'QPushButton'
  QTableWidgetItem(str, type: int = QTableWidgetItem.ItemType.Type): argument 1 has unexpected type 'QPushButton'
  QTableWidgetItem(QIcon, str, type: int = QTableWidgetItem.ItemType.Type): argument 1 has unexpected type 'QPushButton'
  QTableWidgetItem(QTableWidgetItem): argument 1 has unexpected type 'QPushButton'

Pela mensagem de erro, dá para ver que o problema está no QTableWidgetItem não aceitar um QPushButton ou qualquer outro widget que não seja str, int, QIcon ou uma instância da mesma classe. Minha dúvida é: o que eu devo fazer então para adicionar um QPushButton ou mesmo um outro widget para a tabela?
Answer: Para adicionar um widget em um QTableWidget, usamos o método setCellWidget do mesmo. Tente mudar essa linha
self.table.setItem(current_row, 2, QTableWidgetItem(button))

para
self.table.setCellWidget(current_row, 2, button)

Comment: Muito obrigado Carlos!


Vagrant com PHP + MySQL + Linux + Puphpet + ZF2 muito lento

Question: Tenho um ambiente montado no Windows com ZF2, Doctrine e MySQL que roda bem rápido.
Porém agora estou experimentando o Vagrant com a máquina configurada através do Puphpet. Consegui fazer o sistema funcionar nesse ambiente, porém ele está extremamente lento. E quando eu faço as buscas diretamente no MySQL pelo console, é super rápido. Não fiz alterações de configuração nem no PHP e nem no MySQL.
Teriam alguma luz para me dar?
Comment: Cara eu tentei usar o Puphpet(5vzs) e não consegui fazer funcionar o nginx e algumas outras coisas,o sistema deles é extremamente rápido mas acredito que não seja perfeitamente estável.
Eu excluí a VM e criei uma nova do zero sem puphet,te aconselho a fazer o mesmo. Abs
Answer: O Vagrant reconhecidamente possui alguns problemas com desempenho, sendo o mais comum relacionado à sincronização de arquivos.
A documentação do Vagrant fornece alternativas para sanar o problema usando NFS. ísso só funciona em linux. Se sua máquina host for Windows, pode usar sincronização via SMB.
Outros pontos em potencial que podem ser causa de lentidão são:

Pouca memória disponível
Poucos núcleos (cores) para processamento
Problema com o provider padrão da VM (Virtual Box)


How can I construct a monomorphism on field extensions?

Question: Say, in a loose sense apparently if $K,L$ are fields and $K \subset L$ I am told that $K$ is a subfield of $L$ and there is a field extension. But the formal definition says,

A field extension is a monomorphism $l:K \rightarrow L$ where $K$ and $L$ are subfields of $\mathbb{C}$.

So, a monomorphism is a map which is one-to-one but not necessarily onto.
So, I should always be able to construct some monomorphism if I am told $L$ is a field extension of $K$.
Specifically, $\mathbb{Q}$ and $\mathbb{Q}(\sqrt{2})$. How can there be a monoomrphism $\mathbb{Q} \rightarrow \mathbb{Q}(\sqrt{2})$?
$\mathbb{Q}(\sqrt{2})$ has elements of the form $p+q\sqrt{2}$ where $p,q \in \mathbb{Q}$. So namely, I have to specify some monomorphism $p \rightarrow (p,q)$. I can't think of one explicitly. How can I pinpoint some $p+q \sqrt{2}$ given some $p \in \mathbb{Q}$? This really confuses me, it seems impossible to explicitly write down the monomorphism.
How does this work? Does anyone know an explicit way for example to define a monomorphism here?
Answer: "Monomorphism" is not equivalent to "injective" in general, but every homomorphism between fields is automatically injective, which turns out to imply that it's automatically a monomorphism. The (unique!) homomorphism from $\mathbb{Q}$ to $\mathbb{Q}(\sqrt{2})$ sends $a \in \mathbb{Q}$ to $a + 0 \sqrt{2} \in \mathbb{Q}(\sqrt{2})$.
Comment: I see..but then, how can it be unique? In a similar manner, can I not construct something like, $a \in \mathbb{Q}$ sent to $0+a \sqrt{2} \in \mathbb{Q}(\sqrt{2})$ for example?
Comment: @John: this is not a homomorphism of fields. For example, it does not send $1$ to $1$, and it does not respect multiplication.
Comment: ah i see...thanks


"Node Picker" for custom module?

Question: I'm building a custom module so the editors at my company can select several nodes and spit them out as a newsletter. There are some modules that get me halfway, but due to some specific requirements, coupled with me really wanting to wrap my head around creating custom modules, I'm starting from scratch.
I understand the hooks, and have set up the menu, permissions, and most of the form fields where users can select a template and other options. I'm stuck at the part where they actually pick the nodes.
I was thinking I can probably create a View with some exposed filters and maybe hook into that, if it's possible. Ideally, I'd let them drag and drop the nodes, reorder them, etc.
I'm not looking for someone to code this out for me, would just like to be pointed in the right direction.
Comment: I'm thinking maybe I just need to use Views Bulk Operations. There's an option to pass the IDs as a comma-separated list to another page. There's even a Draggable Views plugin. As much as I want to, there's probably no point to reinventing the wheel here.
Comment: The https://drupal.org/project/nodequeue module seems to do what you want, and if it doesn't I am sure it would have lots of reusable code that would help you along the way.
Answer: Without knowing the full scope or what modules/custom code you've already developed, this could be done fairly easily with a hook_menu, custom form and a content type. The new content type would have a multi-select (probably auto complete) node reference field which will allow for simple reordering. You could then implement a hook_menu with a custom form returning all the newsletters in a select list and when the form is submitted you can use node_load() to get all the referenced nodes from the selected node. Your submit handler would pass the applicable values to whatever batch mail module/functions you're using.

"Node Picker" for custom module?


List all Tables,Indexes, Views, Procedures, Materialize views from PostgreSQL version 13

Question: I am trying to list all the created Tables,Indexes, Views, Procedures, Materialize views from all Databases. By 'created' I mean not all the postgres default tables,views etc. I found a way to list all tables but it's per database and couldn't find a way to list all tables from all databases.
SELECT * FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema';

SELECT viewname FROM pg_views WHERE schemaname NOT IN ('pg_catalog', 'information_schema') AND viewname !~ '^pg_';

Can't find a way to list all from all databases , hope someone has an easy solution for this.
Comment: As you found pg_catalog and the information_schema is per database.  What about connecting to each database and extracting the information?
Comment: Yeah I know it's possible to do this per each db, I though maybe there's a way to run this once for all databases.
Answer: You will have to connect to each database seperatly, these details are not revealed in other databases as this might reveal sensitive information. You can query pg_database to retrieve a list of all databases and use that information to write a program that connects to all the databases (if you have the privileges to do so).


Jquery: append creates multiple new elements in elements before when clicked

Question: I'm creating a personal use website where I want to add "modules" or groups in which I can add links.
The problem I'm facing is when I add a group and start adding links, it all works fine. However when I add another group, afterwards add a link in the first group, it will add two links instead of one (in the first group) but adding a link in the second group adds one.
This scales up with however many groups I have, the last group always works as intended, but the groups before adds additional links to however many groups are underneath itself.
I'd really appreciate any help to understand the problem as I've been going at this for way too long without any progress.

const moduleHTML =
  '
 \

 \
         \

Group name
 \
         \
         \
         \

 \

 \

Add new link...
 \

 \

';

const linkHTML =
  '
 \

 \

 \
             \
            <input type="text" maxlength="16" placeholder="Name..."> \
             \

 \

 \
             \
            <input type="url" placeholder="Link..."> \

 \

 \

';

$(document).ready(function() {
  console.log("ready!");

  $('.module-add').on('click', function() {
    console.log('add module');
    $("#module-container").append(moduleHTML);

    $('.module-head-delete').on('click', function() {
      console.log('delete module');
      $(this).closest(".module").remove();
    });

    $(".module-body-container-edit-add").click(function() {
      console.log("add link");
      $(this).closest(".module-body").append(linkHTML);

      $('.module-body-container-edit-delete').on('click', function() {
        console.log('delete link');
        $(this).closest(".module-body-container-outer").remove();
      });
    });
  });
});

<!DOCTYPE html>

  <title>Daily Links</title>
  <link rel="stylesheet" href="styles.css">

Daily Links

    <input type="submit" class="module-add" value="Add module">

Answer: Every time you click on the Add module button you execute
$('.module-body-container-edit-delete').on('click', function...);

This adds another click handler to all the previously created Add new link buttons, so they execute the handler function multiple times, which creates multiple links.
Use event delegation rather than adding a handler every time. See Event binding on dynamically created elements?

$(document).ready(function() {
  console.log("ready!");

  $('.module-add').on('click', function() {
    console.log('add module');
    $("#module-container").append(moduleHTML);

    $('.module-head-delete').on('click', function() {
      console.log('delete module');
      $(this).closest(".module").remove();
    });
  });

  $("#module-container").on("click", ".module-body-container-edit-add", function() {
    console.log("add link");
    $(this).closest(".module-body").append(linkHTML);
  });

  $('#module-container').on('click', '.module-body-container-edit-delete', function() {
    console.log('delete link');
    $(this).closest(".module-body-container-outer").remove();
  });
});

const moduleHTML =
  '
 \

 \
         \

Group name
 \
         \
         \
         \

 \

 \

Add new link...
 \

 \

';

const linkHTML =
  '
 \

 \

 \
             \
            <input type="text" maxlength="16" placeholder="Name..."> \
             \

 \

 \
             \
            <input type="url" placeholder="Link..."> \

 \

 \

';

<!DOCTYPE html>

  <title>Daily Links</title>
  <link rel="stylesheet" href="styles.css">

Daily Links

    <input type="submit" class="module-add" value="Add module">


Add ASP.NET MVC and Web API Web Application in the same project

Question: I have created a new asp.net (standard) web api project and now I would like to have the front logic (ASP.net MVC) in the same project, I came to know that we can have both client (MVC) and server (Web API) application in the same project.
I tried to find the step by step process to follow, but I couldn't find any.
I would really appreciate if someone can provide me steps to follow, as this is the first time I'm building a application from scratch.
Thanks in advance.
Comment: What version of .Net?  What version of web api?
Answer: You could try to create an empty asp.net project and define that this project has the web and api features. For sample:

in Visual Studio 2019, select the asp.net template:

Define the name of the project

Select the Empty and check the options, MVC and Web Api

In the App_Start folder you will see two files. The RouteConfig.cs file define the routes for the ASP.NET MVC Web App. The WebApiConfig.cs file define the routes for the ASP.NET Web Api application.
Importante: The API controllers has a prefix on the route called api, so, when you create a controller that inherits from ApiController, it will be routed by api/ControllerName.


Least-squares solution to almost-linear equations with a few cross-terms

Question: I have an intermediate number of equations N (say, 15) that I'd like to solve in a least-squares manner for M unknowns (M

To clarify, I have a set up with unknowns $x_i$like:
$y_1 = a_1 x_1 + b_1 x_3$
$y_2 = a_2 x_2 + b_2 x_3$
and so on.
A small percentage of the equations are of the format
$y_9 = a_9 x_9 + b_9 x_5 + c_9 x_1 x_2$
Thanks!
Answer: Let's try this solution. We seem to be in $\mathbb{C}^{2}$. Consider the complete polynomial through order 2:
$$
 z(x,y) = \underbrace{a_{00}}_{0} +
\underbrace{a_{10} x + a_{01} y}_{\text{order }1} +
\underbrace{a_{20} x^{2} + a_{11} xy + a_{02} y^{2}}_{\text{order }2}
$$
Is the cross term $xy$ what you are after?
There are $m$ measurements $\left\{ x_{k}, y_{k}, z_{k} \right\}_{k=1}^{m}.$
The linear system is
$$
\begin{align}
  \mathbf{A} a &= z \\
\left[ \begin{array}{cccccc}
  1 & x_{1} & y_{1} & x_{1}^{2} & x_{1}y_{1} & y_{1}^{2} \\
  1 & x_{2} & y_{2} & x_{2}^{2} & x_{2}y_{2} & y_{2}^{2} \\
  \vdots & \vdots &  \vdots &  \vdots &  \vdots &  \vdots \\
  1 & x_{m} & y_{m} & x_{m}^{2} & x_{m}y_{m} & y_{m}^{2} \\
\end{array} \right]
%
\left[ \begin{array}{c}
  a_{00}\\ a_{10} \\ a_{01} \\ a_{20} \\ a_{11} \\ a_{02}
\end{array} \right]
&=
\left[ \begin{array}{c}
  z_{1} \\ z_{2} \\ \vdots \\ z_{m}
\end{array} \right]
%
\end{align}
$$
Typically, you will have full column rank, and the unique least squares solution will be
$$
 a_{LS} = \mathbf{A}^{+} b = \left( \mathbf{A}^{*} \, \mathbf{A} \right)^{-1} \mathbf{A}^{*} b
$$


Replace Characters in Excel

Question: I am trying to replace the last character in an excel cell. I am using
<code>=IF(RIGHT(B2,1)="W", LEFT(B2,LEN(B2)-1) &"U", B2)
</code>
This works to replace W with U, as I want. The problem I am having is that I need to replace any A as well. Is there a way to do an IF W or IF A, replace with U?
Answer: Try this (Incorrect):
<code>=IF(RIGHT(B2,1)="W" OR RIGHT(B2,1)="A", LEFT(B2,LEN(B2)-1) & "U", B2)
</code>
As per @Oberling
<code>=IF(OR(RIGHT(B2,1)="A", RIGHT(B2,1)="W"), LEFT(B2,LEN(B2)-1) & "U", B2)
</code>
As per @Barry
<code>=IF(OR(RIGHT(B2)={"W","A"}), LEFT(B2,LEN(B2)-1) & "U", B2)
</code>
The second two were tested in Excel 2013
Comment: `OR(RIGHT(B2,1)="W", RIGHT(B2,1)="A")`
Comment: The piece that Orbling gave works. Thank you guys so much for your help.
Comment: You can also use `OR(RIGHT(B2)={"W","A"})`

Replace Characters in Excel


Find a way to interact with the list generated by scriptAll() with filter

Question: Scenario: I have a table where I am trying to iteratively go through each row that matches my expected text and grab a particular column value for that row.
The html looks something like this:

                Write

                123

                220.127.116.11

                TargetProduct1

                P1

                10.0

                en-US

...

...

...

...

...

On that table, my goal is to go through each row and pick any row that has the value of "TargetProduct" and get the fifth column value of that row.
I am using the following Karate command:
* def getProduct = scriptAll('//table//tbody//tr', '_.innerText', function(x){ return x.contains('TargetProduct') })

However, when I do a karate.log on getProduct, I get something like the following:
Write  123 184.108.40.206 TargetProduct1       P1 10.0 en-US
Write  4586 22.214.171.124 TargetProduct5      Test2 10.1  en-US
Write  134 22.214.171.124 TargetProduct0       Four2 10.3  en-US
Write  3 220.127.116.11 TargetProduct2     Boo3 10.1   en-US

Along with many more like it under it (due to each row that matches the criteria).
It looks like primitive data structure, but I am not well versed in JS to know that. However, my goal is to grab the 5th index of each sets of results like above (basically generate a list with just these values: (P1, Test2, Four2, Boo3). What is one way to do that? Historically I have been able to get values using keys (i.e targetJson.result). However, there are no keys in this case to call to.
I have looked over JSON Transforms section of the documentation and I have tried some potential solutions like mapWithKey, however, they have not worked due to the strange data structure.
Please advise.
Answer: You could return an array from the JavaScript expression, containing a first value for filtering and a second string containing the text from your fifth column.
* def filter = function(x){ return x[0].contains('TargetProduct') }
* def rows = scriptAll('//table//tbody//tr', 'function(e){ return [e.innerText, e.cells[4].innerText] }', filter)
* def fifthCols = map(rows, function(x){ return x[1] })

Comment: edited. it seems the underscore only works for simple access expressions
Comment: I am getting an error on the rows variable:

`org.graalvm.polyglot.PolyglotException: js eval failed twice:(function(){ var res = []; var fun = [_.innerText, _.cells[4].innerText]; var es = document.evaluate("//table//tbody//tr", document, null, 5, null); var e = null; while(e = es.iterateNext()) res.push(fun(e)); return res })(), error: [type: MAP, value: {type=object, subtype=error, className=ReferenceError, description=ReferenceError: _ is not defined`
Comment: it worked!! I had to adjust it a bit and add "karate.map" to fifthCols (instead of just "map). Thank you so much!
Answer: First, read up on innerText to see what it does: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText - it just returns a single string, concatenating all child elements.
Suggestion: try to do this in multiple steps:
* def rows = locateAll('//table//tbody//tr')
* def filtered = rows.filter(x => x.text.includes('TargetProduct'))
* def temp = filtered.map(x => x.locateAll('td'))

What I have above is a guess, sorry I don't have time to dig into the details.
Comment: Unfortunately getting the following output `(document._karate.ref1657773424673)` multiple times over. This is a common issue I have seen with locateAll. Will play around with JSON transforms. Thank you


"Cannot import name __version__" when installing createsend in Python 3

Question: I've created a fresh venv running Python 3.3.2. While trying to install Campaign Monitor's createsend package via pip, it yields:
  Running setup.py egg_info for package createsend
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/vagrant/3.3.2venv/build/createsend/setup.py", line 5, in <module>
        from createsend import __version__
      File "./createsend/__init__.py", line 1, in <module>
        from createsend import __version__
    ImportError: cannot import name __version__
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/vagrant/3.3.2venv/build/createsend/setup.py", line 5, in <module>

    from createsend import __version__

  File "./createsend/__init__.py", line 1, in <module>

    from createsend import __version__

ImportError: cannot import name __version__

I believe this package is Python 3 compatible. I'm running the latest version of pip. Can anyone explain why I'm receiving this error?
Answer: As of version 4.2.0, released 10 Oct, 2016, this package is now Python 3 compatible. Old answer, from 2013, follows below.

No, this package is not Python 3 compatible. It is using relative imports:
    from createsend import __version__
  File "./createsend/__init__.py", line 1, in <module>
    from createsend import __version__

where the second createsend is meant to be createsend/createsend.py. Instead, Python 3 sees it as an absolute package and the recursive import fails to find the __version__ name.
Comment: Thanks for the quick answer. I didn't realize that relative imports cannot be used in a python 3 package.
Comment: It is not the only problem; just the first.
Comment: The package has been updated, and is now Python 3 compatible.


How to search for a string in an SQLite database

Question: I am new to SQLite in Android. I have successfully created the database with this schema:
public final class BookDbSchema {

    private BookDbSchema() {
    }

    public static final class BookEntry implements BaseColumns{
        public static final String NAME = "bookItems";

        public static final String ID = "id";
        public static final String URL = "url";
        public static final String TITLE = "title";
    }
}

The problem I am having is searching the database for a particular string.
I want to search the id column if 1993 exists. Please how do I do that?
I have read the documentation but I don't know where to input "1993" for in the query method.
Answer: You can use the below method :
Cursor query (String table,
                String[] columns,
                String selection,
                String[] selectionArgs,
                String groupBy,
                String having,
                String orderBy,
                String limit)

query(NAME, new String[]{ID, URL, TITLE}, ID + "=?", new String[]{"1993"}, null, null, null, null);

Answer: i belive you are looking for this
 Context context;
    BookDbSchema mDbHelper;

    public BookDbSchema (Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }
    ...

    ArrayList<String> urls = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();
    ArrayList<String> ids= new ArrayList<>();

    mDbHelper = new BookDbSchema(context);
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String[] projection = {
            FeedEntry.ID,
            FeedEntry.URL,
            FeedEntry.TITLE
    };

    String selection = FeedEntry.ID + " LIKE ? "; //WHERE
    String[] selectionArgs = {"1993"};   //VALUE

    Cursor c = db.query(
            FeedEntry.NAME,  // Your Table Name
            projection,
            selection,
            selectionArgs,
            null,
            null,
            null
    );

    if(c.getCount() != 0) {
        c.moveToFirst();
        for(int i = 0; i<c.getCount(); i++) {
            urls.add(c.getString(c.getColumnIndex(FeedEntry.URL)));
            titles.add(c.getString(c.getColumnIndex(FeedEntry.TITLE)));
            ids.add(c.getString(c.getColumnIndex(FeedEntry.ID)));
            c.moveToNext();
        }

        String firstUrl = urls.get(0);   //Returns the first url found
        String firstID = ids.get(0);   //Returns the first id found
        int urlSize = urls.size(); // returns the count of urls found
    }else{
        //Nothing found
    }

    c.close();
    db.close();

Comment: Thanks. This works but will it work if the result was no found on the first row?
Comment: yes, i will edit the awnser so if you have multiple rows with id of 1993 you will be able to get all of them
Comment: i edited my awnser, `urls` and `titles` will now hold every row with id of 1993
Comment: Please I ran into a little problem. I need to update the row in which the result was found. Is there anyway I can get the id of the row that the result was found?
Comment: you just need to add `c.getString(c.getColumnIndex(someColumn)` see the edit


Random variables transformation Normal distribution

Question:
if $x_1,x_2,...,x_{20}$ are iid $N(0,4)$, what is the distribution of

$x^2$
${{\sum_{i = 1}^5 {{x_i}^2} } \over {\sum\limits_{i = 1}^{10} {{x_i}^2} }}$

my attempt for (1):
$$\begin{align}E({e^{tx^2}}) &= \int_{ - \infty }^\infty  {{1 \over {2\sqrt {2\pi } }}} {e^{t{x^2} - {1 \over 8}{x^2}}}dx \\
&= \int\limits_{ - \infty }^\infty  {{1 \over {2\sqrt {2\pi } }}} {e^{ - ({{1 - 8t} \over 8}){x^2}}}dx = \left({1 \over {1 - 8t}}\right)^{{1 \over 2}}
\end{align}
$$
so the distribution is $\operatorname{Gamma}\left({1 \over 2},8\right)$.
as for (2):
$$
  {{\sum\limits_{i = 1}^5 {{x_i}^2} } \over {\sum\limits_{i = 1}^{10} {{x_i}^2} }} = {{\sum\limits_{i = 1}^5 {{x_i}^2} } \over {\sum\limits_{i = 1}^5 {{x_i}^2}  + \,\sum\limits_{i = 6}^{10} {{x_i}^2} }}$$
which is $\operatorname{Beta}\left({5 \over 2},{5 \over 2}\right)$.
Is my solution correct?
Answer:
indicating $X\sim N(0;4)$ usually $N(\mu;\sigma^2)$ is meant.

Thus, as
$$\frac{X}{2}\sim \Phi$$
$$\frac{X^2}{4}\sim\chi_{(1)}^2=Gamma\Bigg(\frac{1}{2};\frac{1}{2}\Bigg)$$
that is also
$$X^2\sim Gamma(\frac{1}{2};\frac{1}{8})$$

EDIT: your answer is correct. The only difference with mine is that I use the following parametrization
$$f_Y(y)=\frac{\beta^{\alpha}}{\Gamma(\alpha)}y^{\alpha-1}e^{-y\beta}$$
While you use this one
$$f_Y(y)=\frac{1}{\Gamma(\alpha)\beta^{\alpha}}y^{\alpha-1}e^{-\frac{y}{\beta}}$$
Thus the two answers are the same

Correct.

Do not forget that

$X_1,X_2,\dots ,X_{20}$ are random variables, thus a Capital letter is required.
Comment: @Ahmed : I am reviewing your answer and it is correct. The difference with mine is only a different parametrization of Gamma distribution
Comment: thank you very much


What is the probability space/measure here? In general, what does "almost sure" convergence mean when a probability space is not explicitly specified?

Question: In a set of lecture notes (on measure theoretic probability) that I'm going through, this is an exercise:

Suppose $\{\xi_k\}$ are i.i.d. positive integer valued random variables,
with $P(\xi_1 = i) = p_i > 0$ for $i = 1, 2, \dots$. Let $D_\ell = |\{\xi_1, \dots , \xi_\ell\}|$ denote the number of distinct elements among the first $\ell$ variables.
Show that $D_n \rightarrow \infty$ almost surely as $n \rightarrow \infty$.

I'm still not quite used to the idea that we could define just a random variable without explicit reference to the probability space it is defined on. I'm having trouble knowing how to frame what this question is asking in a mathematically rigorous way - in my mind, almost sure convergence only makes sense when we have an underlying sample space on which $D_n$ is defined. Do I explicitly construct one (if so, what is the "right" way to do it and is our result independent of the construction we choose?), and then use Kolmgorov's consistency theorem? Or is it simpler than that?
Answer: What matters in order to establish the almost sure convergence of a sequence $(Y_n)_n$ is the law of the sequence. If you have two probability spaces
$(\Omega_1,\mathcal F_1,\mathbb P_1)$ and $(\Omega_2,\mathcal F_2,\mathbb P_2)$ and sequences of random variables $(Y_{n,i})_{n\geqslant 1}$, $i=1,2$, such that
$\mathbb P_1\left((Y_{n,1})_{n\geqslant 1}\in B\right)=\mathbb P_2\left((Y_{n,2})_{n\geqslant 1}\in B\right)$ for each $B\in\mathbb R^{\mathbb N}$, then $Y_{n,1}\to 0$ $\mathbb P_1$-almost surely if and only if $Y_{n,2}\to 0$ $\mathbb P_2$-almost surely.
The information on the law of the sequence is usually sufficient in order to establish/disprove almost sure convergence. For example, $(Y_n)$ is independent,
$\mathbb P(Y_n=1)=1/n$ and $\mathbb P(Y_n=0)=1-1/n$, one can prove that $Y_n\to 0$ in probability but not almost surely.
Comment: I agree that in your example, $X_n$ and $Y_n$ have the same law for each fixed $n$. But the sequences $(X_n)$ and $(Y_n)$ do not: for example $P(X_1=X_4=1)=1/4$ but $P(Y_1=Y_4=1)=1/3$.
Comment: I'm not convinced this is true. If, for example, if I define sequences of random variables $Y_n$ and $X_n$ on probability space $[0,1]$ with the borel sigma algebra and Lebesgue measure, and
$ X_n = 1_{\{[0,\frac{1}{n}]\}}$ and $Y_1 = 1_{\{[0,1]\}}, Y_2 = 1_{\{[0,\frac{1}{2}]\}}, Y_3 = 1_{\{[\frac{1}{2}, \frac{1}{2} + \frac{1}{3}= \frac{5}{6}]\}}, Y_4 = 1_{\{[\frac{5}{6},1] \cup [0, \frac{1}{6}]\}},\dots, Y_n = 1_{\{[\sum_{i=1}^n \frac{1}{k}, \sum_{i=1}^{n+1} \frac{1}{k}]\}}$, where we think of this interval as "wrapped around" $[0,1]$ so that the total length is $\frac{1}{n}$.
Comment: Then $X_n$ and $Y_n$ have the same law, but $X_n \rightarrow 0$ as, but $Y_n$ does not. (for every $\omega \in [0,1]$, there are infinitely many $n$ such that $Y_n(\omega) = 1)$
Comment: Ah, I see what you mean now, I'm sorry. Yes, that makes sense.
$X_n \rightarrow 0$ as iff $\mathbb{P}(\liminf_{n \rightarrow \infty} \{|X_n| < \epsilon\}) = 1$ for all $\epsilon > 0$, which just depends on the law of the sequence $X_n$.
Comment: Exactly! No need to be sorry; usually that is the mistakes/misunderstanding that makes one make progress.


Is it possible to define such an operator $\operatorname{\Gamma}$ that satisfies $ \lim_{n\to \infty} {\Gamma} (f(n))=\beta $?

Question: Let, the function $f:\mathbb N^+ \longrightarrow \mathbb R$ is given. Is it possible to define such an operator $\operatorname{\Gamma}$  that satisfies the following conditions:

For any $n\in\mathbb {N^+}$  we have
$$\operatorname{\Gamma} (f(n))=\alpha$$and
$$\displaystyle \lim_{n\to \infty} \operatorname{\Gamma} (f(n))=\beta $$

where $\alpha,\beta \in \mathbb R$ and $\alpha\neq \beta.$
Is this mathematically possible?
Comment: Please check [Prove: If a sequence converges, then every subsequence converges to the same limit.](https://math.stackexchange.com/q/213285/602049).
Comment: @JohnOmielan So, it is not possible?
Comment: Good work! Yes, you are correct, it's not possible. I see there's now an answer, but I hope that other post helps you understand better why it's not possible.
Answer: No, simply because
$$\lim_{n\to\infty}\Gamma(f(n)) =
\lim_{n\to\infty}\alpha = \alpha\neq\beta$$
Comment: Wrong answer. ${}$
Comment: The answer is correct for the question as asked. Perhaps you stated the question incorrectly?
Comment: Yes, you are most likely right. I may not have asked the question correctly. I accept your answer. If I want to ask new question, I will ask for a new one.


How to pass multiple arguments when mapping and filtering RDD?

Question: I currently have this line to filter and apply a function to an RDD.
data_to_update.rdd.map(find_differences).filter(lambda row: bool(row))

I want to modify the find_differences function to also take another argument unique_id in addition to row. I'm not exactly sure how to go about modifying this line to do that, or if there's a better way to write it.
Comment: Use fold operations?
Answer: Assuming that your cuurent function looks something like this:
def find_differences(row):
    # do something
    return result

You can create a new function and a partial function that matches your original function:
from functools import partial

def find_differences_id(unique_id, row):
    # do something else
    return another_result

find_differences = partial(find_differences_id, unique_id)

And map the RDD as you did before.


How to hide rating field when adding comment to own node?

Question: On my website, users can rate nodes with the Fivestar module while adding a comment. In other words, the rating field (called 'stars') is part of the comment. Now, I'd like to hide the rating field for users when they comment on their own nodes (or when they already have commented before - see: How to hide Fivestar rating field after first comment?).
How can I do that?

Edit 1: I applied this patch (patch 97 on https://drupal.org/node/189527), but my problem still isn't solved. I now have the following option at Administration > Structure > Content types > MyArticle > Comment fields:

But after clearing caches and creating new content, the rating field is still displayed when I add a new comment.

Edit 2: I sent an e-mail to the patch's author and he answered this:

The purpose of the patch I created is to prevent a user from rating
  their own node.  I believe the problem you are having with this patch
  is that, since the fivestar field is on the comment, that the patch I
  wrote would probably reference the comment itself (as the entity id)
  instead of the node - freely allowing someone to vote.

Edit 3: I tried to solve my problem with a custom module called 'hiderating'. This is the code I'm using:
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid) {
      $form['field_stars']['#access'] = 0;
      }
      else {
      $form['field_stars']['#required'] = 1;
      }
    }
}

I made the 'Stars' field not required from the interface. The code is nearly working: the 'Stars' field isn't displayed when one comments on his/her own node, but unfortunately, it isn't turned to 'Required' when one comments on someone else's node. In other words, my code's else part doesn't work properly.
How can this be fixed?
Comment: have you tried using unset($form['field_stars']); instead of $form['field_stars']['#access'] = 0; and also make the field as required and remove the else part
Comment: Did you check the issue queue, we have a issue for this. https://drupal.org/node/189527. Patch 97 was the fix for that.
Comment: @Gladiator: I applied the patch you mentioned, but it doesn't work (see edit 1). The patch's author Travis thought that it's possibly not suitable for my problem (see edit 2).
Comment: why do you need an else part?
Comment: @Mohammed Shameem: well, I'd like the rating field to be required, but when I mark it as 'required' via the interface, people adding a comment to their own node get an error, because they didn't rate it (the field was hidden).
Comment: @MohammedShameem: That works! Finally solved, thank you so much! If you post it as an answer, I'll check it as the solution.
Comment: Have added it as an answer
Answer: You should use unset($form['field_stars']); instead of $form['field_stars']['#access'] = 0;
You can keep the fields as required and also remove the else condition.
So your final code would be something like this
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid) {
      unset($form['field_stars']);
      }
    }
}


sorting a series by the powers of the variable... Sort of a generalized binomial sum

Question: I am just wondering if there is any analytical solution for the coefficients  $c_n$ in the equation below:
$$\sum_{N=0}^{\infty} \frac{1}{N!} (a x^p  + b x^q)^N
= \sum_{n=0}^{\infty} c_n  x^n$$
where $p$ and $q$ are positive integers, and $a$ and $b$ are real numbers.
Basically, if reordering the terms and sorting by power, what would be the coefficients.
I appreciate if you could provide a reference. Thanks !
Comment: It is possible... though likely going to be extremely messy...
Answer: The summation on the left is the series for $\exp(ax^p+bx^q) = \exp(ax^p)\exp(bx^q)$ the product of two exponentials and it is easy to get the expansion of both of these. The coefficients of a product is just the convolution of the coefficients of the factors. So we use the series expansions to get
$$  \exp(ax^p)=\sum_{k=0}^\infty a^kx^{pk}=:\sum_{i=0}^\infty a_ix^i,\quad \exp(bx^q)=\sum_{k=0}^\infty b^kx^{qk}=:\sum_{j=0}^\infty b_jx^j $$
where $a_{pk}=a^k,\; b_{qk}=b^k$ and zero otherwise. We multiply them together to get
$$ \sum_{i=0}^\infty a_ix^i \sum_{j=0}^\infty b_jx^j = \sum_{n=0}^\infty\Big(\sum_{i+j=n}a_ib_j\Big)x^n = \sum_{n=0}^\infty c_n x^n.$$


Receber apenas número em campo de dinheiro

Question: Estou buscando um td com jQuery.
var linhaTr = $("tbody").find("tr:first-child");
var tamanhoTd = linhaTr.find("td:nth-child(2)").text();
e ele me retorna por exemplo R$ 5,00. Mas eu preciso receber de volta para fazer cálculos o valor 5.00. Tirar o R$ e mudar a virgula por ponto...
Além disso...
Gostaria de saber se é "Expressões Regulares" que preciso para poder capturar o texto de forma especial, obtendo apenas algumas coisas, preciso estudar isto e não sei o nome direito.
Answer: Se o resultado é R$ 5,00 por exemplo, uma forma inicial pode ser:

var recuperado = "R$ 5.500,10";
var numero = parseFloat(recuperado.split(" ")[1].replace('.', '').replace(',', '.'));
console.log(typeof numero, numero);

Onde é removido o sinal monetário, renomeado "," para "." e convertido para tipo numérico.
Answer: Se quiseres podes usar regex, nesse caso é para capturar a parte importante nessa string. Podia ser algo assim (exemplo):
var parteNumerica = string.match(/[\d\.\,]+/);

Mas podes simplesmente partir a string e tirar a parte numérica como o @Lucas Costa referiu. Nesse caso é ainda mais importante que a string tenha esse formato exatamente.
Nesse caso podes fazer assim:
var parteNumerica = string.split(' ').pop();

Exemplos:
Com regex:

var string = 'R$ 5.000,50';
var parteNumerica = string.match(/[\d\.\,]+/);
var numero = Number(parteNumerica ? parteNumerica[0].replace(/\./g, '').replace(',', '.') : 0);
console.log(numero);

Sem regex:

var string = 'R$ 5.000.400,50';
var parteNumerica = string.split(' ').pop();
var numero = Number(parteNumerica ? parteNumerica.split('.').join('').replace(',', '.') : 0);
console.log(numero);
Comment: `pop` pode ser mais elegante do que acessar o índice nesse caso :p
Comment: Eu recomendaria usar regex também no replace do ponto, pois caso seja um número na casa dos milhões o replace não tira todas as ocorrências do ponto. Assim: parteNumerica.replace(/\./g, '').replace(',', '.'), teria certeza que todos as ocorrências de ponto no número seriam removidas
Comment: Não deu certo, o resultado é NaN
Comment: @BrunoCabral corrigi, tinha um bug. Se não der diz qual a _string_ que estás a usar.
Comment: @GabrielWeber bem visto! corrigi :)


What's the point of estimating the posterior distribution $Y | X $ using a Gaussian Process?

Question: So classic regression methods (ridge regression, LASSO) only predict the posterior mean $E[ Y | X ]$, while Gaussian Processes give you the full posterior distribution $Y | X$.
It would be very useful if the posterior distribution had low variance in regions where the posterior mean is actually close to the true value $Y$, and high variance in other regions. But that's not what is happening (is it?). So why is it useful to estimate the posterior distribution?
Comment: The ridge/LASSO make the assumption that $E[Y\mid X] = \beta^T X$. Gaussian processes let $E[Y \mid X]$ be (essentially) any function. If I model $E[Y \mid X]$ using Gaussian process regression, I do *not* get an estimate of the distribution of $Y \mid X$ from only the GP, I get an estimate of the posterior distribution of $E[Y \mid X]$ which is a **random** function in the Bayesian context (i.e. it is not fixed, and so has a posterior distribution).
Answer: The reason why the full posterior distribution is useful is because is contains all of the relevant statistical information that you can derive given the model.
Given the posterior, you can answer any questions like:

What is the probability that the true value for $Y$ is between $a$ and $b$?,
What is the expected value of some utility function $f(y)$?

given just a point estimate (the posterior mean) doesn't tell you anything about the width of the distribution (although that can often be derived), or, for non-Gaussian models, the shape of the distribution.
This also gives a precise meaning to the idea that the estimates are "accurate" in cases where the posterior distribution has low variance: you can answer the question: "what is the probability is within some range $\pm \delta$ of a point estimate?"
Comment: Ok so if I understand correctly, estimating the posterior distribution does not give any information regarding the true mean or the true posterior distribution.
Comment: No, it _is_ the (inferred) distribution for the true mean.
Comment: The "full posterior distribution" is used as weight of predictive distribution in Bayesian inference, right?


How to create reviews for user comments?

Question: I want use user review for my content. For example they can send their comment in my content and review in comment ( with fivestar field ).
Five star and other module not work in drupal 8.
Comment: Well if you want 5 stars as you says in my answer you will need to help a little in the migration as is not possible at this time.
Answer: The scenario is not very encouraging for Drupal 8 in voting modules at this time, but you can check some modules that can help you:
Votingapi Widgets

A flexible field based Voting System based on
  https://www.drupal.org/project/votingapi .

Like Button

Add a Like button to Drupal content and comments! Get instant
  statistics and insights! Sort content by likes!

Star Rating

Star Rating is a simple module that provides star rating field and
  display formatter using Drupal 7's Field Type API.
Comment: @RobinSon I just see that we have a Drupal 8 version for https://www.drupal.org/project/starrating take a look in the project page, and I updated my answer.
Comment: Thanks but I want add 5star to my content.
Comment: @RobinSon the first module that I recommend https://www.drupal.org/project/votingapi_widgets allow you to add a star widget, can you check the project page? And tell me if this solve your problem?


Compare CStringArray element?

Question: In this code keepSelectedFiles contain 5 text files. And keepFiles contain 3 text Files from keepSelectedFiles. I just want to compare this both array and after that remove 3 keepFiles from the keepSelectedFiiles. Then just 2 files left in keepSelectedFiles. This code is not working.
 for (int i = 0; i < keepSelectedFiles.GetSize(); i++)

{
    testbox4.AddString(keepSelectedFiles[i]);

    CString s1 = keepSelectedFiles[i];
    CString s2 = keepFiles[i];
    for (int i = 0; i < keepFiles.GetSize(); i++)
    {
        if (s1.Compare(s2) != 0)
        {
            junkFiles.Add(keepSelectedFiles[i]);
        }
    }
}

Anyone know how to fix this problem?
Comment: You have posted several variations on this topic now, and most of them are pretty basic. I would advise you to study a programming book or online course. You are not going to improve your coding skills by asking Stack Overflow users to write and debug your code for you.
Comment: If `s1` and `s2` are not equal then you have to add it to `junkfiles` array??
Comment: So i do what correct this code please?
Comment: GazTheDestroyer if you think this is basic why you don't solve this problem. Maybe you are senior but in programming nothing is basic and nothing is advance. When it came to reality both is same.
Comment: @AlexCerry If you changed your container to `std::vector` instead of CStringArray, the solution is a 2 line loop.  In this day and age, there is little reason to be using MFC container classes such as CStringArray.
Comment: @AlexCerry Correction, it would be a `1 line loop:`  Example:  `for (int i = 0; i < keepFiles.GetSize(); i++)       keepSelectedFiles.erase(std::remove(keepSelectedFiles.begin(), keepSelectedFiles.end(), keepFiles[i]), keepSelectedFiles.end()));`
Answer: You can try this code
for (int i = 0; i < keepSelectedFiles.GetSize(); i++)

{
    bool flag = false;
    CString s1 = keepSelectedFiles[i];
    for (int j = 0; j < keepFiles.GetSize(); j++)// you can use different variable name
    {                                            //so there will be no confusion
        CString s2 = keepFiles[j];
        if (s1.Compare(s2) == 0)           // if s1 equal to s2
        {
            flag = true;
            break;
        }
     }

        if(!flag){
               junkFiles.Add(keepSelectedFiles[i]); // or you can pass s1 here
               keepSelectedFile.RemoveAt(i); // remove index value
               i--;
         }
         else // first empty textbox4 before this loop
            testbox4.AddString(keepSelectedFiles[i]);  // update textbox  value

}

Comment: Still code is not working junkFiles contain all Files.
Comment: Debug Assertion Failed?
Answer: CString s2 = keepFiles[i];

move the above line and put this line in the inner for loop.
Comment: Still code is not working junkFiles contain all Files.
Comment: try to print both the value before the compare statement and you will get to know what the two values are getting compaired.
Answer: You don't need 2 for loops:
for (int i = 0,  j=0; i < keepSelectedFiles.GetSize(); i++)

{
    CString s1 = keepSelectedFiles[i];
    CString s2 = keepFiles[j];
    if (s1.Compare(s2) != 0)
    {
                junkFiles.Add(keepSelectedFiles[i]);
     }
     else
     {
           ++j;
           testbox4.AddString(keepSelectedFiles[i]);
     }
 }

Compare CStringArray element?


Efficient fitting of noncentral chi-squared distribution to data?

Question: I am looking for the most efficient way to fit a noncentral chi-squared distribution with fixed d.o.f. to a given data set. So the inputs are d.o.f. and the data and the output should be the noncentrality parameter that gives the best (maximum likelihood? or any other approach that would be more computationally efficient).
Since on Wikipedia the expression for the noncentral chi2 pdf is an infinite sum of chi2 I am at a bit of a loss as to where to start. Might it be possible to find an analytic MLE for the noncentrality in case of fixed dof? Or any other tricks or cancellations that might simplify the likelihood calculation in this special case.
Comment: Thanks - I am using MATLAB and have implemented a similar approach using `mle` and `ncx2pdf` etc but it is extremely slow so I am looking to implement a more efficient approach myself.
Comment: What is the sample size? In R, it takes less than $1$ second to botain the MLE using a sample size $n=1000$. Chek `data = rchisq(1000,1,1);
ll = function(par){
if(par[1]>0)∥[2]>0) return(-sum(dchisq(data,df=par[1],ncp=par[2],log=T)))
else return(Inf)
};
optim(c(1,1),ll)`.
Comment: OK maybe "extremely slow" was a bit strong. It takes me 0.5s for a sample size of 10000... but this is something I will need to perform many times so I really want it to be as fast as possible.
Answer: Just use the method of moments : the mean of a non central chi square $\chi^2(k,\lambda)$ is $k+\lambda$, ($k$ is the dof and $\lambda$ the ncp). So take $\lambda$ equal to the mean of the data minus $k$.
Comment: If the underlying distribution of your data is really a $\chi^2(k,\lambda)$ this is enough. For theoretical considerations, read Wikipedia on the [method of moments](http://en.wikipedia.org/wiki/Method_of_moments_%28statistics%29)
Comment: Doh, so simple! This is great - I had already tried fitting chi-2 just by taking the mean but I was not sure it was theoretically correct (compared to maximum likelihood).


Resize modal from center using JavaScript and CSS

Question: I have the following fiddle example: http://jsfiddle.net/c2mmQ/
Where I show a modal using jQuery when I click the show link, and fade it in and scale it up using CSS animations. Inside the modal I have another link which resizes the modal. The idea is that it should resize from the middle so it looks like it's scaling up (although we are NOT using scale as we are actually changing the dimensions of modal). Think how the popups work on an Xbox 360.
Two issues happen.. first while the resizing does honour the css transitions, they don't fire the event transitionend so the center code doesn't run after the resize. And the second issue is that the resizing doesn't happen from the center...
Any ideas on how I can do this?
Code is below:
<code>jQuery.fn.centerImage = function () {

    var win = window.parent;

    var element = $(this);

    var centerElement = function () {
        element.css("position", "absolute");
        element.css("top", ( (($(win).height()) - element.outerHeight()) / 2));
        element.css("left", ( (($(win).width()) - element.outerWidth()) / 2));
    }

    element.bind('centerElement', centerElement).trigger('centerElement');

    $($(win)).bind('resize', function () {
        element.trigger('centerElement');
    });

    return element;
}

$(document).ready(function(){

    $('.show').on('click', function(e){

        $('.modal').centerImage().addClass('show');

    });

    $('.resize').on('click', function(e){

        $('.modal').width(640).height(480);

        $('modal').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
            $('.modal').centerImage();
        });

    });

});

.modal
{
    width: 480px;
    height: 320px;
    background: #ffffff;
    box-shadow: rgba(0,0,0,.6) 0 0 16px;

    -webkit-transform: scale(0.7);
    -moz-transform: scale(0.7);
    -ms-transform: scale(0.7);
    transform: scale(0.7);
    opacity: 0;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
}

.modal.show
{
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    opacity: 1;
}
</code>
Answer: You're going to kick yourself!
<code>$('modal').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
            $('.modal').centerImage();
        });
</code>
should be
<code>$('.modal').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
            $('.modal').centerImage();
        });
</code>
http://jsfiddle.net/robschmuecker/c2mmQ/1/
Comment: Ah thanks for that. Still it resizes down right and then re-centers... how could I do it from the center? So it has almost the same effect as the scale. Thanks again.


How can a 'tall-and-skinny' property related to kurtosis be stated rigorously in terms of its (smooth) probability functions?

Question: Skewness is generally defined as a standardized third-order centered moment.
$$S(X) \triangleq \frac{\mathbb{E}\left[ \left( X - \mathbb{E} \left[  X \right] \right)^3 \right]}{\left( \mathbb{E}\left[ \left( X - \mathbb{E} \left[ X \right] \right)^2 \right] \right)^{\frac{3}{2}}}$$
Sometimes skewness is the property that we're interested in, but often it is used to quantify the reflective asymmetry of a probability distribution. This is a heuristic because Meijer 2000 demonstrated that asymmetric distributions can have a skewness of zero even though a non-zero skewness implies that a distribution is asymmetric.
Drawing from skewness as an analogy, I would like to consider kurtosis under a similar light. Kurtosis is likewise a high-order moment:
$$K(X) \triangleq \frac{\mathbb{E}\left[ \left( X - \mathbb{E} \left[  X \right] \right)^4 \right]}{\left( \mathbb{E}\left[ \left( X - \mathbb{E} \left[ X \right] \right)^2 \right] \right)^{2}}$$
Analogously, as skewness tells us about reflective symmetry, kurtosis tells us about how 'tall-and-skinny' the distribution is. As whuber discusses on another post, the symmetry property can be formulated as an equality in terms of either its CDF or PDF (assuming sufficient smoothness).
I have yet to see a formulation of the 'tall-and-skinny' property of a distribution written in an analogous way in terms of either the CDF or PDF of a distribution.
Off the top of my head I would speculate that kurtosis of a CDF could involve a comparison to either extreme of a step function being a maximally-kurtic peak, and a line being a minimally-kurtic peak.
In terms of the PDF I might suspect that an aspect-ratio could be suitable, except that some choice on what interval counts as the 'base' would need to be defined. The choice of height might be taken to be the density at the maximum likelihood value (MLV), but this would be problematic for distributions with multiple MLV's.
How can a 'tall-and-skinny' property related to kurtosis be stated rigorously in terms of its (smooth) probability functions?
Comment: [Westfall 2014](https://www.tandfonline.com/doi/abs/10.1080/00031305.2014.917055) does a sort of 'debunking paper' on the topic.
Comment: Thanks @BruceET , I am ahead of you on that suggestion but it is appreciated.
Comment: The meaning and interpretation of kurtosis has become somewhat of a controversy here on CV.  See [this site search](https://stats.stackexchange.com/search?q=kurtosis+long+tail*).  The problem is that kurtosis isn't actually about the height of a density function or its tail behavior, because the fourth moment doesn't directly relate to either.
Comment: @whuber Oh, too bad. Thanks for updating me.
Comment: For various reasons it is difficult to get an intuitive idea of kurtosis. I think that looking at examples might be the best way to start. [This Wikipedia page](https://en.wikipedia.org/wiki/Kurtosis) might be helpful.
Answer: Well, you cannot relate tall and skinny to kurtosis because there is no mathematical connection. The beta(.5,1) distribution is infinitely tall and skinny but has low kurtosis. And the .9999U(0,1) + .0001Cauchy mixture appears perfectly flat over 99.99% of the observable data, but has infinite kurtosis.
Contrary to whuber's comment, kurtosis is in fact precisely related to the tails. Larger kurtosis mathematically implies greater tail leverage. See here and here for precise descriptions of "tail leverage."
Comment: I like the counterexamples you give that illustrate the kurtosis cannot be a direct or monotonic function of what I intuitively recognise as skinny-and-tallness.
Comment: There would have to be many more details, but generally probably not. For example, the sample mean and sample variance are correlated under non-normality.
Comment: Interesting. Does this lack of relation include a lack of [stochastic dependence](https://en.wikipedia.org/wiki/Independence_(probability_theory))?
Comment: I recall from earlier today that [Westfall 2014](https://www.tandfonline.com/doi/abs/10.1080/00031305.2014.917055) provides a mathematical argument for tails being more influential than the central values on the value of kurtosis of a distribution.
Comment: Right. But there is a monotonic relation between kurtosis and tail leverage, as my linked post shows.
Comment: I don't see any connection between kurtosis and independence. Maybe if more context were given I could see it. For example, the marginal distribution of a ARCH process would exhibit high kurtosis even when all the conditional distributions are normal.
Comment: Okay. Let $T(X)$ be an estimator of the tall-and-skinniness of the distribution of the real-valued random variable X, and $K(X)$ the kurtosis. Does $T(X) \perp \!\!\! \perp  K(X)$ (or its negation) hold for all $X$?
Comment: The sense in which I made my comment is that kurtosis tells us little about the tails--but you appear to assert more with your use of "precisely." Here's a test: I have in mind a distribution with zero mean and skewness, unit variance, and excess kurtosis of 1.  What can you tell us, either qualitatively, or quantitatively, about either of the tails? How would your explanation change if the kurtosis were 10 instead of 1? Can you explain what you mean by "tail leverage" (an uncommon term)?
Comment: I answered in the link in my post, with more detail given here https://stats.stackexchange.com/a/481022/102879
Comment: @BigBend Thank you.  Unfortunately, your definition doesn't work, because the meaning of "$m$" is indefinite -- it isn't determined by your existence assumption and there aren't any relevant quantifiers in the attempted definition.  It seems to be saying one distribution has greater "tail leverage" than another if it has a greater standardized central moment of some indefinite order $m.$ In the present case, isn't asserting a "monotonic relation" with kurtosis therefore a tautology?
Comment: Of course the definition works.  Just pick an $m$. With $m=4$, you get kurtosis.  Just like with other definitions of tail-heaviness, there are infinitely many.  This one has the advantage that it actually applies to data. And there is nothing wrong with a tautology when it provides great insights. The issue is not the algebraic tautology, it is the graphical leverage representation, which is precise, provides answers to questions such as "What does larger kurtosis mean, precisely?", and is a new way of looking at the problem that finally settles the issue.