text:
Q: JQuery, el render de mi datatable no cambia el id del item al eliminarlo Estoy obteniendo registros desde una API y los muestro en un grid DataTable

Y con un enpoint estoy actualizando un estatus para que ya no se vean en el grid , paso el mouse sobre el icono de eliminar y me trae los ids correctos y solo me cambia el estatus y desaparece del grid una vez, la segunda vez que lo hago sigue trayendo el id anterior pero cuando recargo la página y vuelvo a cambiarlo otro estatus solo lo hace una vez y así sucesivamente, no logro ver que es lo que me falta para que me pase eso.
Código para dibujar el grid:
$(document).ready(function () {
'use strict';

$('#employeeServicesRequests-datatable').DataTable({
    ajax: {
        url: '/api/Controller',
        dataSrc: 'services'
    },
    columns: [
        { data: 'title', orderable: true },
        {
            data: 'id', orderable: false, targets: 0,
            render: function (data, type, row, meta) {
                var returnValue = `<a href="#" class="action-icon view" data-id="${data}"><i class="mdi mdi-eye"></i></a>` +
                    `<a href="#" class="action-icon edit" data-id="${data}"><i class="mdi mdi-square-edit-outline"></i></a>` +
                    `<a href="/Controller/Delete/${data}" class="action-icon" data-toggle="modal" data-target="#confirm-delete"> <i class="mdi mdi-delete"></i></a>`;
                return returnValue;
            }
        }
    ]
});

});

Código para eliminar el registro:
$confirmDelete.on('click', '.btn-delete', function (e) {
    debugger;
    var url = $(this).data('url');

    $.ajax({
        type: "GET",
        url: url,
        error: () => $.Notification.error("Error: Try again"),
        success: () => {
            $confirmDelete.modal("toggle");
            $dataTable.DataTable().ajax.reload();
        }
    });
});

$confirmDelete.on('show.bs.modal', function (e) {
    $(this).find('.btn-delete').attr("data-url", $(e.relatedTarget).attr("href"));
});

El endpoint para cambiar status es de tipo GET:
public async Task<JsonResult> Delete(string id)
    {
        if(!string.IsNullOrEmpty(id.ToString()))
        {
            var response = await client.GetStringAsync($"api/Services/Delete/{id}");
            var item = await Task.Run(() => JsonConvert.DeserializeObject<RegisterServiceDTO>(response));

            if (item != null)
                return Json(new { Success = true }, JsonRequestBehavior.AllowGet);

            return Json(new { Success = false, Message = "Error" }, JsonRequestBehavior.AllowGet);

        }

        return Json(new { Success = false, Message = "Error" });

    }

Se queda guardado el ultimo id pero no logro que lo haga las veces que sea necesario y no solo una vez

A: El problema que noto es que usas GET en las operaciones, recuerda que el get cachea, con lo cual ejecuta la primer operacion pero la siguiente la tomara del cache del browser sin ir al servidor
Recomendaria que cambies la operacion a el verbo http DELETE
[HttpDelete]
public async Task<JsonResult> Delete(string id)
{
   //codigo
}

desde el codigo cliente seria
$.ajax({
    type: "DELETE",
    url: url,
    error: () => $.Notification.error("Error: Try again"),
    success: () => {
        $confirmDelete.modal("toggle");
        $dataTable.DataTable().ajax.reload();
    }
});

solo cambias el type
Tambien deberias aplicarlo al servicio
var response = await client.GetDeleteAsync($"api/Services/Delete/{id}");

analiza como lo explica el articulo
HttpDelete Method In ASP.NET Web API - Part Six
usa los verbos http de forma correcta en cada operacion


text:
Q: How to update panel from datatable Commandbutton with id("myButtonId2") works fine. I mean it updates "myOutputPanel" but commandbutton which is inside datatable doesn't update outputPanel. Is there a specific update style for datatables?
<h:form id="myForm" prependId="false">
  <p:panel id="myPanel">
     <p:dataTable id="myDatatable">
        <p:column style="width:4%">
          <p:commandButton id="myButtonId" update="myOutputPanel"/>
        </p:column>
     </p:dataTable>
     <p:commandButton id="myButtonId2" update="myOutputPanel"/>
    </p:panel>

 <p:outputPanel id="myOutputPanel">
  //some stuff
 </p:outputPanel>

A: This is because with process and update they work much the same way as the f:ajax component attributes execute and render do.  One can only reference the id of a component directly if they reside within the same NamingContainer.
The clientID is generated by prefixing the naming container ids seperated by : by default.  The p:panel component does not implement NamingContainer although h:form and p:dataTable do implement NamingContainer.
The clientID of myOutputPanel is as follows:
myForm:myOutputPanel

The second button works because it is outside of the dataTable and relative to myOutputPanel in the same NamingContainer which is the form.  To reference the absolute clientID in process or update one can prefix the clientID with the : symbol.
Try changing the update attribute of the first commandButton to:
:myForm:myOutputPanel

This should allow it absolutely reference its generated clientID and work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Braintree Sale Error (PHP) I'm getting the following error when trying to create a transaction with Braintree. In Sandbox it worked fine. My server is an AWS Beanstalk setup with a load balancer with SSL (TLS 1.2).
Here is the error from the error_log:
[Mon Mar 20 11:32:31.816499 2017] [:error] [pid 11335] [client XX] PHP Fatal error:  Uncaught Braintree\\Exception\\Authorization in /var/app/current/scripts/lib/Braintree/Util.php:61\nStack trace:\n#0 /var/app/current/scripts/lib/Braintree/Http.php(47): Braintree\\Util::throwStatusCodeException(403)\n#1 /var/app/current/scripts/lib/Braintree/TransactionGateway.php(477): Braintree\\Http->post('/merchants/jtd9...', Array)\n#2 /var/app/current/scripts/lib/Braintree/TransactionGateway.php(49): Braintree\\TransactionGateway->_doCreate('/transactions', Array)\n#3 /var/app/current/scripts/lib/Braintree/TransactionGateway.php(289): Braintree\\TransactionGateway->create(Array)\n#4 /var/app/current/scripts/lib/Braintree/Transaction.php(502): Braintree\\TransactionGateway->sale(Array)\n#5 /var/app/current/ajax/add_points.php(23): Braintree\\Transaction::sale(Array)\n#6 {main}\n  thrown in /var/app/current/scripts/lib/Braintree/Util.php on line 61, referer: https://XX.com/dashboard

Here is the actual server-side PHP code:
require_once('../scripts/lib/Braintree.php');
Braintree_Configuration::environment('production');
Braintree_Configuration::merchantId('xx');
Braintree_Configuration::publicKey('xx');
Braintree_Configuration::privateKey('xx');
$pym = $_POST["payment_method_nonce"];
$points = 10*1.5;

        $result = Braintree_Transaction::sale([
            'amount' => $points,
            'currency' => 'EUR',
            'paymentMethodNonce' => $pym,
            'options' => [
                'submitForSettlement' => true
            ]
        ]);

The ::sale part of the code above is what gives me the error above. I tried doing an exit(); after including the Braintree.php file and all the configuration options, and it exits as expected, so the error is definitely caused by the ::sale part of the code.
All works fine in Sandbox, and nonce seems to be correctly generated client side, and then sent.
I'm not even sure where to start debugging. Any advice would help!

A: It turns out that my clients application has been declined.
The key term here was authorization - which is different than authentication (which relates to API keys, that were correct).


text:
Q: MySQL Workbench warning when connecting to MariaDB When using MySQL Workbench 6.3 on Kubuntu 15.10 and MariaDB Server version: 10.0.22-MariaDB-0ubuntu0.15.10.1 (Ubuntu), I get the following warning.
Is this expected?

Incompatible/nonstandard server version or connection protocol
  detected (10.0.22).
A connection to this database can be established but some MySQL
  Workbench features may not work properly since the database is not
  fully compatible with the supported versions of MySQL.
MySQL Workbench is developed and tested for MySQL Server versions 5.1,
  5.5, 5.6 and 5.7
Succcessfully made the mysql connection
Information related to this connection:
Host: localhost Port: 0 User: serg SSL: not enabled
A successful MySQL connection was made with the parameters defined for
  this connection.

A: TL;DR
Yes this is expected, because MySQL Workbench is an Oracle product and it does not officially support MariaDB which is actually a MySQL competitor. Workbench is warning you about potential incompatibilities, not necessarily detected ones. In most cases, it can be safely ignored.
Details
The MariaDB knowledge-base article on MySQL compatibility describes the relationship best (emphasis mine):

For all practical purposes, MariaDB is a binary drop in replacement of the same MySQL version (for example MySQL 5.1 -> MariaDB 5.1, MariaDB 5.2 & MariaDB 5.3 are compatible. MySQL 5.5 is compatible with MariaDB 5.5 and also in practice with MariaDB 10.0). What this means is that:

*

*Data and table definition files (.frm) files are binary compatible.

*

*See note below for an incompatibility with views!

*All client APIs, protocols and structs are identical.
  All filenames, binaries, paths, ports, sockets, and etc... should be the same.

*All MySQL connectors (PHP, Perl, Python, Java, .NET, MyODBC, Ruby, MySQL C connector etc) work unchanged with MariaDB.

*

*There are some installation issues with PHP5 that you should be aware of (a bug in how the old PHP5 client checks library compatibility).

*The mysql-client package also works with MariaDB server.

*The shared client library is binary compatible with MySQL's client library.

  This means that for most cases, you can just uninstall MySQL and install MariaDB and you are good to go. (No need to convert any datafiles if you use same main version, like 5.1). You must however still run mysql_upgrade to finish the upgrade. This is needed to ensure that your mysql privilege and event tables are updated with the new fields MariaDB uses.
We do monthly merges with the MySQL code base to ensure we keep up our compatibility and get any and all features and bug fixes Oracle adds.

All that being said, there are some incompatibilities that may or may not affect you. The linked KB article has a section on known incompatibilities between different versions of MySQL and MariaDB. Refer to the section for your MariaDB version for notes that may affect you.


text:
Q: VBA-Copy multiple charts at one time I have a total of 10 charts on a worksheet, 5 being in SI units and the other 5 being in ANSI. Each are divided into two separate columns. The 5 ANSI charts are aligned vertically in column "F". The 5 SI charts are aligned vertically in column "O".
I want to copy only the charts in column "F".
How would I go about copying them all at one time?
I currently have them copied one at a time
Code:
wb.Sheets(w).ChartObjects("Chart 9").Chart.ChartArea.Copy
With ThisWorkbook.Worksheets("Plots")
    .Activate
    .Range( "F2").Select
    .Pictures.Paste
End With
wb.Sheets(w).ChartObjects("Chart 13").Chart.ChartArea.Copy
With ThisWorkbook.Worksheets("Plots")
    .Activate
    .Range("F17").Select
    .Pictures.Paste
