text:
Q: android: ad coding in xml, cannot show any ads when executed i have tried adding the com.google.ads.AdView to the xml part, xml coding as follows:
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:id="@+id/tableLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_color"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="5dp"
    android:stretchColumns="*" >
<TableRow
    <Button android:id="@+id/equal"
        style="@style/Eq_button_style"
        android:text="=">
    </Button>
</TableRow>

  <com.google.ads.AdView
      android:id="@+id/adView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      ads:adUnitId="a123123123123c"      //this ID is confirmed correct
      ads:adSize="BANNER"
      ads:testDevices="TEST_EMULATOR, xxxxxxxxxxxxxxxxx"   //this ID is confirmed correct
      ads:loadAdOnCreate="true"/>

</TableLayout>

However, even though the app does not crash when it runs, there is no ads showing at the bottom. the logcat is as follows:
10-10 01:45:16.360: I/GATE(16797): <GATE-M>DEV_ACTION_COMPLETED</GATE-M>
10-10 01:45:16.365: D/webviewglue(16797): nativeDestroy view: 0x3ef6f0
10-10 01:45:16.365: E/Ads(16797): An error occurred while destroying an AdWebView:
10-10 01:45:16.365: E/Ads(16797): java.lang.NullPointerException
10-10 01:45:16.365: E/Ads(16797):   at android.webkit.WebView.setWebViewClient(WebView.java:5168)
10-10 01:45:16.365: E/Ads(16797):   at com.google.ads.internal.AdWebView.destroy(SourceFile:252)
10-10 01:45:16.365: E/Ads(16797):   at com.google.ads.internal.c$e.run(SourceFile:191)
10-10 01:45:16.365: E/Ads(16797):   at android.os.Handler.handleCallback(Handler.java:605)
10-10 01:45:16.365: E/Ads(16797):   at android.os.Handler.dispatchMessage(Handler.java:92)
10-10 01:45:16.365: E/Ads(16797):   at android.os.Looper.loop(Looper.java:137)
10-10 01:45:16.365: E/Ads(16797):   at android.app.ActivityThread.main(ActivityThread.java:4511)
10-10 01:45:16.365: E/Ads(16797):   at java.lang.reflect.Method.invokeNative(Native Method)
10-10 01:45:16.365: E/Ads(16797):   at java.lang.reflect.Method.invoke(Method.java:511)
10-10 01:45:16.365: E/Ads(16797):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
10-10 01:45:16.365: E/Ads(16797):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
10-10 01:45:16.365: E/Ads(16797):   at dalvik.system.NativeStart.main(Native Method)
10-10 01:45:16.365: I/Ads(16797): onReceiveAd()
10-10 01:45:16.460: D/dalvikvm(16797): GC_CONCURRENT freed 424K, 6% free 9580K/10119K, paused 2ms+11ms
10-10 01:45:16.460: W/Ads(16797): Not enough space to show ad! Wants: <480, 75>, Has: <464, 708>

How can it be solved? The program does not force close, it can still execute but the ad just cannot show.
Also, the last row Logcat says not enough space? how to add more space for it? i have already reserved many space for it.
Many thanks in advance!
revised logcat:
The app can still be executed appearing without any error, but these "E" parts are there any effects on the proper execution of the app in some situation?
10-11 00:52:30.330: E/Ads(10023): An error occurred while destroying an AdWebView:
10-11 00:52:30.330: E/Ads(10023): java.lang.NullPointerException
10-11 00:52:30.330: E/Ads(10023):   at android.webkit.WebView.setWebViewClient(WebView.java:5168)
10-11 00:52:30.330: E/Ads(10023):   at com.google.ads.internal.AdWebView.destroy(SourceFile:252)
10-11 00:52:30.330: E/Ads(10023):   at com.google.ads.internal.c$e.run(SourceFile:191)
10-11 00:52:30.330: E/Ads(10023):   at android.os.Handler.handleCallback(Handler.java:605)
10-11 00:52:30.330: E/Ads(10023):   at android.os.Handler.dispatchMessage(Handler.java:92)
10-11 00:52:30.330: E/Ads(10023):   at android.os.Looper.loop(Looper.java:137)
10-11 00:52:30.330: E/Ads(10023):   at android.app.ActivityThread.main(ActivityThread.java:4511)
10-11 00:52:30.330: E/Ads(10023):   at java.lang.reflect.Method.invokeNative(Native Method)
10-11 00:52:30.330: E/Ads(10023):   at java.lang.reflect.Method.invoke(Method.java:511)
10-11 00:52:30.330: E/Ads(10023):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
10-11 00:52:30.330: E/Ads(10023):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
10-11 00:52:30.330: E/Ads(10023):   at dalvik.system.NativeStart.main(Native Method)

A: The issue is indeed:
W/Ads(16797): Not enough space to show ad! Wants: <480, 75>, Has: <464, 708>

For that device, you'll need the entire width of the screen to show an ad in portrait. Part of the problem is the android:padding="5dp" on your TableLayout.

A: It should be a layout problem.
Try this once.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TableLayout
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:id="@+id/tableLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
            android:background="@color/background_color"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="5dp"
        android:stretchColumns="*" >

        <TableRow>

            <Button
                android:id="@+id/equal"
                    style="@style/Eq_button_style"
                android:text="=" >
            </Button>
        </TableRow>
    </TableLayout>

    <com.google.ads.AdView
        android:id="@+id/adView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="a123123123123c"
        ads:loadAdOnCreate="true"
        ads:testDevices="TEST_EMULATOR, xxxxxxxxxxxxxxxxx" />

</LinearLayout>


text:
Q: Kubernetes cluster has oplock (samba) on file in Azure storage account I'm running the bradbeck/nexus-https container using kubernetes in Azure Container Service and mounting the /nexus-data volume against an Azure storage account File Share. On the k8s-agents I installed cifs-utils to access the file share.
When the pod exited, perhaps not gracefully(?), the samba client put the pending delete flag on /nexus-data/cache/cache.lock and has not released it.
When I try to start a new pod mounting the same file share, it fails with:

File does not exist: /nexus-data/cache/cache.lock

When I try to delete it through the Azure Portal, it fails with:

Failed to delete file 'nexus-data/cache/cache.lock'. Error: The specified resource is marked for deletion by an SMB client.

That is a 409 error.
How do I break this lock / get rid of this file?

Edit: I tried restarting the k8s-agents, but even this didn't work! Fortunately I could delete the entire file share, and recreate it. That might not by an option in the future: az storage share delete --name nexus-data

A: As far as I can tell, this has nothing to do with Nexus per se. I experienced the same thing with a TeamCity server as well.
What is happening is that when a container dies the samba file share is not unmounted on the host machine. I haven't yet figured out how to work out which entry in /etc/mtab belongs to the data volume of the dead container. For now I'm restarting the host, which unmounts the file system and allows the delete instruction to complete.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenGLES , why glReadPixels() can't read data from FBO's Renderbuffer's color buffer? This the complete code:

public class FBORenderer2 implements GLSurfaceView.Renderer {

    private static final String TAG = "FBORenderer2";

    protected FloatBuffer mVerBuffer = ShaderUtils.floatBuffer(-1.0f,  1.0f,
            -1.0f, -1.0f,
            1.0f, 1.0f,
            1.0f,  -1.0f);
    protected FloatBuffer mTexBuffer = ShaderUtils.floatBuffer(0.0f, 0.0f,
            0.0f,  1.0f,
            1.0f,  0.0f,
            1.0f, 1.0f);

    private Bitmap mBitmap;
    private ByteBuffer mBuffer;

    private final int[] fFrame = new int[1];
    private final int[] fRender = new int[1];
    private final int[] fTexture = new int[3];

    protected int mHPosition;
    protected int mHCoord;
    protected int mHTexture;
    protected int mHMatrix;

    protected int program;

    private Context context;

    private float[] mMatrix = {
            1,0,0,0,
            0,1,0,0,
            0,0,1,0,
            0,0,0,1
    };

    private Callback mCallback;

    public FBORenderer2(Context context){
        this.context = context;
        mMatrix = flip(mMatrix,false,true);
    }

    public static float[] flip(float[] m,boolean x,boolean y){
        if(x||y){
            Matrix.scaleM(m,0,x?-1:1,y?-1:1,1);
        }
        return m;
    }

    public void setBitmap(Bitmap bitmap){
        this.mBitmap = bitmap;
    }

    public void setmCallback(Callback callback){
        this.mCallback = callback;
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        program = ShaderUtils.createProgram(ShaderUtils.loadFromAssets("base_vertex.vert",context.getResources()),
                ShaderUtils.loadFromAssets("gray_fragment.frag",context.getResources()));
        GLES30.glEnable(GL_DEPTH_TEST);
        mHPosition= GLES30.glGetAttribLocation(program, "vPosition");
        mHCoord=GLES30.glGetAttribLocation(program,"vCoord");
        mHMatrix=GLES30.glGetUniformLocation(program,"vMatrix");
        mHTexture=GLES30.glGetUniformLocation(program,"vTexture");

        // Texture  source Texture
        GLES30.glGenTextures(1, fTexture, 0);
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, fTexture[0]);
        GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, mBitmap, 0);

        // RenderBuffer
        GLES30.glGenRenderbuffers(1, fRender, 0);
        GLES30.glBindRenderbuffer(GLES30.GL_RENDERBUFFER, fRender[0]);
        GLES30.glRenderbufferStorage(GLES30.GL_RENDERBUFFER, GLES30.GL_RGBA8, mBitmap.getWidth(), mBitmap.getHeight());
        LogUtils.checkError(TAG,"glRenderbufferStorage");

        // FrameBuffer
        GLES30.glGenFramebuffers(1, fFrame, 0);
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fFrame[0]);
        GLES30.glFramebufferRenderbuffer(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_RENDERBUFFER, fRender[0]);
        LogUtils.checkFrameBuffer(TAG,GLES30.glCheckFramebufferStatus(GL_FRAMEBUFFER));

        mBuffer = ByteBuffer.allocate(mBitmap.getWidth() * mBitmap.getHeight() * 4);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES30.glViewport(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        if(mBitmap != null && !mBitmap.isRecycled()){

            clear();
            GLES30.glBindFramebuffer(GL_FRAMEBUFFER,fFrame[0]);
            GLES30.glUseProgram(program);

            // set GLSL's variable value
            GLES30.glUniformMatrix4fv(mHMatrix,1,false, mMatrix,0);
            GLES30.glUniform1i(mHTexture,0);
            GLES30.glEnableVertexAttribArray(mHPosition);
            GLES30.glVertexAttribPointer(mHPosition,2, GLES30.GL_FLOAT, false, 0,mVerBuffer);
            GLES30.glEnableVertexAttribArray(mHCoord);
            GLES30.glVertexAttribPointer(mHCoord, 2, GLES30.GL_FLOAT, false, 0, mTexBuffer);

            // bind source Texture
            GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
            GLES30.glBindTexture(GLES30.GL_TEXTURE_2D,fTexture[0]);

            GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP,0,4);
            GLES30.glDisableVertexAttribArray(mHPosition);
            GLES30.glDisableVertexAttribArray(mHCoord);

            GLES30.glReadPixels(0, 0, mBitmap.getWidth(), mBitmap.getHeight(), GLES30.GL_RGBA,
                    GLES30.GL_UNSIGNED_BYTE, mBuffer);
            LogUtils.checkError(TAG,"glReadPixels");

            GLES30.glDeleteTextures(1, fTexture, 0);
            GLES30.glDeleteRenderbuffers(1, fRender, 0);
            GLES30.glDeleteFramebuffers(1, fFrame, 0);

            if(mCallback!=null){
                mCallback.onCall(mBuffer);
            }
            mBitmap.recycle();
            mBuffer.clear();
        }
    }

    private void clear(){
        GLES30.glClearColor(1.0f,1.0f,1.0f,1.0f);
        GLES30.glClear(GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT);
    }

    interface Callback{
        void onCall(ByteBuffer data);
    }

}