End With

wb.Sheets(w).ChartObjects("Chart 14").Chart.ChartArea.Copy
With ThisWorkbook.Worksheets("Plots")
    .Activate
    .Range("F32").Select
    .Pictures.Paste
End With

wb.Sheets(w).ChartObjects("Chart 15").Chart.ChartArea.Copy
With ThisWorkbook.Worksheets("Plots")
    .Activate
    .Range("F47").Select
    .Pictures.Paste
End With

wb.Sheets(w).ChartObjects("Chart 16").Chart.ChartArea.Copy
With ThisWorkbook.Worksheets("Plots")
    .Activate
    .Range("F64").Select
    .Pictures.Paste
End With

Example of how they are arranged;

A: In a loop you could do:
Dim chartPasteRow as integer

chartPasteRow = 2
For each chartName in Array("Chart 9", "Chart 13", "Chart 14", "Chart 15", "Chart 16")
    wb.Sheets(w).ChartObjects(chartName).Chart.ChartArea.Copy
    ThisWorkbook.Worksheets("Plots").Range("F" & chartPasteRow).PasteSpecial xlPasteValues
    chartPasteRow = chartPasteRow + 15
Next chartName

If you want to paste all charts without having to specify you could do something like:
Dim chartPasteRow as integer

chartPasteRow = 2
For each cht In wb.Sheets(w).ChartObjects
    cht.Chart.ChartArea.Copy
    ThisWorkbook.Worksheets("Plots").Range("F" & chartPasteRow).PasteSpecial xlPasteValues
    chartPasteRow = chartPasteRow + 15
Next cht

This is making the assumption that each chart will get pasted every 15 rows.


text:
Q: Basic references to study the hyperbolic plane I am an undergraduate math student and I want to introduce myself in the study of the hyperbolic plane. I'm looking for references on this topic to start getting into it. Could you recommend me some books?
Thanks in advance.


text:
Q: must appear in the GROUP BY clause or be used in an aggregate function I have a table that looks like this caller 'makerar'

cname
wmname
avg

canada
zoro
2.0000000000000000

spain
luffy
1.00000000000000000000

spain
usopp
5.0000000000000000

And I want to select the maximum avg for each cname.
SELECT cname, wmname, MAX(avg)  FROM makerar GROUP BY cname;

but I will get an error,
ERROR:  column "makerar.wmname" must appear in the GROUP BY clause or be used in an   aggregate function
LINE 1: SELECT cname, wmname, MAX(avg)  FROM makerar GROUP BY cname;

so i do this
SELECT cname, wmname, MAX(avg)  FROM makerar GROUP BY cname, wmname;

however this will not give the intented results, and the incorrect output below is shown.

cname
wmname
max

canada
zoro
2.0000000000000000

spain
luffy
1.00000000000000000000

spain
usopp
5.0000000000000000

Actual Results should be

cname
wmname
max

canada
zoro
2.0000000000000000

spain
usopp
5.0000000000000000

How can I go about fixing this issue?
Note: This table is a VIEW created from  a previous operation.

A: The problem with specifying non-grouped and non-aggregate fields in group by selects is that engine has no way of knowing which record's field it should return in this case. Is it first? Is it last? There is usually no record that naturally corresponds to aggregated result (min and max are exceptions).
However, there is a workaround: make the required field aggregated as well.
In postgres, this should work:
SELECT cname, (array_agg(wmname ORDER BY avg DESC))[1], MAX(avg)
FROM makerar GROUP BY cname;

Note that this creates an array of all wnames, ordered by avg, and returns the first element (arrays in postgres are 1-based).

A: For me, it is not about a "common aggregation problem", but just about an incorrect SQL query. The single correct answer for "select the maximum avg for each cname..." is
SELECT cname, MAX(avg) FROM makerar GROUP BY cname;

The result will be:
 cname  |      MAX(avg)
--------+---------------------
 canada | 2.0000000000000000
 spain  | 5.0000000000000000

This result in general answers the question "What is the best result for each group?". We see that the best result for spain is 5 and for canada the best result is 2. It is true, and there is no error.
 If we need to display wmname also, we have to answer the question: "What is the RULE to choose wmname from resulting set?" Let's change the input data a bit to clarify the mistake:
  cname | wmname |        avg
--------+--------+-----------------------
 spain  | zoro   |  1.0000000000000000
 spain  | luffy  |  5.0000000000000000
 spain  | usopp  |  5.0000000000000000

Which result do you expect on runnig this query: SELECT cname, wmname, MAX(avg)  FROM makerar GROUP BY cname;? Should  it be spain+luffy or spain+usopp? Why? It is not determined in the query how to choose "better" wmname if several are suitable, so the result is also not determined. That's why SQL interpreter returns an error - the query is not correct.
In the other word, there is no correct answer to the question "Who is the best in spain group?". Luffy is not better than usopp, because usopp has the same "score".

A: Yes, this is a common aggregation problem. Before SQL3 (1999), the selected fields must appear in the GROUP BY clause[*].
To workaround this issue, you must calculate the aggregate in a sub-query and then join it with itself to get the additional columns you'd need to show:
SELECT m.cname, m.wmname, t.mx
FROM (
    SELECT cname, MAX(avg) AS mx
    FROM makerar
    GROUP BY cname
    ) t JOIN makerar m ON m.cname = t.cname AND t.mx = m.avg
;

 cname  | wmname |          mx
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | usopp  |     5.0000000000000000

But you may also use window functions, which looks simpler:
SELECT cname, wmname, MAX(avg) OVER (PARTITION BY cname) AS mx
FROM makerar
;

The only thing with this method is that it will show all records (window functions do not group). But it will show the correct (i.e. maxed at cname level) MAX for the country in each row, so it's up to you:
 cname  | wmname |          mx
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | luffy  |     5.0000000000000000
 spain  | usopp  |     5.0000000000000000

The solution, arguably less elegant, to show the only (cname, wmname) tuples matching the max value, is:
SELECT DISTINCT /* distinct here matters, because maybe there are various tuples for the same max value */
    m.cname, m.wmname, t.avg AS mx
FROM (
    SELECT cname, wmname, avg, ROW_NUMBER() OVER (PARTITION BY avg DESC) AS rn
    FROM makerar
) t JOIN makerar m ON m.cname = t.cname AND m.wmname = t.wmname AND t.rn = 1
;

 cname  | wmname |          mx
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | usopp  |     5.0000000000000000

[*]: Interestingly enough, even though the spec sort of allows to select non-grouped fields, major engines seem to not really like it. Oracle and SQLServer just don't allow this at all. Mysql used to allow it by default, but now since 5.7 the administrator needs to enable this option (ONLY_FULL_GROUP_BY) manually in the server configuration for this feature to be supported...

A: SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
    SELECT cname, MAX(avg) max
    FROM makerar
    GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;

Using rank() window function:
SELECT cname, wmname, avg
FROM (
    SELECT cname, wmname, avg, rank()
    OVER (PARTITION BY cname ORDER BY avg DESC)
    FROM makerar) t
WHERE rank = 1;

Note
Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.

A: This seems to work as well
SELECT *
FROM makerar m1
WHERE m1.avg = (SELECT MAX(avg)
                FROM makerar m2
                WHERE m1.cname = m2.cname
               )

A: In Postgres, you can also use the special DISTINCT ON (expression) syntax:
SELECT DISTINCT ON (cname)
    cname, wmname, avg
FROM
    makerar
ORDER BY
    cname, avg DESC ;

A: I recently run into this problem, when trying to count using case when, and found that changing the order of the which and count statements fixes the problem:
SELECT date(dateday) as pick_day,
COUNT(CASE WHEN (apples = 'TRUE' OR oranges 'TRUE') THEN fruit END)  AS fruit_counter

FROM pickings

GROUP BY 1

Instead of using - in the latter, where I got errors that apples and oranges should appear in aggregate functions
CASE WHEN ((apples = 'TRUE' OR oranges 'TRUE') THEN COUNT(*) END) END AS fruit_counter


text:
Q: OpenGL: two spheres in single vertex buffer (Question is at bottom)Im learning opengl(using lwjgl) and done some drawing of flat shape through sending buffers. Now I need to draw many spheres in single buffer. In my last question, I was advised to use geometry instancing but I dont know how to use any shader language in java yet so I'm trying to make multiple objects in single buffer just like in the examples.
What I tried to generate two spheres by QUAD_STRIP style(using lwjgl's own GLU.Sphere() function to fill the buffers):
n=c1*(c2+1);
        float rr=(float) Math.random();
        float gg=(float) Math.random();
        float bb=(float) Math.random();
        float aa=(float) Math.random();

        positions = new float[c1 * (c2+1) * 3*2 *2];
        normals = new float[c1 * (c2+1) * 3*2 *2];
        colors = new float[c1 * (c2+1) * 4*2 *2];
        int counter=0;
        float drho = 3.141593F / 32.0f;
        float dtheta = 6.283186F / 32.0f;
        float ds = 1.0F / 32.0f;
        float dt = 1.0F / 32.0f;
        float t = 1.0F;

        /*first sphere*/
        for (int i = 0; i < 32; i++) {
            float rho = i * drho;

            float s = 0.0F;
            for (int j = 0; j <= 32; j++) {
              float theta = j == 32 ? 0.0F : j * dtheta;
              float x = (float) (-Math.sin(theta) * Math.sin(rho));
              float y = (float) (Math.cos(theta) * Math.sin(rho));
              float z = (float) (1.0f * Math.cos(rho));

              normals[counter*3+0]=x*1.0f;normals[counter*3+1]=y*1.0f;normalscounter*3+2]=z*1.0f;

              colors[counter*4+0]=rr;colors[counter*4+1]=gg;colors[counter*4+2]=bb;colors[counter*4+3]=1.0f/*aa*/;

              positions[counter*3+0]=x*r;positions[counter*3+1]=y*r;positions[counter*3+2]=z*r;
              counter++;
              x = (float) (-Math.sin(theta) * Math.sin(rho + drho));
              y = (float) (Math.cos(theta) * Math.sin(rho + drho));
              z = (float) (1.0f * Math.cos(rho + drho));

              normals[counter*3+0]=x*1.0f;normals[counter*3+1]=y*1.0f;normals[counter*3+2]=z*1.0f;

              colors[counter*4+0]=rr;colors[counter*4+1]=gg;colors[counter*4+2]=bb;colors[counter*4+3]=1.0f/*aa*/;

              positions[counter*3+0]=x*r;positions[counter*3+1]=y*r;positions[counter*3+2]=z*r;
              counter++;
              s += ds;
            }

            t -= dt;
          }