I debug and get mBuffer data is :
[0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0,
-1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0,
 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0,
 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, +586,656 more]

If i replace Renderbuffer using Texture attach to FBO, after glReadPixels(), i can get data like this :
[-10, -10, -10, -1, -10, -10, -10, -1, -10, -10, -10, -1, -10, -10, -10, -1, -10, -10,
-10, -1, -10, -10, -10, -1, -10, -10, -10, -1, -11, -11, -11, -1, -11, -11, -11, -1, -11,
 -11, -11, -1, -11, -11, -11, -1, -11, -11, -11, -1, -11, -11, -11, -1, -11, -11, -11,
-1, -11, -11, -11, -1, -11, -11, -11, -1, -11, -11, -11, -1, -12, -12, -12, -1, -11, -11,
-11, -1, -11, -11, -11, -1, -11, -11, -11, -1, -11, -11, -11, -1, -11, -11, -11, -1, -11,
 -11, -11, -1, -11, -11, -11, -1, +586,656 more]

And this can show the complete render result on ImageView. Using RenderBuffer only got black view.
I think maybe this is because GLES30.glRenderbufferStorage(GLES30.GL_RENDERBUFFER, GLES30.GL_RGBA8, mBitmap.getWidth(), mBitmap.getHeight()) 's GL_RGBA8 not accepted by glReadPixels(), but i don't know how to solve this problem.

A: I'm not sure why this isn't working - it's possibly just a driver bug on the device you are using.
The solution is just to use a Texture. For all practical purposes they are the same as a Renderbuffer.


text:
Q: VBA OpenRecordset Producing Too few parameters. Expected 2. Error I have a query called qryAlloc_Source that has two paramaters under one criteria:
>=[forms]![frmReportingMain]![txtAllocStart] And <=[forms]![frmReportingMain]![txtAllocEnd])

A have a separate query that ultimately references qryAlloc_Source (there are a couple queries in between), and that query runs fine when I double click it in the UI, but if I try to open it in VBA, I get an error.  My code is:
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset("qryAlloc_Debits")

I am getting run-time error 3061, Too few parameters. Expected 2.  I've read that I may need to build out the SQL in VBA using the form parameters, but it would be pretty complex SQL given that there are a few queries in the chain.
Any suggestions as to a workaround?  I considered using VBA to create a table from the query and then just referencing that table--I hate to make extra steps though.

A: The reason you get the error when you just try to open the recordset is that your form is not open and when you try to access [forms]![frmReportingMain] it's null then you try to get a property on that null reference and things blow up. The OpenRecordset function has no way of poping up a dialog box to prompt for user inputs like the UI does if it gets this error.
You can change your query to use parameters that are not bound to a form
yourTableAllocStart >= pAllocStart
and yourTableAllocEnd <= pAllocEnd

Then you can use this function to get the recordset of that query.
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset

    Dim db As DAO.Database
    Dim qdef As DAO.QueryDef
    Set db = CurrentDb
    Set qdef = db.QueryDefs("qryAlloc_Debits")
    qdef.Parameters.Refresh
    qdef.Parameters("pAllocStart").Value = pAllocStart
    qdef.Parameters("pAllocEnd").Value = pAllocEnd
    Set GetQryAllocDebits = qdef.OpenRecordset

End Function

The disadvantage to this is that when you call this now on a form that is bound to it it doesn't dynamically 'fill in the blanks' for you.
In that case you can bind forms qryAlloc_debts and have no where clause on the saved query, then use the forms Filter to make your where clause. In that instance you can use your where clause exactly how you have it written.
Then if you want to still open a recordset you can do it like this
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset

    Dim qdef As DAO.QueryDef
    Set qdef = New DAO.QueryDef
    qdef.SQL = "Select * from qryAlloc_Debits where AllocStart >= pAllocStart and pAllocEnd <= pAllocEnd"
    qdef.Parameters.Refresh
    qdef.Parameters("pAllocStart").Value = pAllocStart
    qdef.Parameters("pAllocEnd").Value = pAllocEnd
    Set GetQryAllocDebits = qdef.OpenRecordset

End Function

A: While a [Forms]!... reference does default to a form reference when a QueryDef is run from the GUI, it is actually just another Parameter in the query in VBA.  The upshot is you don't have to recode your query/create a new one at all.  Also, as @Brad mentioned, whether a parameter is in the final query of a chain of queries or not, you are able to refer to the parameter as if it is in the collection of the final query.  That being the case, you should be able to use code similar to this:
Sub GetQryAllocDebits(dteAllocStart As Date, dteAllocEnd as Date)

    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim rst As DAO.Recordset

    Set db = CurrentDb()
    Set qdf = db.QueryDefs("qryAlloc_Debit")

    If CurrentProject.AllForms("frmReportingMain").IsLoaded Then
        qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = [forms]![frmReportingMain]![txtAllocStart]
        qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = [forms]![frmReportingMain]![txtAllocEnd]
    Else
        qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = CStr(dteAllocStart)
        qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = CStr(dteAllocEnd)
    End If

    Set rst = qdf.OpenRecordset

    Do Until rst.EOF
        '...do stuff here.
    Loop

    Set rst = Nothing
    Set qdf = Nothing
    Set db = Nothing

End Function

If the referenced form is open, the code is smart enough to use the referenced controls on the form.  If not, it will use the dates supplied to the subroutine as parameters.  A gotcha here is that the parameters did not like when I set them as date types (#xx/xx/xx#), even if the field were dates.  It only seemed to work properly if I set the params as strings.  It didn't seem to be an issue when pulling the values straight out of the controls on the forms, though.

A: I know it's been a while since this was posted, but I'd like to throw in my tuppence worth as I'm always searching this problem:
A stored query can be resolved:
Set db = CurrentDb
Set qdf = db.QueryDefs(sQueryName)
For Each prm In qdf.Parameters
    prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset

For SQL:
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "SELECT * FROM MyTable " & _
    "WHERE ID = " & Me.lstID & _
    " AND dWeekCommencing = " & CDbl(Me.frm_SomeForm.Controls("txtWkCommencing")) & _
    " AND DB_Status = 'Used'")
For Each prm In qdf.Parameters
    prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset

This assumes that all parameter values are accessible - i.e. forms are open and controls have values.

A: 'I have two parameters in my recordset and I was getting the "Too few parameters. Expected 2" 'error when using an OpenRecordset in MS Access vba, and this is how I got around it and IT WORKS! see the below sub routine:
'Private Sub DisplayID_Click()
'1. I created variables for my two parameter fields xEventID and xExID as seen below:
Dim db As Database
Dim rst As Recordset
Dim xEventID As Integer
Dim xExId As Integer

'2. Sets the variables to the parameter fields as seen below:
Set db = CurrentDb
xEventID = Forms!frmExhibitorEntry!txtEventID
xExId = Forms!frmExhibitorEntry!subExhibitors!ExID

'3. Set the rst to OpenRecordSet and assign the Set the variables to the WHERE clause.  Be sure to include all quotations, ampersand, and spaces exactly the way it is displayed. Otherwise the code will break!exactly as it is seen below:
Set rst = db.OpenRecordset("SELECT tblInfo_Exhibitor.EventID,tblInfo_Display.ExID, tblMstr_DisplayItems.Display " _
& "FROM tblInfo_Exhibitor INNER JOIN (tblMstr_DisplayItems INNER JOIN tblInfo_Display ON tblMstr_DisplayItems.DisplayID = tblInfo_Display.DisplayID) ON tblInfo_Exhibitor.ExID = tblInfo_Display.ExID " _
& "WHERE (((tblInfo_Exhibitor.EventID) =" & xEventID & " ) and ((tblInfo_Exhibitor.ExID) =" & xExId & " ));")

rst.Close
Set rst = Nothing
db.Close

'End Sub


text:
Q: Why am I getting a 502 bad gateway when sending a redirect from behind amazon elastic load balancer? I'm trying to redirect any HTTP requests to my server over to HTTPS.
ELB is listening on port 80 and forwarding all request to port 8088 on my application. The application then sends a 301 Moved Permanently response redirecting to the same URL, but with any ports stripped off and 'https://' prepended. This causes clients to re-request the url over HTTPS.
When I test it locally it works fine, but when I deploy it to EC2 behind an Elastic Load Balancer I get 502 Bad Gateway coming back. The server is receiving the request and appears to be sending the redirect correctly (as I said, it works when I hit the server directly, not via a load balancer).

A: It turns out that ELB is very picky about what it considers a 'valid' response and will return 502 Bad Gateway if it isn't happy. I fixed it by making sure the response from my server had the following headers:
eg. if I was listening at http://example.com
I send back the following response:
HTTP/1.1 301 Moved Permanently
Content-Type: */*; charset="UTF-8"
Location: https://example.com/
Content-Length: 0

This makes ELB happy and everything works.
For interest, here's the code (Java, using Simpleframework):
private static void startHttpsRedirector() throws IOException {
    org.simpleframework.http.core.Container container = new org.simpleframework.http.core.Container() {
        @Override
        public void handle(Request request, Response response) {
            Path path = request.getPath();
            Query query = request.getQuery();
            String rawHost = request.getValue("host");

            System.out.println("Raw host: " + rawHost);
            System.out.println("Raw path: " + path);
            System.out.println("Raw query: " + query);

            String host = rawHost.replaceFirst("\\:.*", "");
            response.setStatus(Status.MOVED_PERMANENTLY);
            String redirectTo = "https://" + host + path + (query.values().size() > 0 ? "?" + query : "");

            System.out.println("redirectTo = " + redirectTo);
            response.setContentType("*/*; charset=\"UTF-8\"");
            response.setValue("Location", redirectTo);
            response.setContentLength(0);
            try {
                response.commit();
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    Server server = new ContainerServer(container);
    Connection connection = new SocketConnection(server);
    SocketAddress address = new InetSocketAddress(8088);
    connection.connect(address);
}

The same code in javascript can be found here: https://gist.github.com/dhobbs/6164710


text:
Q: Django - Is there a way to configure certain url to be inaccessible from browser request? I've searched for this question but could not found an answer.
Basically, let's say i have my_app/successfully_page that i want to be displayed within the application flow. I don't want that to be displayed if some one is typing into browser the direct url.
How can i make that url page INACCESSIBLE from browser search?

A: You can do it using request.META.get('HTTP_REFERER') in order to check from which url the user is coming. If this is not the authorized url, then you can redirect the user:
if request.META.get('HTTP_REFERER') == my_url:
    # Do something...
else:
    # Redirect...

Check the doc here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META

A: I had some kind of same problem before , I solved it using sessions in the page before that set a session on the request and in the views of the url which needs to be inaccessible by direct browser set a if condition on it.
This need to be set in view of before page
request.session['is_accessible'] = True

And in the page u want to make the condition like
if (request.session['is_accessible'] == True):
        redirect("Your_page_url.html")
else:
        redirect("Page you want to show .html")

And if you are thinking that a page needs to be accessed only on login then there is a decorator in Django itself like
from django.contrib.auth.decorators import login_required

@login_required(login_url='/login.html')
def yourfunction(request):
     return Httpresponse("Your page")

And if u have more problem in it u can write an email to me at kiranu941@gmail.com

A: You have to use user agent that will let you know the perfect output.
request.META['HTTP_USER_AGENT']

But I would also recommend you to take a look at the Django User-Agents library.
You can find more relevant examples over the link.


text:
Q: PHP: equivalent of MySQL's function SUBSTRING_INDEX ? I love the SUBSTRING_INDEX function in MySQL, especially because you can use negative indexes to start searching from the right side of the string.
Is there an equivalent of this function in PHP?  (or an easy way to do it with a bit of code)

A: I think
string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

is the right php function for you.
strstr — Finds the first occurrence of a string
<?php
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

A: There's no single library function that gets you this same functionality, but you can get a one-liner:
$str = "www.mysql.com";
echo implode('.', array_slice(explode('.', $str), 0, 2)); // prints "www.mysql"
echo implode('.', array_slice(explode('.', $str), -2));   // prints "mysql.com"

Easily turn this into a function:
function substring_index($subject, $delim, $count){
    if($count < 0){
        return implode($delim, array_slice(explode($delim, $subject), $count));
    }else{
        return implode($delim, array_slice(explode($delim, $subject), 0, $count));
    }
}

A: I was curious and tested another method using a preg/match setup, then refactored it to allow for any number of delimiters/count. I added in the count check the other example was using, but I would probably also recommend some kind of sanitization of the delimiter field.
function substring_index($subject, $delim, $count){
  if($count < 0){
    $notRe = '[^\\'.$delim.']*';
    $elem = array();
    for($x=1;$x<=$count;$x++){
      array_push($elem,$notRe);
    }
    $re = '/^('.implode('\\'.$delim,$elem).')/';
    preg_match($re, $subject,$m);
    if(count($m) == 2) {
      return $m[1];
    }
  }
}

A: If you need equivalent only for SUBSTRING_INDEX(str, delim, 1), you can use:
list($str,) = explode($delim, $str);

A: function substring_index($subject, $delim, $count){
    if($count < 0){
        return implode($delim, array_slice(explode($delim, $subject), $count));
    }else{
        return implode($delim, array_slice(explode($delim, $subject), 0, $count));
    }
}


text:
Q: Error Class is public should be declared in a separate file Am getting the following error, and this error is only showing up on an auto-generated file which shouldn't be edited.
error: class CardviewAttributesBinding is public, should be declared in a file named

CardviewAttributesBinding.java
public final class CardviewAttributesBinding implements ViewBinding {

From research, I have found out that this error occurs when there are 2 public java classes in the same file. However there is no class CardviewAttributesBinding.java where I would check for more than one java class except in the auto-generated file. There is no other occurrence of that name/class/file.
Please point me so I can look in the right direction.


text:
Q: Vscode: How can I config "open new tab (editor)" keyboard shortcut? I am looking for a shortcut to open a untitled blank tab (editor) in Vscode (version 1.28.1) instead of moving the mouse and double-click the upper bound of Vscode.

A: You can open a new tab by creating a new file ("Command + n" on Mac, "Ctrl + n" on windows). The file won't be saved to disk until you do it manually.

A: You can get a list of main default short-cuts at Help/ Keyboard Shortcut Reference.
Additionally, you can find the command at View/ Command Palette. Type e.g. new and you'll see the File: New Untitle File command together with current short-cut.


text:
Q: How to get better performance out of Html 5 video via canvas? I have a video tag on my page used with the canvas element. I have been experiencing some jittery/stutter in the video. Chrome was (unexpectedly) the worst as far as play back is concerned but all of the major browsers I have tested all had difficulty playing smoothly.
Here is the code:

//This deals with drawing the video (the init is inside of a component not shown here)
function OnInit(e, f) {
  setTimeout(function() {
    var a = document.getElementById("video"),
      b = document.getElementById("canvas"),
      c = b.getContext("2d");
    a.addEventListener("loadedmetadata", function() {
      b.width = a.videoWidth;
      b.height = a.videoHeight
    });
    a.addEventListener("play", function() {
      var a = this;
      (function d() {
        a.paused || a.ended || (c.drawImage(a, 0, 0), setTimeout(d, 1E3 / 30))
      })()
    }, 0)
  }, 10)
};

//This mostly to prep the video for mobile/tablets
function mobile() {
  var a = document.getElementsByTagName("video")[0];
  navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) || navigator.userAgent.match(/Opera Mini/i) || window.matchMedia("(max-device-width: 960px)").matches ? (document.getElementById("canvas").style.display = "none", a.removeAttribute("autoplay"),
    a.removeAttribute("loop")) : a.removeAttribute("controls");
}
video {
  width: 100%;
  height: 600px;
  object-fit: fill;
  -o-object-fit: fill;
}

  <canvas id="canvas" style="width: 100%; height: 600px;"></canvas>
  <video id="video" autoplay="autoplay" controls="controls" loop="loop" poster="video.jpg" oncanplaythrough="mobile()">
    <source src="video.mp4" type="video/mp4" />
    <source src="video.webm" type="video/webm" />

  </video>

I will also note that the video sizes are about 25 MB (mp4) and 5 MB (webm). I have tried requestAnimationFrame instead of set timeout BUT I did not really see a difference (although its possible it was not implemented as well as it should have been). If anyone has any suggestions, or if there is anything I can do better I am happy to listen. Before upgrading the hardware I am looking to improve performance in the code first. Thank you.

A: it turns out (for some reason) when ever I switched the source tags in the video element around, it worked pretty good. Thank you guys for your contributions and input. Also I put in requestAnimationFrame instead of setTimeout but putting the webm video before the mp4 video seemed to do the trick.


text:
Q: Java 8 Lambda Parameter Annotations Is there any way to access the annotations of the parameters on a lambda expression? I don't see the parameters when I attempt to introspect the lambda class at runtime:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.function.Consumer;

@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation {

}

public class ParameterNameTest {
    static void printParameterName(Consumer<String> consumer) {
        System.out.println(consumer.getClass().getDeclaredMethods()[0].getParameterAnnotations()[0][0]);
    }

    public static void main(String[] args) {

        // a regular anonymous inner class
        Consumer<String> consumer0 = new Consumer<String>() {
            @Override public void accept(@TestAnnotation String foo) {

            }
        };

        // a lambda expression
        Consumer<String> consumer1 = (@TestAnnotation String foo) -> {

        };

        //prints @TestAnnotation()
        printParameterName(consumer0);

        //throws ArrayIndexOutOfBoundsException because the parameter does not exist
        printParameterName(consumer1);
    }
}


text:
Q: Tense agreement in reported speech
Jack didn't tell me that he __ my chocolate.

*

*eats

*ate

*had eaten

*has eaten

I have a hard time figuring out which one to choose and why.

A: As jwpat7 pointed out, it depends on circumstances.  Here is how you might use each tense, with examples for each tense:
Fred:

1.) "Hey, Jim, did Jack tell you he eats your chocolate?"

In this example, Fred is really informing Jim that Jack eats Jim's chocolate, even though Fred is asking a question.  We might call the questioner (Fred) a snitch, an informer, a tattletale, a talebearer, a rat--take your pick.  Jim would then say,

"No, Jack didn't tell me he eats my chocolate."

In other words, Jim is saying he was not aware of Jack's habit of eating his (Jim's) chocolate.
Fred:

2.) "Jim, did Jack tell you he ate your chocolate?"

In this example, Fred is likely (but not definitely) seeking information about something that happened in the past.  He is asking for the purpose of asking, not telling, as with example 1.  Jim would then say matter-of-factly,

"No, I didn't know Jack ate my chocolate."

Fred:

3.) "Jim, did Jack tell you he had eaten your chocolate?"

In this example, Fred is probably, as in example 2, asking Jim if he knew that Jack ate his chocolate. In other words, perhaps Jack told Fred, who saw Jack eat the chocolate when Jim was not with them,

"Hey, Fred, remind me to tell Jim I ate his chocolate, just in case I forget."

Fred says

"OK."

The next time Fred sees Jim, he says

"Hey, Jim, did Jack tell you he had eaten your chocolate?"

Jim then says,

"No, Jack didn't tell me he had eaten my chocolate."

Fred:

4.) "Jim, did Jack tell you he has eaten your chocolate?"

In this example, Fred, as in example 3, is asking Jim if he was aware of something Jack did.  Perhaps Jim, in the presence of both Jack and Fred told Jack he was free to eat all his (Jack's) chocolate at his leisure, just before Jim handed the chocolate over to Jack.  Later, when just Fred and Jim are together, Fred asks,

"Hey, Jim, did Jack tell you he has eaten your chocolate [yet]?"

to which Jim might respond,

"No, Jack didn't tell me [yet] he has eaten my chocolate.  Did he enjoy it?"

In conclusion, in each of the above examples, the tense of eat is correct, each in its own way.


text:
Q: Receiving "error: Errno 98 Address already in use" message from socket I am trying to send a message to switch through socket in python. Switch and host are created through mininet with the command like below.
sudo mn --switch ovsk --topo tree,depth=2,fanout=8 --controller=remote,ip=127.0.0.1,port=6633

In the client side, I used socket like below.
import socket
host = socket.gethostbyname("")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 6633))

message = np.random.choice(normalized_x[0], 1, replace=False)

s.send(message.encode())
s.close()

On the server side, code is like below.
host = socket.gethostbyname("")
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      s.bind((host, 6633))          # Define ip address as local host and port number
      s.listen(1)                       # Listen for incoming connection
      clt, addr = s.accept()

      c_messg = clt.recv(10240)                # Store message received from the server

      temp_msg = c_messg.decode()
      s.close()

However, whenever I execute those python files, I get an error message that is
error: [Errno 98] Address already in use

I am not sure about how to resolve this problem. Thank you for your answer in advance.

A: The error means that the Address that your server is trying to listen on is already in use by another process.
you can use
sudo lsof -i :6633
to see which process is listening on the same port
or if its doable, you can switch to a different port that is not in use.
if nothing shows up with netstat or lsof
You may want to look at Link and Link too


text:
Q: Using jQuery as a dev tool I have a lot of static pages that I want to edit in some uniform manner, rename or adding classes for example. Now, jQuery allows me to do such operations in a manner that I'm very familiar with, but on the client side. Now I would like to do this in development; pick up a static web page, change something using jquery and save it again to disk. Is there a simple way to set up jQuery (and probably node.js) to allow this?