/* first sphere end */
/* second sphere generation */
        {
            drho = 3.141593F / 32.0f;
            dtheta = 6.283186F / 32.0f;
            ds = 1.0F / 32.0f;
            dt = 1.0F / 32.0f;
            t = 1.0F;
            for (int i = 0; i < 32; i++) {
                float rho = i * drho;

                float s = 0.0F;
                for (int j = 0; j <= 32; j++) {
                  float theta = j == 32 ? 0.0F : j * dtheta;
                  float x = (float) (-Math.sin(theta) * Math.sin(rho));
                  float y = (float) (Math.cos(theta) * Math.sin(rho));
                  float z = (float) (1.0f * Math.cos(rho));
                 normals[counter*3+0]=x*1.0f;normals[counter*3+1]=y*1.0f;normals[counter*3+2]=z*1.0f;

                  colors[counter*4+0]=rr;colors[counter*4+1]=gg;colors[counter*4+2]=bb;colors[counter*4+3]=1.0f/*aa*/;

                  positions[counter*3+0]=x*r+1.0f;positions[counter*3+1]=y*r+1.0f;positions[counter*3+2]=z*r+1.0f;
                  counter++;
                  x = (float) (-Math.sin(theta) * Math.sin(rho + drho));
                  y = (float) (Math.cos(theta) * Math.sin(rho + drho));
                  z = (float) (1.0f * Math.cos(rho + drho));

                  normals[counter*3+0]=x*1.0f;normals[counter*3+1]=y*1.0f;normals[counter*3+2]=z*1.0f;

                  colors[counter*4+0]=rr;colors[counter*4+1]=gg;colors[counter*4+2]=bb;colors[counter*4+3]=1.0f/*aa*/;

                  positions[counter*3+0]=x*r+1.0f;positions[counter*3+1]=y*r+1.0f;positions[counter*3+2]=z*r+1.0f;
                  counter++;
                  s += ds;
                }

                t -= dt;
              }
        }
        /*second sphere end*/

        positionsBuf=BufferUtils.createFloatBuffer(c1 * (c2+1) * 3*2  *2);
        positionsBuf.put(positions);
        positionsBuf.rewind();
        colorsBuf=BufferUtils.createFloatBuffer(c1 * (c2+1) * 4*2  *2);
        colorsBuf.put(colors);
        colorsBuf.rewind();
        normalsBuf=BufferUtils.createFloatBuffer(c1 * (c2+1) * 3*2  *2);
        normalsBuf.put(normals);
        normalsBuf.rewind();

As you can see, below image shows how two spheres are drawn. There is an unwanted link between two.

Most probably the rope is caused by the last point of first sphere and first point of second sphere. Is there some kind of delimiter/drawing-hint to separate two drawings in the same buffer?
Here is how they are drawn:
         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER,sphereBufferCol.get(0));
         GL11.glColorPointer(4, GL11.GL_FLOAT, 0, 0);
         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, sphereBufferPos.get(0));
         GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, sphereBufferNormal.get(0));
         GL11.glNormalPointer(GL11.GL_FLOAT, 0, 0);

         GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
         GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
         GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);

         //Each sphere is generated 32 by 32 quadstriparray and each having two sets of two points and there are two spheres
         GL11.glDrawArrays(GL11.GL_QUAD_STRIP, 0, 32*33*2 *2);

         GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
         GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
         GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY);

         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);

Question: How can I make that rope-like thing disappear without decreasing performance? Maybe putting zero to last and first points' alpha value can make it invisible but wouldnt that cause two holes on each sphere and decrease performance because of many lines on the screen?
All vertex values will be altered by opencl interoperability so single drawing call is needed to draw whole 10000+ spheres.

A: There seem to be a number of options:

*

*use multiple buffers

*use quads instead of quad strips

*use primitive restart

*use degenerate triangles, i.e. add the last vertex twice

*use [instanced rendering] (http://www.opengl.org/wiki/Vertex_Rendering#Instancing)

If you are on newer hardware and want to use quad strips, I'd prefer using primitive restart.
Please note that this is just the result of a quick assessment and anchecked (I personally don't use quad strips or even tri strips that often ;) ).


text:
Q: What are the associations of the word "Heights" in a city name? There are lots of cities and other designations with the word "Heights" in the name. Does this refer to something specific? Is it a marketing tactic perhaps?
Examples:

*

*Hacienda Heights

*Sterling Heights

*Washington Heights

*Golan Heights

A: In the 19th century most big cities weren't particularly pleasant places. Horses, coal fires and limited sanitation meant they were dirty and smelly.
The best places to live was on a hill in the fresh clean air - so XXX heights was the upper class area of the city. Or later, a marketing slogan for a new area to give the impression of luxury
Golan heights is a high plateau on the Israel/Syria border with rather more strategic than real estate value.


text:
Q: pg_Ctl -data directory has wrong ownership I am unable to start the Postgres server and whenever I use pg_ctl I am getting the following error - can some one help me to fix this. I changed the folder permissions using CHmod and tried running with Sudo -s also but still the problem exists.
one error I did was, I deleted the Postmaster.pid when the server was running- post this I am getting this issue when ever I try to start the server through pg_ctl and another error when I use the pgadmin.
Any suggestions here will be really helpful- thanks.
Using Macos Shell command :
'pg_ctl start -D /Library/PostgreSQL/12/data waiting for server to start....2020-05-05 11:40:04.838 IST [1216] FATAL: data directory "/Library/PostgreSQL/12/data" has wrong ownership 2020-05-05 11:40:04.838 IST [1216] HINT: The server must be started by the user that owns the data directory. stopped waiting pg_ctl: could not start server Examine the log output.'
Using pgadmin the error is as follows :
'could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5434? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5434?'
p.s. : I modified the hba.conf and also the postgres.conf files to allow connection from the local ip
Error received on 5May
waiting for server to start....2020-05-05 19:54:13.029 IST [7274] LOG:  starting PostgreSQL 12.2 on x86_64-apple-darwin, compiled by Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn), 64-bit
2020-05-05 19:54:13.030 IST [7274] LOG:  listening on IPv6 address "::", port 5433
2020-05-05 19:54:13.030 IST [7274] LOG:  listening on IPv4 address "0.0.0.0", port 5433
2020-05-05 19:54:13.030 IST [7274] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5433"
2020-05-05 19:54:13.039 IST [7274] LOG:  redirecting log output to logging collector process... 2020-05-05 19:54:13.039 IST [7274] HINT:  Future log output will appear in directory "log" stopped waiting .. pg_ctl: could not start server
Examine the log output.
Log file details
2020-05-05 21:29:30.748 IST [8853] LOG:  invalid authentication method "0.0.0.0/0"
2020-05-05 21:29:30.748 IST [8853] CONTEXT:  line 80 of configuration file "/Library/PostgreSQL/12/data/pg_hba.conf"
2020-05-05 21:29:30.748 IST [8853] FATAL:  could not load pg_hba.conf
2020-05-05 21:29:30.749 IST [8853] LOG:  database system is shut down

Details of my pg_HBA conf

# "local" is for Unix domain socket connections only
local   all             all            0.0.0.0/0                md5
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.

local   replication     all                                     md5
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5
host    all             all             0.0.0.0/0               md5

    host    all             all               ::/0                  md5
latest log file
bash-3.2$ cat postgresql-2020-05-05_221328.log
2020-05-05 22:13:28.794 IST [9834] LOG:  database system was interrupted; last known up at 2020-05-05 22:13:09 IST
2020-05-05 22:13:28.872 IST [9834] LOG:  database system was not properly shut down; automatic recovery in progress
2020-05-05 22:13:28.874 IST [9834] LOG:  redo starts at 0/17742C8
2020-05-05 22:13:28.874 IST [9834] LOG:  invalid record length at 0/1774300: wanted 24, got 0
2020-05-05 22:13:28.874 IST [9834] LOG:  redo done at 0/17742C8
2020-05-05 22:13:28.881 IST [9832] LOG:  database system is ready to accept connections
......
also I found this error while staring the server and the PID is chaning everytime..
pg_ctl: another server might be running; trying to start server anyway
waiting for server to start....2020-05-05 22:09:21.941 IST [9746] FATAL:  lock file "postmaster.pid" already exists
2020-05-05 22:09:21.941 IST [9746] HINT:  Is another postmaster (PID 9735) running in data directory "/Library/PostgreSQL/12/data"?
 stopped waiting
pg_ctl: could not start server
Examine the log output.
bash-3.2$ kill -9 9735
bash-3.2$ pg_ctl start -D /Library/PostgreSQL/12/data
pg_ctl: another server might be running; trying to start server anyway
waiting for server to start....2020-05-05 22:09:35.829 IST [9758] FATAL:  lock file "postmaster.pid" already exists
2020-05-05 22:09:35.829 IST [9758] HINT:  Is another postmaster (PID 9747) running in data directory "/Library/PostgreSQL/12/data"?
 stopped waiting
pg_ctl: could not start server
Examine the log output.
502  9833  9832   0 10:13PM ??         0:00.00 postgres: logger
  502  9835  9832   0 10:13PM ??         0:00.00 postgres: checkpointer
  502  9836  9832   0 10:13PM ??         0:00.04 postgres: background writer
  502  9837  9832   0 10:13PM ??         0:00.01 postgres: walwriter
  502  9838  9832   0 10:13PM ??         0:00.01 postgres: autovacuum launcher
  502  9839  9832   0 10:13PM ??         0:00.01 postgres: stats collector
  502  9840  9832   0 10:13PM ??         0:00.00 postgres: logical replication launcher
    0  9641  9504   0 10:03PM ttys000    0:00.02 sudo -u postgres -s /bin/bash
  502  9904  9642   0 10:37PM ttys000    0:00.00 grep postgres

A: The data directory should be owned by the postgres user and have user-only access (700 or u+rwx)
Does this match what you have set up?
Thom Brown
Disclosure: I am an EnterpriseDB employee.

A: Try running this code
pg_ctl -D /usr/local/var/postgres start


text:
Q: Rebuild Very Large Primary Key Index I have a SQL database that is hosted on Azure. The problem is that the size is getting out of control, I can see up to 99% fragmentation in the Primary Key clustered indexes.
I'm able to rebuild all other indexes with online=on option and it won't affect performance. The size of one of the PK Clustered indexes is greater than 200GB, and for this one a REBUILD...WITH (ONLINE=ON) causes locking.
We do have users from all timezones accessing the site so really, I'm unable to find a time where I can rebuild the index offline.
What is the best strategy to rebuild large indexes without having a downtime in the site?
I believe reorganize won't help since fragmentation is 99%. The problem is that the table gets locked even with online. The main problem is that the index is greater than 200GB. The primary key is an integer.

A: First, it's important to consider whether fragmentation matters.
If your query is only doing single-row seeks, you might not notice fragmentation at all. On modern SANs, the SAN-level caching may make phyiscal IOs fast enough that fragmentation doesn't matter. On SSD, the random IO pattern caused by scanned a fragmented index may actually result in better performance than non-fragmented data.
Often times, people notice that rebuiliding an index fixed a performance problem. Rebuilding an index also builds fresh statistics. It may be the case that the real fix is fresh statistics, not rebuilding the index. UPDATE STATISTICS...WITH FULLSCAN may be a cheaper, faster, less intrusive way to solve the same performance problem.
If you are not having problems caused by fragmentation, then you could be spending significant time & effort for no actual gain.
Second, there are two kinds of fragmentation:

*

*Physical fragmentation. This is what most people think of when they think of fragmentation. Pages are out of order, and need to be re-ordered. When scanning an index this type of fragmentation can sometimes be a problem. I've generally noticed this has the largest impact on performance with physical reads. If you are looking at the results from sys.dm_db_index_physical_stats, this number is the avg_fragmentation_in_percent column.

*Low-density fragmentation. This fragmentation is caused by pages that are only partially filled with data. You have low density of data because your data is spread across more pages than necessary. As a result, reading the data requires more IOs because the data is spread across more pages than necessary. This can affect both logical and physical reads. If you are looking at the results from sys.dm_db_index_physical_stats, this number is the avg_page_space_used_in_percent column. This column is only populated when using SAMPLED or DETAILED mode.
So what do you do about it:
Physical Fragmentation: If you are simply chasing high numbers for avg_fragmentation_in_percent, really consider if you're wasting your time. Make sure that you have an actual query that is performing poorly, and use a test environment to confirm that you're fixing a problem by eliminating fragmentation.
You can address physical fragmentation by doing ALTER INDEX...REORGANIZE. The REORGANIZE operation is online, moving pages one at a time to reorganize them back into physical order. If you kill a REORGANIZE statement part way through, any work that was already performed is maintained--only the one page currently being moved will be rolled back. Doing a REORGANIZE on a large table that is highly fragmented can require more total transaction log space, and in full recovery mode may generate a significant amount of transaction log backups. It may also take longer to REORGANIZE a highly fragmented index than to REBUILD it.
You will often see advice to perform a REBUILD on highly-fragmented indexes, rather than a REORGANIZE -- This is because rebuilding from scratch can be more efficient. However, reorganizing can be a "more online" operation and is sometimes preferred, even for highly fragmented indexes.
Low-density fragmentation cannot be fixed by REORGANIZE. It can only be fixed by doing an ALTER INDEX...REBUILD. By doing the index with ONLINE=ON, you should be able to minimize blocking. However, the REBUILD still needs to take a lock for a moment to swap the old index for the new index. On a very busy system, attaining this exclusive lock can sometimes be a problem. You should be able to confirm if you are having this issue by using something like sp_whoisactive to examine blocking during your rebuild, and looking at the details of the locks & waits. Using the WAIT_AT_LOW_PRIORITY option may be useful if you know that there is an upcoming period of low utilization, and your rebuild can "sneak in" for this swap when activity drops low enough to attain that lock. Note that a long-running REBUILD operation is also going to be a long-running open transaction. Long-running open transactions can have their own problems, related to transaction log use/reuse. If you are using mirroring or Availability Groups, there are also considerations for transaction log redo on the secondary replica.

A: Notice
After this comment:

You will lose rows that are inserted during the copy. If you want to prevent this by locking the table then you end up with the same problem as the OP stated in his question. Also 200Gb will not come for free :-) – Marco Sep 5 '17 at 11:18

...I see how this approach will not work.
I'll leave this answer up as an example of what not to do.

If you have a spare 200+ GB free on your Azure DB, you can get sneaky with the "rebuild", by copying your data to a totally new table and ordering it there.
Try:

*

*scripting your LiveTable into an empty NewTable

*copying the LiveTable into the NewTable

*renaming LiveTable to OldTable

*renaming NewTable to LiveTable
Obviously, use your table's name instead of LiveTable.

A: Even though it's a bit late, I'm going to field a response with hope that it helps or at least spurns some additional ideas/commentary on this issue because I think it's a good question.
First, and I don't know if you're doing this or not, but please don't assume that high fragmentation levels on the index are always going to cause poor performance.  Stale statistics (e.g. sys.dm_db_stats_properties) and high amounts of white space per page (i.e. avg_page_space_used_in_percent column in sys.dm_db_index_physical_stats dmv) hold more relevance regarding performance issues than fragmentation alone.  Yes, highly fragmented indexes will generate more read-aheads and you typically do see stale statistics and higher levels of white space per page coupled with fragmentation, but fragmentation isn't directly tied to query plan optimizations nor how much memory loading the index from disk will actually consume.  Query plans are affected by statistics and your memory footprint bloats with more white space.  For instance, an index that is 99% fragmented but has less than 5% avg. white space and up-to-date statistics is likely not causing you drastic performance issues as compared to either a bad execution plan as a result of stale statistics or constant paging of an index that's too big to fully fit in memory because there's a significant amount of white space present per page.
If fragmentation is truly an issue, you can reduce it, ONLINE, by issuing an ALTER INDEX ... REORGANIZE statement as identified by Dan Guzman in the comments.  This won't create as streamlined an index as a REBUILD operation will, but it will reduce your fragmentation.  The key here is to identify windows of lower usage on your database and run it then.  This could be 15 minutes or multiple hours, obviously the longer the better, but the key here is this operation doesn't rollback and retains any progress made even if you kill it mid-execution.
If, in a perfect world where your fragmentation was eliminated, would it make more sense to utilize partitioning on this table?  Azure SQL Database does allow for table partitioning and Microsoft has a great article outlining some Partitioning strategies for Azure SQL Database.  If your data is non-volitile, partitioning it may help reduce maintenance needs, and if coupled with Table Compression, you may even be able to reduce your overall storage footprint as well.  Alberto Murillo's earlier answer alludes to utilizing Horizontal Partitioning based on a data region, and this approach may help create some maintenance windows for you as your data would be more regionally specific instead of global.
Transitioning to a partitioned table won't be easy with your current absence of maintenance windows, but you may be able to utilize an approach outlined by Maria Zakourdaev which uses Partitioned Views over the top of your current table and a new partitioned table to start partitioning future data.  As time goes on (and hopefully your old data is purged), you can eventually transition fully over to the partitioned table.  Again, I don't know your data or application, but maybe this approach is something you can employ.

A: Ideally, if an index is well designed, we shouldn't need to fiddle with the locking mechanism.
It sounds to me like you'll need to accept the locking to defrag the clustered index. If there's a good chance of this happening again, then look at redesigning the clustered index (it should be narrow, unique, static and ever-increasing).
I'm not sure what version of SQL Server you are using, but you could try the following in 2012:

*

*SET DEADLOCK_PRIORITY LOW - This tells the engine that the index rebuild should be the deadlock victim when/if one occurs.

*MaxDOP = 1 - The MaxDOP value limits the total number of logical CPUs used in parallel to create the index (2005 upwards - Enterprise edition only).
You can also change the page/row locks configuration, but I wouldn't do that without testing. You could just make the locking worse, especially if it's a badly designed index.
In 2014 onwards, there is the following option that basically tells the engine to allow other sessions to proceed and the online index operation to wait:
(WAIT_AT_LOW_PRIORITY (MAX_DURATION = 1 MINUTES, ABORT_AFTER_WAIT = SELF))

A: I have used the same approach as Oreo described above with great success!  The only thing that is missing is that you need to run an update script after you have copied the data and made the last renaming.
The update will look like this:
Insert from OldTable into LiveTable
  Where not exists (select From OldTable Where LiveTable.Key = OldTable.Key)

If Key is an Identity column, you need to use a slightly different approach.

A: Try to use sharding to distribute data of your database geographically. You then will be able to identify different maintenance windows for each geographic location, and the time to make maintenance will be shorter. This will also improve performance. You can learn more on this article. Do not wait for the database to get bigger.
With big databases and users connected 24 x 7, you need to use index reorganize and update only statistics that need to be updated (sp_updatestats) to minimize the time needed for maintenance and the impact to users.
Hope this helps.


text:
Q: Map canvas covers other elements on Android I'm writing an application on Android using PhoneGap and i want map to be 100% width and height of the screen. The problem is that all of DOM elements like divs are not displayed above my map when i'm running the app on android device. E.g. popups are triggered but they're under map canvas (setting high z-index doesn't help).
While running on browser (FF, Chrome) evrything works fine. Is it problem with Android default browser? Does anyone know how to solve this?
Example:
button

I can't make this simple JQM button display above the map.

A: So the solution is to be careful about order of including js/css files. So if you're writing an app using JQM, google-maps-api and phone gap you should remember:
First include css files e.g
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
Then this google api declaration

After that the jquery .js file

Next jquery ui map files like

And at last jquery mobile script file (I think this is where I made mistake)


text:
Q: Working with delegates Action So I am trying to authenticate some user on twitter api using LinqToTwitter.
public class PinAuthorizer : AuthorizerBase, IAuthorizer
{
        public PinAuthorizer();
        public PinAuthorizer(bool forceLogin);
        public PinAuthorizer(bool forceLogin, AuthAccessType accessType);
        public PinAuthorizer(bool forceLogin, AuthAccessType accessType, string preFillScreenName);

        public Func<string> GetPin { get; set; }
        public Action<string> GoToTwitterAuthorization { get; set; }
        public Task CompleteAuthorizeAsync(string pin);
}

The problem is I dont know how to work with this delegate. I'm trying:
 Authorizer = new PinAuthorizer {
                            CredentialStore = new InMemoryCredentialStore {
                                    ConsumerKey = ConsumerKey,
                                    ConsumerSecret = ConsumerSecret,
                                    ScreenName = Name
                            }
                    };
 WebBrowserControl.Navigate(Authorizer.GoToTwitterAuthorization);

I get null reference exception.
UPDATE: I'am not trying to understand why the null reference happens. I'm trying to understand how can I correctly use the delegate so I can go to the authorization url with my WebBrowser control. Please read the question before marking it as duplicate.


text:
Q: Компиляция итогового exe Нужно сделать готовый отдельный .exeшник из проекта. Вытаскивая из bin/debug получаю ошибку на другом компьютере. Как сделать так, чтобы после компиляции получался единый .exe, который можно было бы запустить на другом компьютере?
Помогите еще вот с чем: как поставить в настройки компилятора это:

Не могу найти

A: На другом компьютере надо установить .NET Framework. Если есть желание запускать его без установки фреймворка - попробуйте запускать его через Mono (Mono установки не требует).


text:
Q: java opening a socket at wrong ip address There are 2 backend machines which will provide the same content. I'm trying to create a round-robin setup and fail-safe so that if one goes down, the request should be sent to other.
As for the round-robin thing, my code is working fine.
For the fail-safe thing, I'm trying to change one IP to some invalid ip (on which no service is running) and then it should connect to other. But it is getting hung up on the line:
client = new Socket(ip, port);