A: You can do it using jquery for node
https://github.com/coolaj86/node-jquery
// install
npm install jquery

// usage:
var $ = require('jquery');
var inputHtml = '';

var $html = $(inputHtml);

/* change background to red */
$html.find('body').css('background-color', 'red');

/* get back html string*/
var outputHtml = $html.find('body').parent()[0].outerHTML;

console.log(outputHtml);

//console
$ node jquery-test

node-jquery is slow, and not async, do not call it directly in side http handler, but it is good for webcrawler, and offline processing.

A: You can use node.js at your server side.
More answers here: Can I use jQuery with Node.js?


text:
Q: What is the most efficient way to collect HoG descriptors (ndarrays) together for processing by Kmeans In scikit image there is a feature descriptor called HoG
The code below will calculate the descriptor for a single frame "greyVideoFrame"
HoGDescriptor = hog(greyVideoFrame, orientations=8, pixels_per_cell=(8, 8),cells_per_block=(2, 2), visualise=False)

Which returns a flattened (using ravel) nd array, below are some properties of the individual arrays
('NDarray Shape', (251328,))
('NDarray Number of Dimensions', 1)
('NDarray length of 1 array element in Bytes', 8)
('NDarray Total bytes consumed by elements', 2010624)
('NDarray DataType', dtype('float64'))

My question is how would i collate* the results from multiple frames together which would be able to handle efficiently 10,000 results of shape (251328, ) .
*I'm not sure of the correct term to use here and whether I need to append or concatenate result 1, result 2,...result 10k and would welcome the communities guidance

A: Decided to go with h5py to store the data in a format that wasn't limited to the size of RAM available


text:
Q: Review quality of code I have been asked to quality review two code bases. I've never done anything like that, and need advice on how to perform it and report it.
Background
There are two providers of code, one in VB and one in C (ISO 9899:1999 (C99)). These two programs do not work so well together, and of course, the two suppliers blames  each other. I will therefore as a independent person review both codes, on a comprehensive level review the quality of the codes to find out where it is most likely that the problem lies. I will not try to find problems, but simply review the quality and how simple it is to manage and understand the code.
Edit:
I have yet not received much information about what the problem consists of. I've just been told that I will examine the code in terms of quality. Not so much more. I do not know the background to why they took this decision.

A: For me your question sounds like a "blaming game".
Is the issue really the code quality of the two code providers or more about the interface description between the two?
Written requirements or unit tests might help to settle this kind of problems in the future:

*

*What are valid inputs/outputs what are not?

*How should error management be done?