What can be done for this? If I'm not getting connection in 2 seconds, I don't want to retry (if that is what java does, can I reduce the retry timeout?).
Also, after long time, it throws IllegalStateException (I was not expecting it at all)
Here is my constructor for Connect.java:
//Variable declartion

private static int balancer = 0;
private static boolean[] down = {false, false};
private static int[] countDown = {0, 0};
private static final int maxRequests = 10000;
private static int countRequests = 0;

//Constructor
public Connect() throws NullPointerException{
    int use = balancer;
    int flag = 0;

    countRequests = (countRequests + 1) % maxRequests;
    if(countRequests == 0){
        down[0] = down[1] = false;
    }

    if((balancer == 0 && down[0] == false) || down[1] == true){
        ip = Config.IP1;
        port = Config.PORT1;
        use = 0;
        System.out.println("balancer = 0");
    }
    else{
        ip = Config.IP2;
        port = Config.PORT2;
        use = 1;
        System.out.println("balancer = 1");
    }
     LOGGER.setLevel(Level.INFO);
     // Single simple socket
     try {
        client = new Socket(ip, port);
        System.out.println("client");
        dos = new DataOutputStream(client.getOutputStream());
        dis = new DataInputStream(client.getInputStream());
        if(client == null || dos == null || dis == null){
            throw new IOException("Connection could not be opened properly\n");
        }
        LOGGER.log(Level.INFO, "Connection to : " + ip + " Successfully opened");
        balancer = (balancer == 0) ? 1 : 0;
        countDown[use] = 0;
        flag = 1;
     } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
        countDown[use] ++;
        if(countDown[use] >= 3){
            down[use] = true;
        }
        LOGGER.log(Level.SEVERE, ": " + ip + " " + e.getMessage());
     }
     finally{       //if connection was not opened on first
         if(flag == 0){
             if(use == 0){
                 ip = Config.IP2;
                 port = Config.PORT2;
                 use = 1;
             }
             else{
                 ip = Config.IP1;
                 port = Config.PORT1;
                 use = 0;
             }
             try {
                    client = new Socket(ip, port);
                    dos = new DataOutputStream(client.getOutputStream());
                    dis = new DataInputStream(client.getInputStream());
                    if(client == null || dos == null || dis == null){
                        throw new IOException("Connection could not be opened properly\n");
                    }
                    LOGGER.log(Level.INFO, "Connection to  " + ip + " Successfully opened");
                    balancer = (balancer == 0) ? 1 : 0;
                    countDown[use] = 0;
                    flag = 1;
                 } catch (IOException e) {
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                    countDown[use] ++;
                    if(countDown[use] >= 3){
                        down[use] = true;
                    }
                    LOGGER.log(Level.SEVERE, ": " + ip + " " + e.getMessage());
                    throw new NullPointerException("Connection could not be opened properly on both machines\n");
                 }
         }
     }
}

What I expected was an IO/NullPointer-Exception and then catch block will be executed

A: How about using the default Socket() constructor, and then connect(SocketAddress, int), which allows you to specify a specific timeout?
Example:
import java.net.*;
public class Test {
  public static void main(String[] args) throws Exception {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(args[0], 80), 2000);
  }
}

You can see the timeout in action by timing it:
$ time java Test google.com

real    0m0.154s
user    0m0.079s
sys     0m0.022s

$ time java Test 192.168.2.123
Exception in thread "main" java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at Test.main(Test.java:5)

real    0m2.111s
user    0m0.076s
sys     0m0.026s


text:
Q: Selenium Firefox - Browser is under remote control I am using Firefox 55.0.2 (64-bit) with selenium. The code works fine, however I see an icon in Firefox saying Browser is under remote control and the URL is highlighted in orange as shown in below screen shot.

Is there a way to disable this message in Firefox?

A: You wouldn't get that in the previous versions of firefox (version 45 or below). Its just an update and cannot be disabled. Even google chrome shows a message(chrome is autmated by a software).  or you could just use the previous versions of the browser.

A: Maybe not related directly to selenium use,
But in case of getting stuck in "under remote control" after having launched firefox with a kind of:
firefox -marionette -foreground -no-remote -profile /path/to/existing/profile

It's because this way it toggles marionette:true in about:config,
Thanks to Firefox Stuck in Remote Control Mode for pointing to this marionette config entry


text:
Q: Firebase Database Structure Review to Review enter image description here

My Firebase Structure is below.
Review
    -userUid
        -shopUid
              -ReviewItem(Time, UserNick, ShopName...)

I want to make it possible that Review to Review(comment to comment) structure.
ex)
user1 Hi.
        -user2 Hello.
        -user3 HI.

    user2 Good
        -user1 Great.

Like this.
How to Change Database structure?
I attached firebase.json with comment.


text:
Q: Disposing All Child Controls and Data - C# I Load a User Control inside a panel, the user Control itself contains so many inner controls such as tab pages, panels, buttons and also inside its panels there will be some other user controls.
Let say I Load the Main User Control inside the MainPanel, If I use this:
MainPanel.Controls.Clear();

It will not clear the memory, so I use this instead:
while (MainPanel.Controls.Count > 0) MainPanel.Controls[0].Dispose();

But it seems it will Dispose the Main User Control and will clear memory just a little and I think all controls inside this user control still exist in the memory. How can I iterate recursively through all of the inner controls and dispose them one by one?
Furthermore, inside the user control, there are several grid controls that load some data. They are not binding to any database, just fetching some data by LINQ from the database and new command.
Do I need to destroy those data before disposing the control or they will be deleted from memory by control disposing?

A: https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged?view=netframework-4.8

Call Dispose when you are finished using the Component. The Dispose method leaves the Component in an unusable state. After calling Dispose, you must release all references to the Component so the garbage collector can reclaim the memory that the Component was occupying. For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.

for (int i = MainPanel.Controls.Count - 1; i >= 0; i--) {
    MainPanel.Controls[i].Dispose();
}

You don't need to dereference any other data. Only the controls so that they can be picked up by gc.
Bear in mind that if you dereference ControlA which has ObjectB, then ObjectB is also dereferenced and can be picked up.


text:
Q: Application of derivatives on trig functions The forward and backward movement of an air molecule in still air during the transmission of a middle C note is given by
$$x = A\sin (2272t)$$ where $t$ is the time in seconds and $A$ is the maximum displacement of the molecule. $A$ is related to the loudness of the sound.
Q: How many times does the molecule have a velocity of zero in 1 second?
So I have answered this question in two ways but they give me different answers and I would like to know why one works and the other one doesn't.
Method 1:

*

*Derive the function to get $x'=2272A\cos(2272t)$

*Calculated the frequency and got a frequency of approx 361

*since cosine has two zeros per period: $361\cdot 2 = 723$ times molecule has zero velocity in 1 second.

Method 2:

*

*Derived function as method 1.

*since cosine has zeros at every $n\pi/2$, equated $\cos(2272t)=n\pi/2$

*subbed $t=1$ and solved for $n$ and got $1446$ which is double method 1's answer.

The correct answer is method 1 but could anyone clarify why method 2 does not give me the same answer?

A: The function $\cos(x)$ has a zero at $x=\frac{\pi}{2}+n\pi$ for any integer $n$. There are two zeros per period $T=2\pi$. In saying that the cosine has a zeros at every $n\pi/2$, you doubled the number of such zeros.


text:
Q: Error: Cannot find module 'once' Error: Cannot find module 'once'
    at Function.Module._resolveFilename (module.js:337:15)
    at Function.Module._load (module.js:287:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/nodemon/node_modules/update-notifier/node_modules/latest-version/node_modules/package-json/node_modules/got/node_modules/duplexify/node_modules/end-of-stream/index.js:1:74)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)

I'm getting this error when I try running my server.js with nodemon. I looked in my node_modules folder and there is a 'once' folder in there. I tried
rm -rf node_modules
npm install

to remove the entire node_modules folder and reinstall but it didn't work. I also did
npm install --save once

and still didn't work.
This is package.json
{
  "name": "FullMean_Friends",
  "version": "0.0.1",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "body-parser": "latest",
    "express": "~4.2.0",
    "mongoose": "latest"
  }
}


text:
Q: Setting theta-ticks in matplotlib polar plots My question is related to the following:
Scatter polar plot in matlab
I tried looking online but couldn't find any with this axis; instead of the polar plot going 0 to 360 degrees how can I do -180 to 180 instead?

A: After creating the polar axis, you can simply set the ticks. Note that you have to set the ticks in radians and matplotlib will display in degrees.
Not quite sure how you want to deal the discrepancy at 180 and -180.
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
ax1.set_xticks(np.pi/180. * np.linspace(180,  -180, 8, endpoint=False))


text:
Q: Extra mouse in /dev/input I have an issue with two-finger scrolling on Google Chrome. I am using Ubuntu 16.04. When scrolling in the browser, the page randomly jumps backwards! I have seen a few similar bugs reported on Google Chrome website. When I digged into the issue, I found that I have 2 mouse devices in my /dev/inputs. mouse0 and mouse1. I am wondering if this is causing the problem. I have not connected any external mouse. I am using a Thinkpad X1. Is it possible that the mouse1 is actually the trackpad?
The issue wasn't there in Ubuntu 14.10.
What is the safest way to disable /dev/input/mouse1 and check if it resolves the problem?


text:
Q: MATLAB loop refactoring I'm curious to know if there is a better way to express the following loop:
To = 1;
fileName = "fourier/signal.txt";
spectrum_left(abs(spectrum_left) < 1e-3) = 0+0i;
Ts = 1 / Fs;
t = 0:Ts:To-Ts;
signal = load(fileName, "-ascii");
Ns = numel(signal);
Fs = Ns / To;

fr = f(abs(spectrum_left) > 0)
a = abs(spectrum_left(abs(spectrum_left) > 0))
p = angle(spectrum_left(abs(spectrum_left) > 0))

signal_synth = 0;
len = length(a);

for i=1:len
    a_i = a(i);
    p_i = p(i);
    f_i = fr(i);
    s_i = a_i * cos(2*pi*f_i*t + p_i)
    signal_synth = signal_synth + s_i;
end

Any suggestions are greatly appreciated. And Happy New Year!

A: In MATLAB, element-wise operators, that preceded by the period character (.), can be applied on arrays. I used (:) operator to convert the vectors to column vectors. Note that t is a row vector, when it is combined with column vectors the result will be a matrix that is formed by implicit expansion. In order to sum up the values the function sum is used that by default sums along the first dimension of the matrix and the result will be a row vector with the same size as t.
signal_synth = sum(a(:) .* cos(2 * pi * f(:) .* t + p(:)));

A more compact form using matrix multiplication:
signal_synth = a(:).' * cos(2 * pi * f(:) .* t + p(:));


text:
Q: set checkbox as checked/unchecked based on database jQuery I am trying to set data on localStorage as 1/0.Then if I get 1 from it I want to checked a checkbox else unchecked.I was wrote a code but it isn't working.And I can't find-out what I am doing wrong!
<label class="a-b-c">
  <input id="check-it" type="checkbox" name="check">
  Check.
</label>

$(window).load(set_func_o());
    function set_func_o(){
        try_it();
        $('#check-it').change(function(){
            var chk= this.checked ? '1':'0';
            localStorage.setItem('checkit-the-item',chk);
            try_it();
        });
        function try_it(){
        var check_stat= localStorage.getItem('checkit-the-item');
        check_stat === '1' ? $('#checkit').prop('checked',true):$('#checkit').prop('checked',false);
        }
    }

Suggestion please!

A: You are referencing a wrong element ID. Also, you can clean your code to only one prop setter.
function try_it(){
    var check_stat = localStorage.getItem('checkit-the-item');
    $('#check-it').prop('checked', check_stat === '1');
}


text:
Q: Ajax 'An error occurred trying to load resource' Safari I am trying to pass data via Ajax to userData.php but cannot figure out why I am getting the following error 'an error occurred trying to load resource'.
Here is the js code:
myApp.onPageInit('form-elements', function(page) {

    $$('.page[data-page=form-elements] form[name=form]').on('submit', function(e) {
    e.preventDefault();
    var formData = myApp.formToData(e.target);
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "//autoapp.webxdetroit.com/material/assets/custom/php/userData.php",
            // url: "assets/custom/php/userData.php",
            data: {userData : formData },
            headers: {
                "cache-control": "no-cache"
            },
            success: function( data ) {
                window.location.href='assets/custom/php/camera.php'
        },
            error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }

});

    });

});

Here is the php:
  <?php

session_start();

require_once "pdo.php";
require_once "util.php";

unset($_SESSION['user_id']); //To log the last user out
unset($_SESSION['employee_id']); //To log the last user out

//  Handle the incoming data
if ( isset($_POST['userData'])) {
   $msg = validateProfile();
   if( is_string($msg)){
     $_SESSION['error'] = $msg;
     header("Location: userData.php");
     return;
   }

// Set user data variable
$userData = $_POST['userData'];

$stmt = $pdo->prepare('INSERT INTO User (name, email, phone, vin, mileage, employeeid)
   VALUES(:nm, :em, :ph, :vin, :mi, :eid)');

 $stmt -> execute(array(
   ':nm' => $userData['input_name'],
   ':em' => $userData['input_email'],
   ':ph' => $userData['input_phone'],
   ':vin' => $userData['vin'],
   ':mi' => $userData['mileage'],
   ':eid' => '1')
 );

 $row = $pdo->lastInsertId();
 echo($row);

 // Set session user_id
 $_SESSION['user_id'] = $row;

 // redirect the browser to index.php
 $_SESSION['success'] = "User Added";
 header("Location: userData.php");
}

?>

<!DOCTYPE html>

   <meta charset="UTF-8">
   <title>Alex Lennard's Profile Add</title>

   <?php
   flashMessages();
   ?>

And here is the util.php:
<?php

function flashMessages(){
  if ( isset($_SESSION['error'])){
    echo('
'.htmlentities($_SESSION['error'])."
\n");
    unset($_SESSION['error']);
  }
  if ( isset($_SESSION['success'])){
    echo('
'.htmlentities($_SESSION['success'])."
\n");
    unset($_SESSION['success']);
  }
}

function validateProfile(){

  $userData = $_POST['userData'];

  if ( strlen($userData['input_name']) == 0 || strlen($userData['input_email']) == 0  ||
    strlen($userData['input_phone']) == 0  || strlen($userData['vin']) == 0  ||
    strlen($userData['mileage']) == 0 ){
    return "All fields are required";
  }
  if ( strpos($userData['input_email'], '@') === false){
    return "Email address must contain @";
  }
  return true;
}

?>

This code works OK on google chrome (desktop), but does not work in safari (desktop/mobile) or chrome (mobile).
If i submit a blank form in Safari then I will get a blank submission in my database but will still get the above error. As soon as I try to populate the fields nothing will go through.
Screenshot 1
Screenshot 2


text:
Q: Visio Document Variable I would like to store variable data inside of a Visio file similar to how you can in a Word file, but I am unable to find anything similar for Visio. A word example would be:
WordDocument.Variables("myVar").Value = "myVariable";

Alternatively, can you store a file (xml for instance) inside of a Visio file, then read and write to the file at run time?

A: You can use the Document's DocumentSheet, which is a normal shapesheet object, so you can add User cells and store your data there.

A: First option is already voiced by @Jon Fournier. DocumentSheet is a Visio way to store document-specific values. Check out also this article, which gives more details: http://visualsignals.typepad.co.uk/vislog/2011/11/shapes-with-global-values.html
The second option could be Document.SolutionXmlElement, which allows you to store arbitrary XML fragment in Visio file for a document.
https://msdn.microsoft.com/en-us/library/office/aa218416.aspx
Third option could be (note that this is a bit archaic) to create a hidden master and store document data in there (in it's ShapeSheet).
Note that Visio does not support "CustomDocumentProperties" the way some other Office application do. See more information here: https://social.technet.microsoft.com/Forums/office/en-US/85fbc601-1612-4e63-91f4-b900a59109bd/how-to-access-visio-document-properties-builtindocumentproperties-customdocumentproperties-from?forum=visiogeneral
Although there are also some "normal" office document properties which are exposed via API; likte "Title" and "Company" which can be accessed directly as document properties (i.e. "Document.Company"), user custom ole compound document properties not exposed directly and are not available with Visio API. If you are interested in that you might find out this topic useful: http://visguy.com/vgforum/index.php?topic=6535.0


text:
Q: Autolayout and UIScrollview and Child View Controller issues In my app I have an embedded child view controller into which at runtime I have to add one or more "Editor UIView"s based on data coming in from the server. I could model each "Editor" as a complete UIViewController in a xib file and add it at run time. The parent of the "Editor" has some items of its own (like titles and a couple of buttons) so I've tried to build a layered approach using a single child UIViewController and loading the "Editors" into its UIScrollview on the fly. However I can't get Autolayout to cooperate. This diagram shows the basic arrangement.

The problems start with just having the "Content View" embedded in the UIScrollview. I can get the content view to work OK with the scrollview. When I add the editor view and add runtime constraints to the content view, I get multiple auto layout complaints plus the scroll view content size is 0,0 so I am clearly not getting what I need.
Any ideas on how to approach this? I could always simply duplicate the child controller's extra items for each editor but it would be nice to have this work in this layered fashion.
Note I did this first with a UITableViewController where each editor is a UITableViewCell and that auto layout liked but I wanted to see if I could do it without the table. Maybe I will go back to that.
Added these at runtime:
_editor = [self editorForDataType];
[_contentView addSubview:_editor];

NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:_editor
                                                                  attribute:NSLayoutAttributeLeading
                                                                  relatedBy:0
                                                                     toItem:self.contentView
                                                                  attribute:NSLayoutAttributeLeft
                                                                 multiplier:1.0
                                                                   constant:0];
[self.contentView addConstraint:leftConstraint];

NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:_editor
                                                                   attribute:NSLayoutAttributeTrailing
                                                                   relatedBy:0
                                                                      toItem:self.contentView
                                                                   attribute:NSLayoutAttributeRight
                                                                  multiplier:1.0
                                                                    constant:0];
[self.contentView addConstraint:rightConstraint];

NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:_editor
                                                                  attribute:NSLayoutAttributeLeading
                                                                  relatedBy:0
                                                                     toItem:self.contentView
                                                                  attribute:NSLayoutAttributeTop
                                                                 multiplier:1.0
                                                                   constant:0];
[self.contentView addConstraint:topConstraint];

NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:_editor
                                                                   attribute:NSLayoutAttributeTrailing
                                                                   relatedBy:0
                                                                      toItem:self.contentView
                                                                   attribute:NSLayoutAttributeBottom
                                                                  multiplier:1.0
                                                                    constant:0];
[self.contentView addConstraint:bottomConstraint];

A: In the end the key to what I needed was the follow set of constraints, plus adding the constraints for the editor view in viewDidLayoutSubviews and saving a property for the content view Height.
In viewDidLoad I set the height property to the height of the editor view. Now it works great.

A: Your last two constraints are incorrect. You have leading to top and trailing to bottom, those should be top to top and bottom to bottom. However, those constraints probably aren't what you want. If it's the first editor view, you probably want the top constraint to the content view and a height constraint. For any subsequent ones, you should pin the top to the editor view above it, rather than the content view.


text:
Q: Finding values of dot products from a pyramid

Question: In the pyramid $ABCDE$, the base is a square with a side of length $5$ and $\vec{AD} \perp \vec{DE}$
    . The vector $\vec{AE}$ creates equal angles with the vectors $\vec{AD}$ and $\vec{AB}$. Let us denote $\vec{AB}=u$, $\vec{AD}=v$ and $\vec{AE}=w$ (See the figure):
(a.) Showing all working, find the numerical value of $w⋅ v$ and the numerical value of $w⋅ u$
(b.) Show that $EDC$ is a right-angle triangle.

What I have done to start (a) we have that
$$\begin{cases}
||u||=5 \\
||v||=5 \\
||w||=? \\
\cos(\theta)=\frac{\vec{w}\cdot \vec{v}}{||w||||v||} \\
\cos(\theta)=\frac{\vec{w} \cdot \vec{u}}{||w||||u||} \\
\end{cases}$$
So since AE creates equal angles with AD and AB we can equate the angle of dot product:
$$ \cos(\theta) = \cos(\theta) \Longrightarrow \frac{\vec{w}\cdot \vec{v}}{||w||||v||}=\frac{\vec{w} \cdot \vec{u}}{||w||||u||} $$
Then i don't know how to continue :(

A: I dont know at the moment a proof for b but in a take origin at $A $ from triangle rule we have $AE=AD+DE $ we want $AD.AE=AD (AD+DE)=|AD|^2+0=25$ as $AD$ is perpendicular to $DE $

A: you know that $\underline v\cdot\vec{DE}=0$ so the way to find $\underline w$ goes like this:
$$\underline w=\underline v+\vec{DE}\\\underline v\cdot\underline w=\underline v\cdot\left(\underline v+\vec{DE}\right)\\\underline v\cdot\underline w=\underline v\cdot\underline v+\underline v\cdot\vec{DE}\\\underline v\cdot\underline w=\underline v\cdot\underline v\\\underline v\cdot\underline w=\|\underline v\|\|\underline v\|\cos0\\\underline v\cdot\underline w=\|v\|^2\\\underline v\cdot\underline w=25$$
for $\underline u\cdot\underline w\,$ you are doing the same and get the same result.
for (b.) you have the following:$$\vec{EC}=-\underline w+\underline v+\underline u\\\implies\vec{EC}\cdot\underline u=\left(-\underline w+\underline v+\underline u\right)\cdot\underline u\\=-\underline w\cdot\underline u+\underline v\cdot\underline u+\underline u\cdot\underline u\\=-\|\underline u\|\|\underline w\|+0+\|u\|^2\\=-25+25\\=0$$ and you know that $\vec{EC}\cdot\underline u=\|\vec{EC}\|\|\underline u\|\cos\theta,\|\vec{EC}\|\ne0\ne\|\underline u\|\,$ therefore $\theta=90$
I see i came late but i'll answer nonetheless in case someone will see the question and will want to know the answer