A: If your task is not to find the actual bugs, but as you say, simply measure the quality, then you will need a way to measure it.
In C this is quite easy, you can simply check how well the code conforms to a known coding standard. The most well-known and recognized authority is probably MISRA-C, but there is also CERT C. Either can be used, though the former is more suitable for high integrity systems and the latter for PC programming. Both standards focus on banning dangerous practice.
From such a coding standard you can pick a number of rules that should be part of the review. For example, it would make a lot of sense to include all MISRA-C rules that ban reliance on undefined behavior. As a result, you should get a number of rules which can be used as a mean to measure quality.
Then comes the actual review. You would certainly need to do it manually, but the professional way would be to also use a static analysis tool. There are plenty of them supporting MISRA-C, and some supporting CERT C. The fancier tools can also find various other bugs such as data anomalies, buffer overruns, needless complexity etc ect. They can also perform code coverage, to see if there is any code in the program that will never be executed.
As for VB, that is far harder. There is probably no widely-recognized authority you can cite, although there are perhaps coding standards you can use, maybe this one? (found it in Google, I've never used it). Microsoft would be the best authority to cite, they seem to have some vague, shallow guidelines for how to write VB, but those won't be anywhere near as professional as the C coding standards.

A: Drop that "background" out of your head - it's useless for the assignment you've got.
For both programs, do the same: read the code, file by file, line by line. Anything that doesn't feel right, add it to the list of issues. Typos, duplicate or dead code, things that are hard to understand, IDE/compiler warnings, anything. Use free form comments, don't worry about the structure at this moment, just fill the list with what catches your attention.
After done with the list, review it. Re-check if your notes are correct. If you can see some sort of structure / grouping in the issues you noticed, rearrange the list to fit. Submit the list to whoever asked you about it.

At past project, my colleague has been told to review a component I was assigned to maintain, 5 or 10 K LOC if memory serves. He went over it and submitted a list of 180 items (one hundred eighty issues noticed). Week later, management gave me a full power and unlimited time to rework that component. I spent about a month, addressed all the items that guy listed. Five years of intensive use that passed after review, there were two or maybe three bugs submitted against this component.

A: Sounds to me like what you really need is some instrumentation to sit between the to applications and spy on what messages they are passing each other (depending on how they communicate this may be something you need to write your self or something already available like wireshark)
once you can see the messages you can decide who is right and who is wrong compared to the interface spec. of course its possible the spec is ambiguous in which case you either need to fix the spec (and possibly incur more costs for changes to one of the components) or convert your spy tool into a compatibility shim
reviewing their code is certainly not without its merits but it will not help you trace interface issues (especially if the spec is wrong)

A: (Regarding the code, just dive in - it is the only way to learn it).
I would suggest you look into having an API for the two parties to work across (a contract essentially).  If they conform to the API then the code should work together.
Very much like how it is done with a WSDL in the Web Service world.
If at all possible then have a test suite on the API so you can see that stuff works.  Otherwise you can play the blame tag game for years.

A: Doing code reviews in a way which is acceptable for all parties involved is hard. A good process will help, as well as an objective standard, which together ensure the review is verifiable and repeatable. Also, analysis and getting the technical facts is one, reporting in a way that resolves the problem situation, including managing the different perspectives, positions, feelings, is another.
Visual inspection and making a list of all things that are wrong with the code is typically only a good idea there are no time and budget constraints or the code base is really small. Otherwise, the inspections themselves might just be too much work, or the corrections that you would suggest could be too time consuming to perform. Please keep this in mind when you come with recommendations.
What research questions does your client have for the code review and what will be done with the results?

A: How much time have you been allocated - unless is rough order off magnitude is 20% - 50% of the development time for the apps you are reviewing, you are wasting your time and performing a political exercise to make someone feel good about it.
Most of the suggested things to look for are (although the best we know of) an inaccurate way to determine software quality, and very unlikely to standup up to rigorous scrutiny. Consider what you write in your report carefully - you may end up having to defend it in a witness box - how far is this dispute going to go, and how much money is at stake, are the parties wanting to find resolution or blame?
Assuming you are a programmer, not a forensic analyst with a programming specialization (In which case you would know not to have asked this question in a public forum), if I was you I would refuse the assignment in the strongest way I could. You are being set up to take a fall - playing software vendors off against each other with nothing but your opinion..... If one of those vendors finds this Q&A, how will that make you look....
Before you complete you report, you will need to be certain what it is going to be used for. Make sure it is phrased with statements such as "it appears" and "I believe" rather than absolutes such as "the code is crap". If you must make assertions - reference to published and widely accepted standards will be required. e.g. "The code does not meet the standards specified in the MISRA guidelines for C" is a fact, but stating that is should meet those guidelines would not be (unless your contract said so or they claimed it did).

A: It really depends on what they want and mean by code quality.
But in general, your goal would be to give a review of how the code fares in terms of:

*

*ease of maintainability and extensibility,

*stability and security,

*performance.

Pretty much most of the metrics fall under these porte-manteau categories (actually, I'd not even consider performance in general, and consider it most of the time as a bonus side-effect of good scores in terms of stability and maintainability, hence good code design).
There are some more absolute things to look for, like code certifications that can be directly applied and measured on some codebases, but they don't necessarily give a fine-grained review of these categories.
I'd advise you:

*

*open an IDE and start browsing the code,

*put breakpoints to know what happens at runtime and identify interesting cross-cutting concerns and major bottlenecks,

*find some code checkers and have them flag violations and identify "hotspots" in your codebase,

*do some profiling on the application to identify bottlenecks,

*also have a look at the tooling used and the system's build (not what they directly asked, but some can be inferred from that, and it can help to identify other issues),

*define process and practices to then start improving the metrics you identified, and explain how that will benefit the codebase, the developers, and the end product.

I know you tagged vb, but just to give you an example, Sonar would be a good example of a tool that can greatly help you quantifying the quality of a code base in many regards, from code quality from a technical point of view or even from a business perspective, by linking (more or less accurately) some markers to business costs. You want to find an equivalent tool, or a set of tools allowing you to achieve similar results, in your area. Sonar does have a C plugin, if you want, and I'm pretty sure Visual Studio has a few good code quality analyzers built-in or external, for VB.

A: Roll a 6 sided die. 1-3 is the VB code, 4-6 is the C code. Take a 2 month vacation and tell everyone which code is bad after you return. You are in a political fight it would appear.
Or better yet, tell them you are going to review the code, but don't. Come back with working fixes to both sets of code that allow them to work together.


text:
Q: xliff-file vs. database translations Currently i have not a code-problem, but i dont know which way would be better for me.
For our project, we have two kind of data which would be translatet for the view.
The part, which be coded in the source code like system messages (e.g. You are logged in, log out, etc.)
The second part is the database content like services, there can be added or deleted rows. And not for every entity would be a translation available.
Now i need to know, if i should save and get the translation from a translation table or is it better to transfer (via script) the translation into a services.xliff file

A: I would suggest to use XLIFF or GetText for the application (source: php, js).
Especially http://jmsyst.com/bundles/JMSTranslationBundle might be helpful.
The storage mechanism is less important, because of caching. So feel free to use either a DB or files as backend.
User created content is often managed via database. So you might use a common DoctrineExtension, like translateable. http://symfony.com/doc/current/cookbook/doctrine/common_extensions.html
https://github.com/stof/StofDoctrineExtensionsBundle/blob/master/Resources/doc/index.rst


text:
Q: Mutable array/list memory size If I recall correctly, the initialization of a fixed array with a length of 8 of object type int will reserve a memory block the size of (8 * size_of_int) at compile time.
How does memory management work for initialization of dynamic/mutable arrays, whose length can change at run time?

A: Change length of array at the run time called dynamic memory allocation. When you need to increase the size of array, the System will release the previous memory and allocate the new memory for new length and assign the first element address into your pointer variable.
You can read more about Dynamic memory allocation here: https://en.wikipedia.org/wiki/C_dynamic_memory_allocation


text:
Q: How to set up multi finger gesture control in 20.04 How can you setup Multi-finger (3 and 4 finger specially) gesture controls in Ubuntu 20.04? I am new and this is my 1st question.

A: Try Fusuma. It worked for me. https://github.com/iberianpig/fusuma


text:
Q: Xpages - Remove selected items from an array Does anyone know how to remove selected items from an array?
var view:NotesView = getComponent("viewPanel2");
var UtbildningarArray = new Array();
viewScope.col = view.getSelectedIds();
if (viewScope.col.length > 0){
for (i=0; i<viewScope.col.length; i++){
    var docid = viewScope.col[i];
        if (docid != null) {
            var doc = database.getDocumentByID(docid);
            UtbildningarArray.push(doc.getItemValueString("Namn"))
        }
    }
}
document1.removeItemValue("Utbildningar",UtbildningarArray);
document1.save();

I have tried, removeEntry and splice but I don't get it work.
Thanks,
Jonas
Edit:
You are right, have added this in the code:
var view:NotesView = getComponent("viewPanel2");
var UtbildningarArray = new Array();
var UtbildningarArray = new Array();
var FieldUtbArray = new Array(getComponent('inputHidden1').getValue());

viewScope.col = view.getSelectedIds();
if (viewScope.col.length > 0){
    for (i=0; i<viewScope.col.length; i++){
        var docid = viewScope.col[i];
            if (docid != null) {
                var doc = database.getDocumentByID(docid);
                UtbildningarArray.push(doc.getItemValueString("Namn"))
            }
        }
    }

document1.replaceItemValue("Utbildningar",FieldUtbArray.slice(UtbildningarArray));
document1.save();

I'm saving what the user selected in a hidden input, and when the user clicks the "Remove programs" button I display the selected courses in the view. Then should the user be able to click a checkbox and remove the selected course(s). Now when I save nothing happens.

A: I think you need to show more what you want to remove.
Below you have to code snippets that will remove an entry from an js array.
http://openntf.org/XSnippets.nsf/snippet.xsp?id=remove-an-entry-from-an-array-of-strings
http://dontpanic82.blogspot.se/2010/10/code-snippet-arraysplice-according-to.html

A: I got it work!
for (var i = 0; i < FieldUtbArray.length; i++) {
    found = false;
    // find a[i] in b
    for (var j = 0; j < UtbildningarArray.length; j++) {
        if (FieldUtbArray[i] == UtbildningarArray[j]) {
            found = true;
            break;
        }
    }
    if (!found) {
        result.push(FieldUtbArray[i]);
    }
}


text:
Q: How can I determine the "caller" of my method in Objective-C? So I have a rather complex application that I've, perhaps naively, agreed to "debug".  Upon entering into a certain method, I'd like to print out as much info about who called the method, from which class, method, etc. it was called from. Any suggestions would be very much appreciated!!

A: Just add in your method:
NSLog(@"Show stack trace: %@", [NSThread callStackSymbols]);

A: For debugging you could use a debugger :) put a breakpoint in the method and view the backtrace.
You could also scatter NSLog statements with relevant information in methods.


text:
Q: Twig - Why are vars defined as false become empty? Define a twig var as true, and it has a value of '1'.
Define another var as false, and it has no value. Why is that?
{% set myOtherVar = true %}
{{ myOtherVar }}

This outputs '1'
{% set myVar = false %}
{{ myVar }}

This outputs nada
https://twigfiddle.com/ebbwgf
This is bothersome because simple logic like this fails:
{% set myVar = false %}
{% if myVar is not empty and not myVar %}
stuff
{% endif %}

A: Because you are using set to set the variable as a boolean. So you need to use it as a boolean. You can't print the value.
You might do your logic something like this:
{% set myOtherVar = true %}
{% set myVar = false %}

{% if not myVar %}
myVar is false
{% endif %}

{% if myOtherVar %}
myOtherVar is true
{% endif %}

Here is a twigfiddle showing it working properly:
https://twigfiddle.com/yxt1jd
Hope that helps!

A: false is equivalent to '' for empty:
{% set myVar = '' %}
{% if myVar is empty %}
    stuff
{% endif %}

{% set myOtherVar = false %}
{% if myVar is empty %}
    other stuff
{% endif %}

https://twigfiddle.com/5g9thl
Depending on what you want to do, you can test if the variable exists with defined:
{% set myVar = false %}
{% if myVar is defined and not myVar %}
stuff
{% endif %}

https://twigfiddle.com/m1n1q0


text:
Q: Compress multiple HTML pages using tree encoding I noticed that Huffman Coding can be used to compress strings by creating a tree.
But I was wondering.. could this also be applied to HTML pages?
Imagine you want to compress a whole domain, or pages over time. A lot of nodes will be repeating over time (as pages don't change), and a lot of pages contain overlapping nodes. At different heights in their trees.

   menu

some

some

another

The example HTML can perhaps create an element out of each HTML node (the
some
 occuring twice), perhaps the whole
 could be expressed as a single element, or perhaps it even pays off to encode this whole text as a single element if there are more pages that contain this exactly.
So I was wondering how can Huffman Coding be applied to this problem?


text:
Q: Sinatra Heroku app: `start_server': undefined method `run' for HTTP:Module (NoMethodError) So I've been trying all sorts over the past couple of hours hoping I could fix this, but I've caved and have to ask for some help...
I'm trying to deploy a Sinatra-based app to Heroku using PostgreSQL with Datamapper.
Restarting the dyno hasn't helped, and it works fine locally using Shotgun (which appears to be WEBrick 1.3.1).
The Heroku logs:
2014-09-15T00:44:16.620710+00:00 heroku[web.1]: State changed from crashed to starting
2014-09-15T00:44:18.868126+00:00 heroku[web.1]: Starting process with command `bundle exec ruby app.rb -p 55219`
2014-09-15T00:44:21.353588+00:00 app[web.1]: /app/vendor/bundle/ruby/2.1.0/gems/sinatra-1.4.5/lib/sinatra/base.rb:1497:in `start_server': undefined method `run' for HTTP:Module (NoMethodError)
2014-09-15T00:44:21.353629+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.1.0/gems/sinatra-1.4.5/lib/sinatra/base.rb:1435:in `run!'
2014-09-15T00:44:21.353657+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.1.0/gems/sinatra-1.4.5/lib/sinatra/main.rb:25:in `block in <module:Sinatra>'
2014-09-15T00:44:22.014311+00:00 heroku[web.1]: State changed from starting to crashed
2014-09-15T00:44:22.005268+00:00 heroku[web.1]: Process exited with status 1
2014-09-15T00:44:23.532489+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=glacial-retreat-7648.herokuapp.com request_id=df6fe1b9-9868-49b0-83e1-fc57dd1c3e63 fwd="86.161.84.51" dyno= connect= service= status=503 bytes=

Parts of app.rb:
require 'sinatra'
require 'data_mapper'
require 'twitter'

...

configure :development do
    DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")
end

configure :production do
    DataMapper.setup(:default, ENV['HEROKU_POSTGRESQL_BLUE_URL'])
end

...

DataMapper.finalize.auto_upgrade!

Gemfile:
source 'http://rubygems.org'
ruby '2.1.2'

gem 'sinatra'
gem 'twitter'

gem 'dm-aggregates'
gem 'dm-constraints'
gem 'dm-core'
gem 'dm-migrations'
gem 'dm-serializer'
gem 'dm-timestamps'
gem 'dm-types'
gem 'dm-validations'

gem 'data_mapper'

group :development do
    gem 'sqlite3'
    gem 'dm-sqlite-adapter'
    gem 'do_sqlite3'

end

group :production do
    gem 'pg'
    gem 'do_postgres'
    gem 'dm-postgres-adapter'
end

config.ru:
require './app'
run Sinatra::Application

Procfile:
web: bundle exec ruby app.rb -p $PORT

database.yml:
development:
  adapter: postgresql
  host: localhost
  username: user
  database: development

If you have any thoughts whatsoever, I'd be extremely grateful for your help.
Thank you.


text:
Q: How to output dependency walker to the console? Fairly straightforward question, but I can't seem to find if this is an option in their command line help. Is there anyway to output the contents of the dependency walker directly to the console?
Yes, I'm aware that you can specify it to output to a file and then I can parse the file, however that takes a bunch of time that I would rather avoid.
I'm not necessarily worried about how "ugly" it looks in the console. I can programmatically search what I want from the output pretty quickly, just need to know if this is possible.
Thanks in advance if you can offer any advice!

A: Dependencies is a modern replacement for dependency walker. It contains both a GUI tool and a console app (dependencies.exe), which dumps as you require. It supports the following options:
Dependencies.exe : command line tool for dumping dependencies and various utilities.
Usage : Dependencies.exe [OPTIONS] FILE

Options :
  -h -help : display this help
  -json : activate json output.
  -apisets : dump the system's ApiSet schema (api set dll -> host dll)
  -knowndll : dump all the system's known dlls (x86 and x64)
  -manifest : dump FILE embedded manifest, if it exists.
  -sxsentries : dump all of FILE's sxs dependencies.
  -imports : dump FILE imports
  -exports : dump  FILE exports
  -modules : dump FILE resolved modules
  -chain : dump FILE whole dependency chain


text:
Q: Haskell List of Data Type Sorting I got a custom Data type named Student which has marks for 2 subjects. I have created a function named average that calculates the average of two. All work fine.
My question is how can I sort list of students by their average?
data Student = Student
    {studentName :: String,
     subject1 :: Double,
     subject2 :: Double} deriving (Show)

average :: Student -> Double
average (Student _ sub1 sub2) = (sub1 + sub2) / 2

students :: [Student]
students = [Student "Dave"  50.0  40.0,
            Student "Joe"   65.0  90.0,
            Student "Ann"   75.0  82.0]

P.S. I am a beginner in Haskell and don't know whether its got a
 inbuilt average function but I prefer if I can sort my list in similar
 way without using inbuilt average function (if it is there) as this
 small test solution to be use with a different type of function
 instead average.

A: import Data.Function (on)
import Data.List (sortBy)

studentsSortedByAverage = sortBy (compare `on` average) students

Note that those are backticks around on, not single quotes.
Here are links to docs for sortBy and on.

If you are using an old compiler that doesn't come with Data.Function, here is the definition of on:
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(.*.) `on` f = \x y -> f x .*. f y


text:
Q: Perl Net::SSH2 scp_put returns unknown error I am using Net:SSH2 to put file on a remote server with scp_put.
It returns unknown error:

-43, LIBSSH2_ERROR_UNKNOWN(-43), SCP failure

It seems that the error comes after some timeout/delay, as it takes several minutes to return.
Connection to sftp-server is working. I can get a directory list from the directory.
I have access rights to that directory as I can put files there with SFTP-client.
I am using Strawberry Perl in Windows environment.
use warnings;
use strict;
use Net::SSH2;

my $dir1 = '.';
my $file = 'D:\\test\\test.txt';
my $ssh2 = Net::SSH2->new();
$ssh2->connect('testserver') or die "Unable to connect Host $@ \n";
$ssh2->auth_password('test','test') or die "Unable to login $@ \n";

if($ssh2->scp_put($file, $dir1)) {
            print "File $file transferred to $dir1\n";
} else {
            print "Couldn't transfer file $file to $dir1\n";
            print join ', ', $ssh2->error;
            print "\n";
}

A: SCP support in libssh2 is quite rudimentary and buggy.
Better alternatives are Net::SSH::Any which has a proper pure-perl implementation of SCP or Net::SFTP::Foreign for SFTP. Both can work on top of Net::SSH2.


text:
Q: Excel, Create a named range from the contents of cells usign cell formulas I am stuck...
I have a 100 Row sheet with 10 Columns.  This list is broken into classes simply by inline headers. I have definitions of the blocks of data under each head, for example:
UNASSOCIATED  A2  A19
HOSTS   A21   A32
ROOF    A34  A100
I compute those ranges as they may change from time to time. I need
first: Define Name of each group by formula
Second: From time to time select the defined group
I am unable to get a formula to work which will allow me to use the "Content" of the cell as opposed to the cell location to define these ranges.
I'm stuck.
Suggestions would be appreciated.
Regards,
RHD

A: This cannot be done in a cell formula. You'll need to create a macro (VBA) to do this. Essentially, what you need is to grab the value of a cell then use that value as if it were a cell address.
Take a look at the example macro below. If cell A1 contains the characters "B22", then x will become the value of A1 (which is "B22") and "test" will be written to cell B22. This cannot be done in with cell formulas.
Sub test()
    Dim x As String
    x = Range("A1").Value
    Range(x).Value = "test"
End Sub

A good amount of adaptation will been needed to incorporate this technique, and you'll need to play with this a bit. Ping this community to help answer more specific questions as they come up.


text:
Q: React Script Test not terminate after tests have been completed I try to run npm test in Github Action, but it just stuck there forever. I can see that the tests are completed successfully in very short time, so I have no idea why it is not terminating
This is the test script in package.json
"test": "react-scripts test --watchAll --coverage --forceExit --transformIgnorePatterns \"node_modules/(?!axios)/\"",

A: You can try removing the --watchAll flag from the test script to see if that helps. The script should then run the tests once and exit when they are completed.
It's possible that the --watchAll flag is causing the test script to stay running indefinitely.


text:
Q: Equivalent of PostMethod of Java in PHP I would like to ask if there exists a PHP function to simulate this block of code in Codeigniter.
HttpClient httpClient       = new HttpClient();
PostMethod postMethod       = new PostMethod(requestURL);
NameValuePair[] datas       = {new NameValuePair("studentnumber", studentnumber),
                              new NameValuePair("studentdata", encryptedData)};

postMethod.setRequestBody(datas);
int statusCode      = httpClient.executeMethod(postMethod);
byte[] responseByte = postMethod.getResponseBody();
String responseBody = new String(responseByte, "UTF-8");

curl doesn't seem to work, while $this->output->set_output passes the data properly but fails to catch the response of the requestUrl.
Thank you.

A: I was able to catch the response from requestUrl using this block of code that I found on HTTP POST from PHP, without cURL (thanks a lot for this).
$options = array(
    'http' => array(
        'method' => "POST",
        'header' => "Accept-language: en\r\n" . "Content-type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query(array(
            'studentnumber' => $studentnumber,
            'studentdata' => $encryptedData,
        ),'','&'
    )
));