text:
Q: Edit MP4 metadata using Python I need to give attributes (meta data) to a file in python code on Linux, specifically Ubuntu.
Specifically I need to set the author, title, album, etc. on MP4 files.

A: You could try with Mutagen or Tagpy
Both seem very straightforward, but I don't have any experience with them.

A: I know this post is ancient, but, If anyone is interested I put together some basic example python code.
I am focused on MP3s but going to expand it, just working on a custom MP3 Player with TKinter & Mutagen.
This example is strictly using Mutagen:
https://github.com/JayRizzo/MP3Player/blob/master/mp3TagEditor.py


text:
Q: How to More Efficiently Parse a Large File in Python to Cut Down on Run Time? I have a large text file (2,000,000+ lines) that I am attempting to read into a dataframe and then write to a csv file ultimately so it can be read into a database. Just wanted to state up front that I did not create the file and I cannot have the person who created the file modify it in any way, essentially I am stuck with the file as is and my goal is to parse it into a more usable formate. My code seems to work (I tested it on smaller subsegments of files) but when I attempt to process an entire file with over 2,000,000 rows, the program takes hours and hours to complete (like almost 20  hours!). I am trying to get some advice on how I could make this program run a lot faster as I have quite a few files to process.
Also, I am trying to improve my question writing so I have tried to include more detail about the problem, including snippets of code and an explanation of what I am trying to accomplish with each snippet. Please note that the code as it exists in full is listed at the end of my question as well as a sample file in full. The sample file has lines missing so the balances will not line up.
The current file is a list of account holders with their name and address, followed by accounts that they have and the transactions that occurred on the account over time. Once all the transactions have been listed for all the accounts a person has, the file then moves on to a new person and again lists all of their information (Name, address) and then all the transactions for their accounts. For each new account, there is a new header line that is either  DATE    DESCRIPTION            DEPOSIT     WITHDRAWAL         BALANCE  for a deposit type of account or DATE    DESCRIPTION          PRINCIPAL       INTEREST         BALANCE for a Loan type of account. Within the list of transactions, there are some transactions that are actual deposit or withdrawals or loan repayment transactions. There are also some BALANCE FORWARD transactions which denote the starting balance for an account at the beginning of the period. These balance forward transactions signify switching to another account for the same person. Lastly, there are some transactions that don't have a transaction amount and are essentially just a continuation of a description from the last transaction on the previous line.
The following are some examples of what the file looks like and some accompanying code that I use to parse these pieces of information:
Header to start off file:
ABC COMPANY
JAN 01 2019 TO DEC 31 2019
000000001
                      ABC COMPANY

      JOHN SMITH
      176 HUGH CRES
      NOWHERE ON
      Z9Z 9Z9

I generally ignore the first two lines of the file, the 3rd line is an account number, which I store in prev_line. The 4th line is a header of ABC COMPANY which denotes that there is an account holder's name and address that will follow after 2 blank lines. There may be multiple people on the account, so my code just reads in the first lines of this section as the primary name on the account and the rest is just grouped into "Other Information", the following are the columns of the dataframe (df) and how I read in a person's info into this dataframe for the acct_num, mem_name and other_mem_info columns:
df = pd.DataFrame(columns=['acct_num', 'mem_name', 'other_mem_info', 'acct_name', 'acct_type', 'trxn_date', \
                          'trxn_description', 'deposit', 'withdrawal', 'principal', 'interest', 'balance'])

if i > 1:
   prev_line = line.strip()
line = next(file)

# New person header
if line.strip() == new_person_header and i > 2:
   # Skip 2 blank lines after header
   blank = next(file)
   blank = next(file)
   i += 2

   # Account Number stored in prev_line, followed by name and remaining other info
   person_info.append(prev_line)
   name = next(file).strip()
   i += 1
   person_info.append(name)

   #Remaining other info
   line = next(file)
   i += 1
   while line.strip() != "":
           person_info.append(line.strip())
           line = next(file)
           i += 1

I check to see if the person I read in is the same as the last person I read in (therefore meaning that the information that follows is more account transactions for the same person). I clear the person_info variable after each iteration so that it can store the new person info on the next iteration:
if person_info != prev_person_info:  # Therefore not the same as past account holder, so add new account holder
       #Write to df new person
       df.loc[df_i] = [person_info[0], person_info[1], ' '.join(person_info[2:]), "", "", "", "", "", "",
                       "", "", ""]
       prev_person_info = person_info.copy()
       person_info.clear()
   else: #Therefore not a new person
       person_info.clear()

There are two transaction headers, one for Loans and one for deposits, in both cases the transaction header is followed by dashes:
  DATE    DESCRIPTION            DEPOSIT     WITHDRAWAL         BALANCE
 -----------------------------------------------------------------------

Or
 DATE    DESCRIPTION          PRINCIPAL       INTEREST         BALANCE
 -----------------------------------------------------------------------

When my code comes across a line in the file with all dashes, I use the prev_line variable to determine if this is a Deposit or Loan account:
#Setup to define what type of transaction - Loan or Deposit
elif line.strip() == new_trxn_header:
   if prev_line == deposit_trxn:
       loan_dep = "DEP"
   elif prev_line == loan_trxn:
       loan_dep = "LOAN"
   else:
       loan_dep = "ISSUE WITH TRANSACTION TYPE"
       print(loan_dep+line.strip() + " Line #" + str(i))
       exit()

In terms of transactions, typically the first transaction for a new account is the balance forward line which describes the account name:
JAN 01 19 BALANCE FORWARD: MY ACCOUNT TYPE                      3,135.32

It seems that this account name can be any length but is generally proceeded by BALANCE FORWARD and ends with the balance, so I split the string to get the name of the account and I also extract the date using a regex, I then write to the df the account info, storing the account name and opening balance. I have a counter called df_i which I increment after each time I add a new line to the dataframe:
elif balance_fwd_trxn in line and \
               len(re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())) > 0:
   #Therefore a Balance Forward Transaction - will want to put name of account and write to DF

   #Parse line to get date, account number and balance
   trxn_date = re.findall(r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}", line)[0] #Pick first element in list in case description has a date too
   balance_values = re.findall(r"\d*\.\d+", re.sub(",", "", line))
   querywords = line.split(balance_fwd_trxn, 1)[1].replace(",", "").split()
   resultwords = [word for word in querywords if word.lower() not in balance_values]
   account_name = ' '.join(resultwords)
   if len(balance_values) > 0:
       balance = format(float(balance_values[-1]), '.2f')
   else:
       balance = ""

   #Write Account Info
   df.at[df_i, "acct_name"], df.at[df_i, "trxn_date"], df.at[df_i, "trxn_description"], df.loc[df_i]["balance"], \
   df.loc[df_i]["acct_type"] = account_name, trxn_date, "BALANCE FORWARD", balance, loan_dep

   #Fill in previous row account details when we first created the person
   if (pd.isnull(df.at[df_i, 'acct_num'])):
       df.at[df_i, 'acct_num'], df.at[df_i, 'mem_name'], df.at[df_i, 'other_mem_info'] = df.at[df_i - 1, 'acct_num'],df.at[df_i - 1, 'mem_name'], df.at[df_i-1, 'other_mem_info']

   #Increment df_i for next row in df
   df_i += 1

The last thing that gets check is if the line in the file is an actual transaction. I then have a parsing function to handle these actual transactions:
elif len(re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())) > 0 and \
       balance_fwd_trxn  not in line and i > 2:
   append_description, trxn_date, new_description, deposit, \
   withdrawal, interest, principal, balance = parse_trx(line, loan_dep, i)

   if(append_description) : #Therefore not a transaction, just a continuation of previous transaction and need to append description
       df.at[df_i-1, "trxn_description"] = df.at[df_i-1, "trxn_description"].strip() + " " + new_description
   else: #Therefore real transaction
       df.at[df_i, "trxn_date"], df.at[df_i, "trxn_description"], df.at[df_i, "deposit"], df.at[df_i, "withdrawal"], \
       df.at[df_i, "interest"], df.at[df_i, "principal"], df.loc[df_i]["balance"], df.loc[df_i]["acct_type"] = \
               trxn_date, new_description.strip(), deposit, withdrawal, interest, principal, balance, loan_dep

       if (pd.isnull(df.at[df_i, 'acct_num'])):
           df.at[df_i, 'acct_num'], df.at[df_i, 'mem_name'], df.at[df_i, 'other_mem_info'], df.at[df_i, 'acct_name']  \
               = df.at[df_i - 1, 'acct_num'], df.at[df_i - 1, 'mem_name'], df.at[df_i - 1, 'other_mem_info'], \
                 df.at[df_i - 1, 'acct_name']

       # Increment df_i for next row in df
       df_i += 1

Parsing Transaction Function:
This function returns all the parsed transactional information for a regular transaction (append_description = False) and a transaction that is just a continuation of a description (append_description = True).
def parse_trx(line_string, account_type, i):
   append_description = False
   new_description =deposit = withdrawal = interest = principal = balance = trxn_date = ""
   if(len(re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())) == 0):
       print("Not a proper transaction, line: " + str(i) + " String: " + line_string.strip())
       exit()
   else:
       trxn_date = re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())[0]

   if line_string[69] != ".": #Therefore no balance and is a description which be appended
       append_description = True
       new_description = line_string.replace(trxn_date, "").strip()

   else: #Therefore has a balance and is a real transaction
       dollar_values = re.findall("\d*\.\d+", re.sub(",", "", line_string))
       new_description = line_string.replace(trxn_date, "").strip()
       new_description = new_description.replace("-", "").strip()
       new_description = new_description.replace(",", "")
       for amount in dollar_values:
           new_description = new_description.replace(amount, "").strip()
       new_description = ' '.join(new_description.split())
       balance = format(float(dollar_values[-1]), '.2f')

       if(account_type == "DEP" and len(dollar_values) == 2):
           # Determine if Withdrawal or Deposit
           if (line_string[38] == "."): #Therefore Deposit
               deposit = format(float(dollar_values[0]), '.2f')
               withdrawal = ""
               interest = ""
               principal = ""

           elif (line_string[53] == "."): #Therefore Withdrawal
               deposit = interest = principal = ""
               withdrawal = format(float(dollar_values[0]), '.2f')
           else:
               print("Issue with transaction - not proper Deposit type - on line: " + str(i) + " String: " + line_string.strip())
               exit()
       elif(account_type == "LOAN" and len(dollar_values) == 3):
           deposit = withdrawal = ""
           interest, principal = format(float(dollar_values[0]), '.2f'), format(float(dollar_values[1]), '.2f')
       else:
           print("Issue with transaction - not proper type - on line: " + str(i) + " String: " + line_string.strip() + " type: " + account_type)
           exit()

   return append_description, trxn_date, new_description, deposit, withdrawal, interest, principal, balance