$refno = file_get_contents($requestUrl,false,$context);


text:
Q: Full outer join on two multiindex dataframes (one with multi level columns) not working properly pandas Using Python 3.8, pandas 1.1.2
I have two dateframes with multiindex
df1 (multi level column):
                       user      price
                       count     sum
name    date    hour
  A      9/17    1       33       34
  A      9/17    2       66       55
  A      9/17    3       77       2
  A      9/17    4       88       1

df2:
                       seller_count
name    date    hour
  A      9/17    1        100
  A      9/17    15        66

I am trying to do full outer join on two of them.
Desired output:
                       user      price
                       count     sum        seller_count
name    date    hour
  A      9/17    1       33       34            100
  A      9/17    2       66       55            null
  A      9/17    3       77       2             null
  A      9/17    4       88       1             null
  A      9/17    15     Null     Null           66

I am trying to find out a way to do this without resetting indexes. Any help? Thanks!
solution from Pandas Dataframe Multiindex Merge does not seem to work, I am only able to get seller_count if it has same name, date,hour as df1.
df1.columns outputs:
MultiIndex([(          'user',    'count'),
            (           'price',    'sum')])

df2.columns outputs:
Index(["seller_count"])

A: Setup:
print (df1.index)
MultiIndex([('A', '9/17', 1),
            ('A', '9/17', 2),
            ('A', '9/17', 3),
            ('A', '9/17', 4)],
           names=['name', 'date', 'hour'])

print (df1.columns)
MultiIndex([( 'user', 'count'),
            ('price',   'sum')],
           )

print (df2.index)
MultiIndex([('A', '9/17',  1),
            ('A', '9/17', 15)],
           names=['name', 'date', 'hour'])

print (df2.columns)
Index(['seller_count'], dtype='object')

First is necessary create MultiIndex in df2, then use merge with outer join:
df2.columns = pd.MultiIndex.from_product([[''], df2.columns])

print (df2.columns)
MultiIndex([('', 'seller_count')],
           )

df = df1.merge(df2, left_index=True, right_index=True, how="outer")
print (df)
                user price
               count   sum seller_count
name date hour
A    9/17 1     33.0  34.0        100.0
          2     66.0  55.0          NaN
          3     77.0   2.0          NaN
          4     88.0   1.0          NaN
          15     NaN   NaN         66.0

df = df1.join(df2, how="outer")
print (df)
                user price
               count   sum seller_count
name date hour
A    9/17 1     33.0  34.0        100.0
          2     66.0  55.0          NaN
          3     77.0   2.0          NaN
          4     88.0   1.0          NaN
          15     NaN   NaN         66.0

print (df.columns)
MultiIndex([( 'user',        'count'),
            ('price',          'sum'),
            (     '', 'seller_count')],
           )

print (df.index)
MultiIndex([('A', '9/17',  1),
            ('A', '9/17',  2),
            ('A', '9/17',  3),
            ('A', '9/17',  4),
            ('A', '9/17', 15)],
           names=['name', 'date', 'hour'])

A: I assume that column names in the index in df1 are of "single level".
You can achieve it the following way:

*

*The source file contains:
name,date,hour,user,price
 , , ,count,sum
A,9/17,1,33,34
A,9/17,2,66,55
A,9/17,3,77,2
A,9/17,4,88,1

Note spaces as first 3 column names at the second level.

*Read the file executing:
df1 = pd.read_csv('Input_1.csv', header=[0,1])
df1 = df1.set_index([('name', ' '), ('date', ' '), ('hour', ' ')])\
    .rename_axis(index=['name', 'date', 'hour'])

This way "2-level" column names, after setting as the index, get single
level names.
Another detail to note is that:

*

*index column names in both DataFrames are of single level,

*df1 has a MultiIndex on columns,

*df2 has an ordinary (single level) index on columns,

*the result should have MultiIndex on columns.

To perform the join, you have to start from adding a MultiIndex level
to the column index in df2 (with a space as the top level):
df2.columns = pd.MultiIndex.from_product([[' '], df2.columns])

Then perform ordinary outer join:
result = df1.join(df2, how='outer')

The result is:
                user price
               count   sum seller_count
name date hour
A    9/17 1     33.0  34.0        100.0
          2     66.0  55.0          NaN
          3     77.0   2.0          NaN
          4     88.0   1.0          NaN
          15     NaN   NaN         66.0


text:
Q: What does "in a wide range" mean? Does it mean "in many forms"?
"In the 2004-2006 cycle, long-term yields rose before the Fed hiked rates as investors anticipated the changes, but then fell after the actual increase in the Fed funds rate began. In the current cycle, 10-year Treasury bond yields have traded in a wide range since the Fed first began to move the Federal funds rate above zero in December 2015. Yet despite three rate hikes, bond yields are about where they were when the cycle began."
Source: http://www.businessinsider.com/3-reasons-to-own-bonds-when-the-fed-is-raising-rates-2017-4

A: This range is about trading range. It's a common term in trading markets (e.g., stock trading, bond trading, future trading, commodity trading).
I'll assume that you know the basics of trading, how it's like trading stocks, bonds, and so on, in a market. The price of a stock or bond always moves.
The most important price data for traders are Open, Close, High, and Low, along with other data such as Volume. The data may be daily, weekly, monthly, quarterly, yearly, or any length of time.
Range is the difference (also known as spread) between the High (i.e., highest price) and Low (lowest price) traded in a given period of time.
So, when something has been traded in a wide range, it means that the difference between the highest and lowest price points in that period of time is large.


text:
Q: C# adding dynamic variables in loop It's a pretty rookie question.
Here is my code
double jury;
jury = double.Parse(Console.ReadLine());
for (int i = 0; i < jury ; i++)
{
    Console.ReadLine();
}

How can I define the input inside the loop so I can use the input data from the additional inputs for math calculations.
It's a vote system and the first variable is the jury count - each jury member votes for a number 1-10. The idea is that the jury is dynamic from 1 to 100,000. Any ideas are welcome.
More: Here is the idea.
-> When you have for example 3 jury members
-> You input 3 on the first row
-> You get 3 new inputs where your jury vote for candidates ( numbers 1 to 10 )
-> In this case the votes are 1, 3, 3
The idea is to parse all this information and output the winner which in our case is "3".

A: You can use List<T> to store votes; IMHO int looks better than Double in your task
Console.WriteLine("Enter number of jurors, please");

int jury;

if (!int.TryParse(Console.ReadLine(), out jury)) {
  Console.WriteLine("Incorrect jury number format");

  return; // <- I'd exit on the first error occured; you may adopt different policy
}
else if ((jury < 1) || (jury > 100000)) {
  Console.WriteLine("Jury should be in range [1..100000]");

  return;
}

var List<int> = new List<int>();

for (int i = 0; i < jury; ++i) {
  int vote;

  Console.WriteLine("Enter next vote, please");

  if (!int.TryParse(Console.ReadLine(), out vote)) {
    Console.WriteLine("Incorrect vote format");

    return;
  }
  else if ((vote < 1) || (vote > 10)) {
    Console.WriteLine("Each vote should be in range [1..10]");

    return;
  }

  votes.Add(vote);
}

A: This code prompts for a number of jurors and validates the input. Then, it prompts for each juror's vote, validating the vote input.
const int minimumVote = 1;
const int maximumVote = 10;
int jurorCount;

do
{
    Console.Write("Enter the number of jurors: ");
} while (!Int32.TryParse(Console.ReadLine(), out jurorCount) || jurorCount < 0);

var votes = new List<int>();

for (int i = 0; i < jurorCount; i++)
{
    int vote;

    do
    {
        Console.Write("Enter juror #{0}'s vote ({1}-{2}): ", i + 1, minimumVote, maximumVote);
    } while (!Int32.TryParse(Console.ReadLine(), out vote) || vote < minimumVote || vote > maximumVote);

    votes.Add(vote);
}

A: Use a List or Array
var values = new List<double>();
for (int i = 0; i < jury; i++)
{
    double current;
    if (double.TryParse(Console.ReadLine(), out current))
    {
       values.Add(current);
    }
    else
      i--;
}


text:
Q: Html to Word long document I can create an extensive word document using html including a cover page, header & footer, page numbers etc.
But my problem is; when my document is too long (like 100 pages or more) and I open the doc with Word 2003:

*

*the document can be loaded and I can see the cover page.

*but when I try to scroll down a little bit to examine the report, Word starts a long lasting process ( I don't know what it is) and does not respond.

*if the doc is about 60 pages, the process lasts about 5 min. And then I can navigate through the document.

I have tried the following:

*

*Disabled Spelling and Grammar check

*Disabled auto-save

Is there anyone with a similar experience? I am creating the document with html and a few vml tags embedded in the document. What can be the cause of this unresponsive behavior?

A: Word is not created for handling large documents. There are several places where behavior is not O(n log n) (with n length of the document). You need to at least disable page numbering.
If you really want to find out: create some test cases and find out:

*

*start with a plain text only, nothing fancy at all, generate a 100 pages and see if the problem persists.

*step by step add features until the problem surfaces (fastest is to halve the feature difference).

*it is likely that there are more features than just one leading to these performance problems, so you have to be careful with the application of Newton's method

And when you know, tell us.


text:
Q: What is the Storable module used for? I am having a hard time understanding what Storable does.
I know that it "stores" a variable into your disk, but why would I need to do that? What would I use this module for, and how would I do it?

A: One example:
Your program spends a long time populating your data structure, a graph, or trie, and if the program crashes then you'd lose it all and have to start again from square one. To avoid losing this data and be able to continue where it stopped last time you can save a snapshot of the data to a file manually or just simply use Storable.

A: Reasons that spring to mind:

*

*Persist memory across script calls

*Sharing variables across different processes (sometimes it isn't possible to pipe stuff)

Of course, that's not all that Storable does. It also:

*

*Makes it possible to create deep clones of data structures

*Serializes the data structure stored, which implies a smaller file footprint than output from Data::Dump

*Is optimized for speed (so it's faster to retrieve than to require a file containing Data::Dump output


text:
Q: How Do I Enable My Ubuntu Server To Host Various SSL-Enabled Websites? Actually, I Have looked around for a few hours now, but I can't get this to work. The main problem I'm having is that only one out of two sites works.
I have my website which will mostly be used for an app. It's called atajosapp.com .
atajosapp.com will have three main sites:

*

*www.atajosapp.com <- Homepage for the app.

*auth.atajosapp.com <- Login endpoint for my API (needs SSL)

*api.atajosapp.com <- Main
endpoint for my API (needs SSL).

If you attempt to access api.atajosapp.com it works. It will throw you a 403 error and a JSON output, but that's fully intentional.
If you try to access auth.atajosapp.com however, the site simply doesn't load. Chrome complains with:
The webpage at https://auth.atajosapp.com/ might be temporarily down or it may have moved permanently to a new web address.
Error code: ERR_TUNNEL_CONNECTION_FAILED
But the website IS there.
If you try to access www.atajosapp.com or any other HTTP site, it connects fine. It just doesn't like dealing with more than one HTTPS websites, it seems.
The VirtualHost for api.atajosapp.com looks like this:
<VirtualHost *:443>
    DocumentRoot /var/www/api.atajosapp.com
    ServerName api.atajosapp.com
    SSLEngine on
    SSLCertificateFile /certificates/STAR_atajosapp_com.crt
    SSLCertificateKeyFile /certificates/star_atajosapp_com.key
    SSLCertificateChainFile /certificates/PositiveSSLCA2.crt
</VirtualHost>

auth.atajosapp.com Looks very similar:
<VirtualHost *:443>
    DocumentRoot /var/www/auth.atajosapp.com
    ServerName auth.atajosapp.com
    SSLEngine on
    SSLCertificateFile /certificates/STAR_atajosapp_com.crt
    SSLCertificateKeyFile /certificates/star_atajosapp_com.key
    SSLCertificateChainFile /certificates/PositiveSSLCA2.crt
</VirtualHost>

Now I have found many websites that talk about possible solutions. At first, I was getting a message like this:
_default_ VirtualHost overlap on port 443, the first has precedence

But after googling for hours, I managed to solve it by editing both apache2.conf and ports.conf. This is the last thing I added to ports.conf:
<IfModule mod_ssl.c>
NameVirtualHost *:443
    # SSL name based virtual hosts are not yet supported, therefore no
    # NameVirtualHost statement here
    NameVirtualHost *:443
    Listen 443
</IfModule>

Still, right now only api.atajosapp.com and www.atajosapp.com are working. I still can't access auth.atajosapp.com. When I check the error log, I see this:
Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)

I don't know what else to do to make both sites work fine on this. I purchased a Wildcard SSL certificate from Comodo that supposedly secures *.atajosapp.com, so after hours trying and googling, I don't know what's wrong anymore.
Any help will be really appreciated.
EDIT: I just ran the apachectl -t -D DUMP_VHOSTS command and this is the output. Can't make much sense of it...:
root@atajosapp:/# apachectl -t -D DUMP_VHOSTS
apache2: Could not reliably determine the server's fully qualified domain name, using atajosapp.com for ServerName
[Thu Nov 07 02:01:24 2013] [warn] NameVirtualHost *:443 has no VirtualHosts
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:443                  is a NameVirtualHost
         default server api.atajosapp.com (/etc/apache2/sites-enabled/api.atajosapp.com:1)
         port 443 namevhost api.atajosapp.com (/etc/apache2/sites-enabled/api.atajosapp.com:1)
         port 443 namevhost auth.atajosapp.com (/etc/apache2/sites-enabled/auth.atajosapp.com:1)
*:80                   is a NameVirtualHost
         default server atajosapp.com (/etc/apache2/sites-enabled/000-default:1)
         port 80 namevhost atajosapp.com (/etc/apache2/sites-enabled/000-default:1)


text:
Q: Ruby; Can a string be parsed so that `2016-12-01` is a day, and `2016-12-01T12:05` is a minute? Using vanilla Ruby (or Rails, but prefer vanilla Ruby),
Supposing custom classes are created by us: Year, Month, Day, Hour, Minute, Second, Millisecond
With these classes, they relate to a specific hour, minute, second, etc.
Example: thisMinute = Minute.new("2016-12-01T12:05") => Minute 5 of hour 12 of day 1 of month 12 of year 2016

Can a function be created so that
foo("2016") can create an instance of the Year Class
foo("2016/12") can create an instance of the Month Class
foo("2016-12-01") can create an instance of the Day Class
foo("2016-12-01T12:05") can create an instance of the Minute Class
and so-on?
Here are the gotchas

*

*The time format may vary ("20161201" or "20161201@12pm" for example)

*With these formats, Time.parse will successfully parse the string, but will set Month, Day, Hour, etc so that "20161201" would have a value set for Hour, even though it should be a Day.

*Checking for == 0 (as in Time.parse().hour == 0) would fail as the time could be "2016-12-01@12am"

A: One possible way would be to have a parse method for each class.  stftime is used to pull specific parts of a time stamp out
a = '2016-12-01T12:05'
=> "2016-12-01T12:05"
b = DateTime.parse(a)
=> #<DateTime: 2016-12-01T12:05:00+00:00 ((2457724j,43500s,0n),+0s,2299161j)>
b.strftime("%M") # minute
=> "05"
b.strftime("%H") # hour
=> "12"
b.strftime("%d") # day of month
=> "01"
b.strftime("%m") # month
=> "12"

So each class would use a different stfrtime() param to filter down to what ever part of the time stamp you need.
http://apidock.com/ruby/DateTime/strftime


text:
Q: Is it possible to center align text in the Speech Bubble annotation in Preview.app? I can create Speech Bubble-style annotations in preview - and easily change the color and font styles, but the text is always left-aligned. Is is possible to center it?

A: There doesn't appear to be a way to do that (other then manually centering it yourself with the space bar).

A: I look at the speech (and thought) bubble feature in Preview as a nice little extra that provides basic functionality. Unfortunately, at least as of 10.7.3 Lion, text justification isn't an option. If your needs (or wants) go beyond the basics you may be interested in comic creation software like Plasq's Comic Life 2.


text:
Q: UI Router: Multiple Independent Views I feel like this is a straight forward use case for the ui-router but maybe I'm missing something...
I want to have two separate views next to each other controlled by their own menus.  When I click a ui-sref link on one menu (or $state.go for that matter), I would like to update only one of the views. Additionally, only one of the two views needs to be reflected in the url.
I tried defining a few states:
$stateProvider
.state('home', {
  url: '/',
  views: {
    'viewA': {
      template: "I'm number A!"
    },
    'viewB': {
      template: "It's good to be B."
    }
  }
})
.state('shouldOnlyChangeA', {
  'url': '',
  views: {
    'viewA': {
       template: 'Check out my new shoes!'
     }
  }
})
.state('shouldOnlyChangeB', {
  'url': '/shouldGoToNewUrl',
  views: {
    'viewB': {
       template: "This probably won't work..."
     }
  }
});

Now press $state.go('shouldOnlyChangeA') from your favorite controller and watch it change the crap out of viewB. I'd also like to omit the url definition in this state since the url should only change between the first and third states I've defined.
I have each ui-view sitting next to each other in index.html:
...

...

TL;DR
I want two sibling ui-views to be stateful all on their own; changing one shouldn't necessarily effect the other.
Hopefully I'm just missing something so I didn't bother to throw a plunker together or anything, but if it's more complicated and folks are willing to fiddle I'll whip something up.

A: See this similar question: Independent routing for multiple regions in an AngularJS single page application

I wrote UI-Router Extras - sticky states to accomplish this use case.
View the demo
Check out the demo source code for details.
I wrote UI-Router Extras - sticky states to achieve your goal.
You'll want one named

 for each region.  Then, add sticky: true to the state definition which targets that region's named view.
See this plunk: http://plnkr.co/edit/nc5ebdDonDfxc1PjwEHp?p=preview

...
$stateProvider
.state('home', {
  url: '/'
 })
.state('shouldOnlyChangeA', {
  'url': '',
  sticky: true, // Root of independent state tree marked 'sticky'
  views: {
    'viewA@': {
       template: 'Check out my new shoes!

'
     }
  }
})
.state('shouldOnlyChangeA.substate', {
  'url': '/substate',
  template: 'Lets get some shoes!'
})
.state('shouldOnlyChangeB', {
  'url': '/shouldGoToNewUrl',
  sticky: true,  // Root of independent state tree marked 'sticky'
  views: {
    'viewB': {
       template: "This probably won't work...

"
     }
  }
})
.state('shouldOnlyChangeB.substate', {
  'url': '/substate',
  template: "Golly, it worked"
  }
);


text:
Q: Изменить timestamp на указанное количество секунд Есть условная таблица пользователей: login, password, ...., created_at
Как передвинуть дату регистрации (created_at) всех пользователей? Скажем, на 1000 секунд вперед или 10000 секунд назад. Дата хранится в timestamp.

A: Для работы с датами в SQL есть INTERVAL. Типы данных от секунды до года.
Чтобы запрос работал правильно:
SELECT created_at + INTERVAL 1000 SECOND AS created_at FROM your_table WHERE conditions;

Если хотите обновить данные, используйте аналогичный запрос для UPDATE.
Вот ссылка для ознакомления http://code.mu/sql/interval.html.


text:
Q: how to delete a file using racket code? I want to delete a file using racket. I am using following code.
 (delete-file c://foo.txt)

I am getting this message.
reference to an identifier before its definition:
c://foo.txt

A: (delete-file "c:/foo.txt")

BTW, since you're asking very basic questions, perhaps it's better to read the guide first?


text:
Q: Usage of "us all"
This story has a useful lesson for us all

In this sentence, need to know the use of us all...

A: In this context, "us all" means something like "everyone".
"A lesson for us" could also work, but "us all"
makes it very clear that it is a lesson for, literally, everyone.

A: In this example, us all is informal for all of us. You could also substitute everyone (as someone else answered).

A: "Us all" and "you all" are ways of emphasizing the totality of a group, much like "all of us/you". "Us all" does not sound particularly formal or informal to my ears. A notable use is in the song "Honor to Us All" (Disney's Mulan).

A: To quote Cambridge:

When "all" refers to a personal pronoun which is the object in a clause, we can use pronoun + "all" or "all of" + pronoun. The pronoun is in the object form:
I used to have three pens but I've lost them all. (or: but I've lost all of them).
Not: but I lost all them.


text:
Q: Replace 0s and forward fill from columns along the same row I would like to replace 0s in my data by forward filling from the previous non zero value along that row.
I was using the following code, but this replaces 0s from the row above instead of the same row:
df.replace(to_replace=0, method='ffill')

In the code above, I am not able to specify the axis as 1.
The code below does exactly what I want, but only to NaN.
columns.fillna(method='ffill',axis=1)

A B C D
1 4 0 0
2 7 8 0
3 8 0 0
4 1 0 0

For example, in the above df, first row, I would like to replace the 0s with "4" and for the row below that, replace the 0 with 8.
Thanks

A: This should work:
x=pd.DataFrame({'A':[1, 2, 3,4],'B':[4, 7, 8, 1],'C':[0, 8, 0, 0],'D':[0, 0, 0, 0]})
x_new=x.apply(lambda y: y.replace(to_replace=0, method='ffill'),axis=1)
x_new
>>  A   B   C   D
0   1   4   4   4
1   2   7   8   8
2   3   8   8   8
3   4   1   1   1

A: You can (1) transpose (2) replace and then (3) transpose again:
df.T.replace(0, method='ffill').T
#output:
    A   B   C   D
0   1   4   4   4
1   2   7   8   8
2   3   8   8   8
3   4   1   1   1


text:
Q: Why does scipy bessel root finding not return roots at zero? I am trying to use code which uses Bessel function zeros for other calculations. I noticed the following piece of code produces results that I consider unexpected.
    import scipy
    from scipy import special

    scipy.special.jn_zeros(1,2)

I would expect the result from this call to be
    array([0., 3.83170597])

instead of
    array([3.83170597, 7.01558667])

Is there a reason a reason why the root at x=0.0 is not being returned?
From what I can see the roots are symmetric along the x-axis except for any found at the origin, but I do not think this would be enough of a reason to leave off the root completely.
The computer I am using has python version 2.7.10 installed and is using scipy version 0.19.0
P.S. the following function is what I am trying to find the zeros of
    scipy.special.j1

A: It appears to be convention to not count the zero at zero, see for example ħere. Maybe it is considered redundant?


text:
Q: Exporting a graph as graphml in python I am new to python and I wanted to export a graph (transportation network) which I constructed using a python package called OSMnx. I am unable to export it as a graphml file for further analysis of the network. I have attached the code I used and the error message I am encountering. Please help.
import osmnx as ox
import networkx as nx
G = ox.graph_from_address('Downtown, Saint Louis, MO', network_type='drive')
nx.write_graphml(G, "g.graphml")

Error message

A: OSMnx has a built-in function for saving street networks as GraphML files, to serialize dict attributes of the nodes and edges:
import osmnx as ox
G = ox.graph_from_address('Downtown, Saint Louis, MO', network_type='drive')
ox.save_graphml(G, filename='g.graphml')


text:
Q: How to communicate between C++ server app and django web app I have some framework doing specific task in C++ and a django-based web app. The idea is to launch this framework, receive some data from it, send some data or request and check it's status in some period.
I'm looking for the best way of communication. Both apps run on the same server. I was wondering if a json server in C++ is a good idea. Django would send a request to this server, and server would parse it, and delegate a worker thread to complete the task. Almost all data that need to be send is string-like. Other data will be stored in database so there is no problem with that.
Is JSON a good idea? Maybe you know some better mechanism for local communication between C++ and django?

A: JSON seems like a fair enough choice for data serialization - it's good at handling strings and there's existing libraries for encoding/decoding JSON in both python & C++.
However, I think your bigger problem is likely to be the transport protocol that you use for transferring JSON between your client and server.  Here's some options:
You could build an HTTP server into your C++ application (which I think might be what you mean by "JSON server" in your question), which would work fine, though might be a bit of a pain to implement unless you get a hold of a library to handle the hard work for you.
Another option might be to use the 0MQ library to send JSON (or otherwise) messages between your client and server.  I think this would probably be a lot easier than implementing a full HTTP server, and 0MQ has some interprocess communication code that would likely be a lot faster than sending things over the network.
A third option would just be to run your C++ as a standalone application and pass the data in to it via stdin or command line parameters.  This is probably the simplest way to do things, though may not be the most flexble.  If you were to go this way, you might be better off just building a Python/C++ binding as suggested by ablm.
Alternatively you could attempt to build some sort of job queue based on redis or something other database system.  The idea being that your django application puts some JSON describing the job into the job queue, and then the C++ application could periodically poll the queue, and use a seperate redis entry to pass the results back to the client.    This could have the advantage that you could reasonably easily have several "workers" reading from the job queue with minimal effort.
There's almost definitely some other ways to go about it, but those are the ones that immediately spring to mind.

A: If your requirement is guaranteed to always have the C++ application on the same machine as the Django web application, include the C++ code by converting it into a shared library and wrapping python around it. Just like this Calling C/C++ from python?
JSON and other serializations make sense if you are going to do remote calls and the code needs to communicate across machines.


text:
Q: MFC double buffering doesn't copy bitmap BOOL CPaintView::OnEraseBkgnd(CDC* /*pDC*/)
{
    //return CPaintView::OnEraseBkgnd(pDC);
    return true;
}
void CPaintView::OnDraw(CDC* pDC)
{
    CDC shadowMem;
    CBitmap shadowBit, *pOldBmp;
    CRect currWin;
    GetClientRect(currWin);

    shadowMem.CreateCompatibleDC(pDC);
    shadowBit.CreateCompatibleBitmap(pDC,currWin.Width(), currWin.Height());
    pOldBmp = (CBitmap*)shadowMem.SelectObject(&shadowBit);
    shadowMem.FillSolidRect(0, 0, currWin.Width(), currWin.Height(), RGB(0, 255, 0));
    shadowMem.Rectangle(330, 300, 400, 500);

    pDC->BitBlt(0, 0, currWin.Width(), currWin.Height(), &shadowMem, 0, 0, SRCCOPY);
    shadowMem.SelectObject(pOldBmp);
}

The code is very simple and intuitive. I created a new CDC and a bitmap, set those to compatible to current CDC. Added new bitmap to new CDC. Then it fills the memory CDC to green color and draw a rectangle on it. then It copy the memory CDC's bitmap to current CDC.
And this is the result i got. You can clearly see a little green line draw near the top edge of the window. I'm not sure which part i messed up.

Update:
Thanks for all the help. I made some random adjustment of bitblt arguments and got a different result.
pDC->BitBlt(0, -400, currWin.Width(), currWin.Height(), &shadowMem, 0, 0, SRCCOPY);

That -400 was a random number when i was trying to figure out the issue. It appears that when i copy the bitmap from shadowMem to pDC, somehow it doesn't match the coordinates correctly.
I couldn't find the reason yet, but if i copy this code to a new project, it works totally fine. I think i may have something to do with MM_ANISOTROPIC mode that my pDC is set to.

A: As @RemyLebeau suggested in the comment, your Rectangle call probably isn't doing what you expect or want.
If we select a pen and brush, then draw a rectangle of (more or less) a size that's entirely inside the client area, we can see the result pretty easily. For example:
void CdoublebufferingView::OnDraw(CDC* pDC)
{
    CDC shadowMem;
    CBitmap shadowBit, * pOldBmp;
    CRect currWin;
    GetClientRect(currWin);

    shadowMem.CreateCompatibleDC(pDC);
    shadowBit.CreateCompatibleBitmap(pDC, currWin.Width(), currWin.Height());
    pOldBmp = (CBitmap*)shadowMem.SelectObject(&shadowBit);
    shadowMem.FillSolidRect(0, 0, currWin.Width(), currWin.Height(), RGB(0, 255, 0));

    shadowMem.SelectObject(GetStockObject(DKGRAY_BRUSH));
    shadowMem.SelectObject(GetStockObject(WHITE_PEN));
    shadowMem.Rectangle(50, 50, currWin.Width() - 100, currWin.Height() - 100);
    pDC->BitBlt(0, 0, currWin.Width(), currWin.Height(), &shadowMem, 0, 0, SRCCOPY);
    shadowMem.SelectObject(pOldBmp);
}

Result:


text:
Q: Panel Data (Longitudinal) Analysis with SEM with continuous variables I am estimating a SEM MIMIC model with 2 indicators, and 5 causes of a latent variable. I have a panel of around 170 countries for the period 1960-2018.
However, my chi-sq and general fit stats are terrible. I read that due to large samples this happens very often these goodness-of-fit stats.
Then, how could I assess my model? What statistical criteria should I use? OR at this point, I just need to consider that the coefficients of the causal variables are with the "right" sign and statistically significant?


text:
Q: Regex for Non-negative numbers with two decimals OR Non-negative Integers. No leading 0 As-salāmu ʿalaykum,
Allowed:

0
0.00
0.01
0.10
0.11
1
1.00
1.10
1.01
1.11
99999999
99999999.00
99999999.01
99999999.10
99999999.11

NOT ALLOWED:
.
.00
00
00.
00.00
00.01
00.10
00.11
01
010
01.
01.00
01.000

I could go on but i think you get the gist of what I want. The Regex will be used to validate currency, with a maximum of two optional decimals. No upper limit for the left hand side of the decimal, as long as it isn't a leading 0.
It will be used in a Java-application.
Thanks in advance

A: One option is, from the start of the string, use negative lookahead for 0 followed by a digit, and then just test for digits optionally followed by a . which is followed by more digits:
^(?!0\d)\d+(\.\d\d)?

https://regex101.com/r/5nUmlI/1/


text:
Q: sending gps data using icomsat v1.1 I am doing my final year project that tracks the vehicle and displays the position on google maps,am using an arduino,GPS module and icomsat v1.1 GPRS module.Am trying to send the GPS data to a web page at my local server with no success,how do i do this, pls help :
this is how am doing it:
    //set http param value
    GPRS.print("AT+HTTPPARA=\"URL\",\"http://my_domain/gps_tracker.php?");
    GPRS.print("visor=false");
    GPRS.print("&latitude=");
    GPRS.print(latitude);
    GPRS.print("&longitude=");
    GPRS.print(longitude);
    GPRS.print("speed=");
    GPRS.print(speedOTG);
    GPRS.print("\"");

A: I suppose that you need to send the url as a single line message, using: println instead of print.
And check if you're receiving or not any data on your GPRS module, or if you're not managing it right.