The following is the code in full:
import re
import pandas as pd
import time
import datetime as dt

def parse_trx(line_string, account_type, i):
   append_description = False
   new_description =deposit = withdrawal = interest = principal = balance = trxn_date = ""
   if(len(re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())) == 0):
       print("Not a proper transaction, line: " + str(i) + " String: " + line_string.strip())
       exit()
   else:
       trxn_date = re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())[0]

   if line_string[69] != ".": #Therefore no balance and is a description which be appended
       append_description = True
       new_description = line_string.replace(trxn_date, "").strip()

   else: #Therefore has a balance and is a real transaction
       dollar_values = re.findall("\d*\.\d+", re.sub(",", "", line_string))
       new_description = line_string.replace(trxn_date, "").strip()
       new_description = new_description.replace("-", "").strip()
       new_description = new_description.replace(",", "")
       for amount in dollar_values:
           new_description = new_description.replace(amount, "").strip()
       new_description = ' '.join(new_description.split())
       balance = format(float(dollar_values[-1]), '.2f')

       if(account_type == "DEP" and len(dollar_values) == 2):
           # Determine if Withdrawal or Deposit
           if (line_string[38] == "."): #Therefore Deposit
               deposit = format(float(dollar_values[0]), '.2f')
               withdrawal = ""
               interest = ""
               principal = ""

           elif (line_string[53] == "."): #Therefore Withdrawal
               deposit = interest = principal = ""
               withdrawal = format(float(dollar_values[0]), '.2f')
           else:
               print("Issue with transaction - not proper Deposit type - on line: " + str(i) + " String: " + line_string.strip())
               exit()
       elif(account_type == "LOAN" and len(dollar_values) == 3):
           deposit = withdrawal = ""
           interest, principal = format(float(dollar_values[0]), '.2f'), format(float(dollar_values[1]), '.2f')
       else:
           print("Issue with transaction - not proper type - on line: " + str(i) + " String: " + line_string.strip() + " type: " + account_type)
           exit()

   return append_description, trxn_date, new_description, deposit, withdrawal, interest, principal, balance

new_person_header = "ABC COMPANY"
new_trxn_header = "-----------------------------------------------------------------------"
loan_trxn, deposit_trxn, balance_fwd_trxn = "DATE    DESCRIPTION          PRINCIPAL       INTEREST         BALANCE", "DATE    DESCRIPTION            DEPOSIT     WITHDRAWAL         BALANCE", "BALANCE FORWARD:"

df = pd.DataFrame(columns=['acct_num', 'mem_name', 'other_mem_info', 'acct_name', 'acct_type', 'trxn_date', \
                          'trxn_description', 'deposit', 'withdrawal', 'principal', 'interest', 'balance'])
loan_dep = ""

with open('somefile.txt', "r") as file:
   N = len(file.readlines())
   file.seek(0,0)
   i = 1
   df_i = 0
   num_members = 0
   person_info = []
   prev_person_info = []

   person_info.clear()
   prev_person_info.clear()
   start = time.time()

   while i < N:
    # Display progress to screen
       if i%10000 == 0:
           end = time.time()
           print("Lines Parsed: " + str(i) + " percent complete " + str(i*100/N) + \
                 "% Elapsed time " + str((end - start) // 60) + " min " + str((end-start) - 60*((end - start) // 60)) + " sec")

       if i > 1:
           prev_line = line.strip()
       line = next(file)

       # New person header
       if line.strip() == new_person_header and i > 2:
           # Skip 2 blank lines after header
           blank = next(file)
           blank = next(file)
           i += 2

           # Member number stored in prev_line, followed by name and remaining other info
           person_info.append(prev_line)
           name = next(file).strip()
           i += 1
           person_info.append(name)

           #Remaining other info
           line = next(file)
           i += 1
           while line.strip() != "":
                   person_info.append(line.strip())
                   line = next(file)
                   i += 1

           if person_info != prev_person_info:  # Therefore not the same as past member, so add new member
               #Write to df new person
               df.loc[df_i] = [person_info[0], person_info[1], ' '.join(person_info[2:]), "", "", "", "", "", "",
                               "", "", ""]
               prev_person_info = person_info.copy()
               person_info.clear()
           else: #Therefore not a new person
               person_info.clear()
       #Setup to define what type of transaction - Loan or Deposit
       elif line.strip() == new_trxn_header:
           if prev_line == deposit_trxn:
               loan_dep = "DEP"
           elif prev_line == loan_trxn:
               loan_dep = "LOAN"
           else:
               loan_dep = "ISSUE WITH TRANSACTION TYPE"
               print(loan_dep+line.strip() + " Line #" + str(i))
               exit()
       elif balance_fwd_trxn in line and \
                       len(re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())) > 0:
           #Therefore a Balance Forward Transaction - will want to put name of account and write to DF

           #Parse line to get date, account number and balance
           trxn_date = re.findall(r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}", line)[0] #Pick first element in list in case description has a date too
           balance_values = re.findall(r"\d*\.\d+", re.sub(",", "", line))
           querywords = line.split(balance_fwd_trxn, 1)[1].replace(",", "").split()

           resultwords = [word for word in querywords if word.lower() not in balance_values]
           account_name = ' '.join(resultwords)
           if len(balance_values) > 0:
               balance = format(float(balance_values[-1]), '.2f')
           else:
               balance = ""

           #Write Account Info
           df.at[df_i, "acct_name"], df.at[df_i, "trxn_date"], df.at[df_i, "trxn_description"], df.loc[df_i]["balance"], \
           df.loc[df_i]["acct_type"] = account_name, trxn_date, "BALANCE FORWARD", balance, loan_dep

           #Fill in previous row account details when we first created the person
           if (pd.isnull(df.at[df_i, 'acct_num'])):
               df.at[df_i, 'acct_num'], df.at[df_i, 'mem_name'], df.at[df_i, 'other_mem_info'] = df.at[df_i - 1, 'acct_num'],df.at[df_i - 1, 'mem_name'], df.at[df_i-1, 'other_mem_info']

           #Increment df_i for next row in df
           df_i += 1

       elif len(re.findall(r"(?:^JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{2} \d{2}",line.strip())) > 0 and \
               balance_fwd_trxn  not in line and i > 2:
           append_description, trxn_date, new_description, deposit, \
           withdrawal, interest, principal, balance = parse_trx(line, loan_dep, i)

           if(append_description) : #Therefore not a transaction, just a continuation of previous transaction and need to append description
               df.at[df_i-1, "trxn_description"] = df.at[df_i-1, "trxn_description"].strip() + " " + new_description
           else: #Therefore real transaction
               df.at[df_i, "trxn_date"], df.at[df_i, "trxn_description"], df.at[df_i, "deposit"], df.at[df_i, "withdrawal"], \
               df.at[df_i, "interest"], df.at[df_i, "principal"], df.loc[df_i]["balance"], df.loc[df_i]["acct_type"] = \
                       trxn_date, new_description.strip(), deposit, withdrawal, interest, principal, balance, loan_dep

               if (pd.isnull(df.at[df_i, 'acct_num'])):
                   df.at[df_i, 'acct_num'], df.at[df_i, 'mem_name'], df.at[df_i, 'other_mem_info'], df.at[df_i, 'acct_name']  \
                       = df.at[df_i - 1, 'acct_num'], df.at[df_i - 1, 'mem_name'], df.at[df_i - 1, 'other_mem_info'], \
                         df.at[df_i - 1, 'acct_name']

               # Increment df_i for next row in df
               df_i += 1

       i += 1

# Clean up dataframe and write to file
df = df.fillna('')
print(df.to_string())
df.to_csv('somefile_write.csv',index=False)
# Display total elapsed time
print("Lines Parsed: " + str(i) + " percent complete " + str(i*100/N) + \
                 "% Elapsed time " + str((end - start) // 60) + " min " + str((end-start) - 60*((end - start) // 60)) + " sec")

Sample File:
ABC COMPANY
JAN 01 2019 TO DEC 31 2019
000000001
                      ABC COMPANY

      JOHN SMITH
      176 HUGH CRES
      NOWHERE ON
      Z9Z 9Z9

                                 ACC: 000000001              PAGE:    1

   DATE    DESCRIPTION            DEPOSIT     WITHDRAWAL         BALANCE
 -----------------------------------------------------------------------

 JAN 01 19 BALANCE FORWARD: ACCOUNT #1                            222.13
 JAN 31 19 DIVIDEND                   .63                         222.76
 AUG 20 19 DEPOSIT                  20.00                         242.76

   DATE    DESCRIPTION            DEPOSIT     WITHDRAWAL         BALANCE
 -----------------------------------------------------------------------

 JAN 01 19 BALANCE FORWARD: ACCOUNT #2                          1,695.04
 JAN 31 19 INTEREST                  2.16                       1,697.20
000000009
                      ABC COMPANY

      PERSON NUMBERONE
      PERSON NUMBERTWO
      1212-250 SOMEROAD RD
      SOMEPLACE AB
      Z9Z 9Z9

                                  ACC: 000000009              PAGE:    1

   DATE    DESCRIPTION            DEPOSIT     WITHDRAWAL         BALANCE
 -----------------------------------------------------------------------

 JAN 01 19 BALANCE FORWARD: ACCOUNT #1                          1,006.30
 JUL 17 19 E/C RE JULY16/19
 JUL 31 19 INTEREST                   .18                       1,006.85
 DEC 02 19 TO ACC # 4736

   DATE    DESCRIPTION            DEPOSIT     WITHDRAWAL         BALANCE
 -----------------------------------------------------------------------

 JAN 01 19 BALANCE FORWARD: ACCOUNT #2                            135.91
 JAN 31 19 INTEREST                   .17                         136.08
 FEB 28 19 INTEREST                   .16                         136.24
000000053
                      ABC COMPANY

      PERSON NUMBERTHREEE
      PERSON NUMBERFOUR
      28 SOMECOURT CRT
      SOMECITY QC
      Z9Z 9Z9

                                  ACC: 000000053              PAGE:    5

   DATE    DESCRIPTION          PRINCIPAL       INTEREST         BALANCE
 -----------------------------------------------------------------------

 JAN 01 19 BALANCE FORWARD: ACCOUNT #5                          2,538.96
 JAN 01 19 LOAN PAYMENT            840.48-          8.52-       1,698.48