text:
Q: Design java swing jframes I work with java swing application .i want to design frame1(Main) consists three parts. Header space.and sidebar(left-jpannel).then remaining area body like website.Sidebar consists three jbuttons if click the button1 i want to display jframe2 in body area.and click button2 close jframe2 display jframe3 in body area.Like body changes in webapplication if click the botton.Any possible ways please suggest me.
package javaapplication8;
public class Mainframe extends javax.swing.JFrame {
/**
 * Creates new form Mainframe
 */
public Mainframe() {
    initComponents();

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jPanel3 = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBackground(new java.awt.Color(51, 153, 255));
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Side bar"));
    jPanel1.setForeground(new java.awt.Color(0, 51, 255));

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("jButton2");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jButton3.setText("jButton3");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    jButton4.setText("jButton4");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton1)
                .addComponent(jButton2)
                .addComponent(jButton3)
                .addComponent(jButton4))
            .addContainerGap(50, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(35, 35, 35)
            .addComponent(jButton1)
            .addGap(45, 45, 45)
            .addComponent(jButton2)
            .addGap(57, 57, 57)
            .addComponent(jButton3)
            .addGap(43, 43, 43)
            .addComponent(jButton4)
            .addContainerGap(171, Short.MAX_VALUE))
    );

    jPanel2.setBackground(new java.awt.Color(0, 204, 255));
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Header"));

    jLabel1.setText("NOT CHANGE");

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(61, 61, 61)
            .addComponent(jLabel1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addContainerGap(75, Short.MAX_VALUE))
    );

    jPanel3.setBackground(new java.awt.Color(255, 255, 255));
    jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Body"));

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 436, Short.MAX_VALUE)
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
     frame1 n = new frame1();
    n.setVisible(true);
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    frame2 n = new frame1();
    n.setVisible(true);
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
   frame3 n = new frame1();
    n.setVisible(true);
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
  frame4 n = new frame1();
    n.setVisible(true);
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Mainframe().setVisible(true);
        }
    });
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration

}
If click jbutton1 new frame open.but i want to change body area and display frame2 .Like web application.


text:
Q: Android - check from web site if Chrome app has storage permission Currently users download an APK from my site. However, some users didn't give access to Chrome to Storage so they get this error:

So users need to give Storage permission to Chrome.
My question is whether I can check before the user click to download the APK (for example, with JavaScript), if Chrome has that permission, and if not instruct the user what he should do.

*

*Note 1: I know how an app can check it for itself - this is not
my question.

*Note 2: I know also how can a site check if he has
permissions - this is not my question.

A: I would say that you cannot do that.
First, let's look at how the Chrome android application check if the storage is granted.
You can use some tools such as jadx-gui to see the code of the chrome application, inside it, search for permission checking. Here we are interested in "WRITE_EXTERNAL_STORAGE", you can see that this permission is checked inside the DownloadController class, reading a bit how this class work allow us to understand that when something want to download any file, and want to save it, first they check if the permission is granted, if it is not, they display an alert dialog (the one you showed in your question).
The problem with this, is that with JavaScript you cannot interact with methods inside the chrome application if they are not any interface setup.
Solution?
The best thing you can do is to put a message on your website before the user download the application.
Trying to figure out a solution for the Chrome android application is not a good idea because that would be very difficult and pointless for any other web browser, because they all manage permission (such as storage) in different way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting Summed Collection by Timestamp In a previous post I asked about getting totals which ended up being the sum() of the values in Laravel. When the data returns, however, it's only outputting the sum without any other information that would normally be output as well (eg: relations, timestamps, etc). Normally this wouldn't be an issue if I were just taking the sum of everything as one number.
Below is the hard-coded example of the visual I am recreating and below that is the data that creates it.

data: [{
                period: '2016-04',
                views: 2666,
            }, {
                period: '2016-05',
                views: 2778,
            }, {
                period: '2016-06',
                views: 4912,
            }, {
                period: '2016-07',
                views: 3767,
            }, {
                period: '2016-08',
                views: 6810,
            }, {
                period: '2016-09',
                views: 5670,
            }, {
                period: '2016-10',
                views: 4820,
            }, {
                period: '2016-11',
                views: 15073,
            }],

So without writing loops, what's the best way to go about getting the daily sum of visitors across all posts for whatever given period. Basically, one user owns many posts and each post has many visitors, so below is how I'm getting the sum of them all, but as you can see above, I need sums for each day based on the created_at timestamp in the visitors table.
return Post::where('user_id', Auth::user()->id)->withCount(['visitors' => function($query)
        {
            $query->where('created_at', '<=', Carbon\Carbon::now())->where('created_at', '>=', Carbon\Carbon::yesterday());
        }])->get()->sum('visitors_count');

A: Im not familiar with Laravel. So I can show you how the query would be write in mySql and maybe you can translate:
You use DATE() to truncate the time part so every one have same date yyyy-mm-dd, then you can GROUP BY those days together to COUNT(visitors)
You need parameters @user_id, @start_range, @end_range
Be carefull how you setup @end_range. If you use @end_range = 2016-11-17' then '2016-11-17 10:10:00' will be out that range. So you probaly should use 2016-11-17 23:59:59
 SELECT DATE(created_at), count(visitors)
 FROM posts
 WHERE user_id = @user_id
   AND created_at BETWEEN @start_range
                      AND @end_range
 GROUP BY DATE(created_at)

A: How about something like this?
function postsPerPeriod()
{
    $posts = Post::orderBy('created_at')->get()->groupBy(function ($date) {
        return Carbon::parse($date->created_at)->format('m');
    });

    return $posts->map(function ($month) {
        return $month->sum('visitors');
    })->toArray();
}

It will group the posts by month then count the number of visitors in each  month and return an associative array of months to post. You can change the array keys by changing the format parameter of that gets passed to Carbon.

A: The basic schema exists as such
Users:
-id (A user owns many posts; Each post has many visitors)
... (etc.)

Posts:
-id (this is not the primary identifier)
-uuid (this is the value that matters)
-user_id (Foreign Key)
... (etc.)

Visitors:
-id
-visitor_id
-posts_uuid (Foreign Key)
-created_at
-updated_at

So it has to be visitors rows created at a certain time period for any post owned by a user.

A: I solved the issue with some input from above. I'm using the relationship to grab the content in a backwards manner, which is perfectly fine with me. Below is the final function used:
public function displayPeriodOverPeriodGraphics()
    {
        return dd(Visitor::all()->where('posts.user_id', Auth::user()->id)->groupBy(function($query)
        {
            return Carbon\Carbon::parse($query->created_at)->format('d');
        })->map(function($total)
        {
            return $total->count();
        }));
    }


text:
Q: Statistics and Probability. Please show solution Miss Romero noted that the mean scores of a random sample of 15 grade 8 students who had taken a special test were 80.5. If the standard deviation of the scores was 3.1 and the sample came from an approximety normal population, find the interval estimate of the population mean, using 95% confidence

A: Assuming a normal distribution:
Subtract 1.95*3.1/sqrt(8) to the mean. That's the lower bound.
Add 1.95*3.1/sqrt(8) times the standard deviation to the mean.That's the upper bound.
Sometimes that 1.95 coefficient will get rounded up to 2. Also, some people define the standard deviation in terms of n (sample size) while others in terms on (n-1). You may have to divide by sqrt(7) instead of sqrt(8)


text:
Q: How do you decide which typed array to use? I am trying to create a view of ArrayBuffer object in order to JSONify it.
var data = { data: new Uint8Array(arrayBuffer) }
var json = JSON.stringify(data)

It seems that the size of the ArrayBuffer does not matter even with the smallest Uint8Array. I did not get any RangeError so far:) If so, how do I decide which typed array to use?

A: You decide based on the data stored in the buffer, or, better said, based on your interpretation of that data.
Also an Uint8Array is not an 8 bit array, it's an array of unsigned 8 bit integers. It can have any length. A Uint8Array created from the same ArrayBuffer as a Uint16Array is going to be twice as long, because every byte in the ArrayBuffer is going to be "placed" as one element of the Uint8Array, while for the Uint16Array each pair of bytes is going to "become" one element in the array.
A good explanation of what happens is if we try thinking in binary. Try running this:
var buffer = new ArrayBuffer(2);
var uint8View = new Uint8Array(buffer);
var uint16View = new Uint16Array(buffer);

uint8View[0] = 2;
uint8View[1] = 1;

console.log(uint8View[0].toString(2));
console.log(uint8View[1].toString(2));
console.log(uint16View[0].toString(2));

The output is going to be
10
1
100000010

because displayed as an unsigned 8 bit integer in binary, 2 is 00000010 and 1 is 00000001. (toString strips leading zeroes).
Uint8Array represents an array of bytes. As I said, an element is an unsigned 8 bit integer. We just pushed two bytes to it.
In memory those two bytes are stored side by side as 00000001 00000010 (binary form again used to make things clearer).
Now when you initialize a Uint16Array over the same buffer it's going to contain the same bytes, but because an element is a unsigned 16 bit integer (two bytes), when you access uint16View[0] it's going to take the first two bytes and give them back to you. So 0000000100000010, which is 100000010 with no leading zeroes.
If you interpret this data as base 10 (decimal) integers you'll know it's 0000000100000010 to base 10 (258).
Neither Uint8Array nor Uint16Array store any data themselves. They are simply different ways of accessing bytes in an ArrayBuffer.
how one chooses which one to use? It's not based on preference but on the underlying data. ArrayBuffer is to be used when you receive some binary data from some external source (web socket maybe) and already know what the data represents. It might be a list of unsigned 8 bit integers, or one of signed 16 bit ones, or even a mixed list where you know the first element is an 8 bit integer and the next one is a 16 bit one. Then you can use DataView to read typed items from it.
If you don't know what the data represents you can't choose what to use.


text:
Q: Possible to extend static SQL statements with dynamic parts? I'd like to create a Oracle package where I have a procedure that executes some dynamic SQL. This is no problem if I'm doing it all dynamic with EXECUTE IMMEDIATE but it would be better if the static parts of the query could be coded static (to have compile time checking).
Example of fully dynamic query:
-- v_stmt is built dynamically.
v_stmt := 'SELECT count(*) FROM <here some joins> WHERE <here some conditions>';
EXECUTE IMMEDIATE v_stmt
  USING v_param1, v_param2
  RETURNING INTO v_count;

Example of what I tried to make the FROM-part static:
-- v_stmt is built dynamically.
v_stmt := 'SELECT count(*) FROM my_package.my_function(:param1, :param2) WHERE <here some conditions>';
EXECUTE IMMEDIATE v_stmt
  USING v_param1, v_param2
  RETURNING INTO v_count;

FUNCTION my_function(
  i_param1 IN VARCHAR2,
  i_param2 IN NUMBER
)
RETURN SYS_REFCURSOR
AS
  v_cursor SYS_REFCURSOR;
BEGIN
  -- Open a cursor for different queries depending on params.
  IF i_param2 = 1 THEN
      OPEN v_cursor FOR <some static query>;
  ELSE
      OPEN v_cursor FOR <some other static query>;
  END IF;
  RETURN v_cursor;
END;

This doesn't work because it's not possible to select from a SYS_REFCURSOR (at least that's what I found with Google).
Is there any way to reach this goal?
edit: As requested, here are some examples:
Static queries:
SELECT a.*, ca.CUS_ID FROM adresses a INNER JOIN customer_adresses ca ON (ca.adr_id = a.adr_id);
SELECT p.*, cp.CUS_ID FROM persons p INNER JOIN customer_persons cp ON (cp.per_id = p.per_id);

Then they are extended dynamically like the following examples:
-- Checks if there is an adress in the customer where the zip is null.
SELECT count(*) FROM <static adresses query> q WHERE q.cus_id = :param1 AND a.zip IS NULL;
-- Checks if there is at least one person in the customer.
SELECT count(*) FROM <static persons query> q WHERE q.cus_id = :param1;

A: Sorry, but why the need to do this?  Seems you're over complicating things by introducing a function that will return different types of data/tables depending on the parameter list.  Very confusing imo.  Besides, you have to do the work somewhere, you're just trying to hide it in this function (inside if param1=this then x if param1=that then y...)
Besides, even if you did implement a cursor function (even pipelined), it would be a bad idea in this case because you'd be forcing Oracle into doing work that it wouldn't necessarily need to do (ignore all the context switching for now).  To just get a count, you'd have Oracle grab each an every row result and then count.  Many times Oracle can just do a fast full index scan to get the count (depending on the query of course).  And often same query run multiple times will not need to do all the work each time if blocks are found in buffer cache.  I'd challenge you to run the count multiple times using straight SQL vs using a function returning a cursor.  You might be surprised.  And to my knowledge (check me on this) the new 11g function result cache won't work on a pipelined functions or a function returning a ref cursor (along with other issues like invalidations due to relies on tables).
So, what I'm saying is why not just do: select count(1) into v_variable from ...;
If you want to hide and modularize, then just know what you're potentially losing.

A: You may want to open a query in function1 and then pipeline the results of it as a table to function2 which then will add a where clause to this "table"
In this case you'll want to rewrite your function1 as a pipelined table function
v_stmt := 'SELECT count(*) FROM table(my_package.my_function(:param1, :param2)) WHERE <here some conditions>';
EXECUTE IMMEDIATE v_stmt
  USING v_param1, v_param2
  RETURNING INTO v_count;

CREATE TYPE object_row_type AS OBJECT (
  OWNER              VARCHAR2(30),
  OBJECT_TYPE        VARCHAR2(18),
  OBJECT_NAME        VARCHAR2(30),
  STATUS             VARCHAR2(7)
);

CREATE TYPE object_table_type AS TABLE OF object_row_type;

FUNCTION my_function(
  i_param1 IN VARCHAR2,
  i_param2 IN NUMBER
)
RETURN object_table_type PIPELINED AS
BEGIN

A: You can have compile time checking of expressions with Oracle expression filter.
It's probably more complicated than the other solutions, but if you really need to verify your conditions it can be helpful.


text:
Q: How do I pass data to modal view in ASP.NET MVC I am having problems passing data to modal view. Either modal view doesn't open at all or reads data from first item every time I open it.
The biggest problem I have is that I don't know jQuery.
I want a button to open a modal that reads a variable of my item in this case item.Code. Items are in a foreach loop.
This is how i want my code to look.

@foreach (var item in Model)
{

@item.Name

}

I tried it with and without a partial view.
This is the code I currently have which just opens a modal window but doesn't show anything else.
I know the problem is in id's, but I tried to change all id's to unique ones which caused even more problems.
    @foreach (var item in Model)
{

@item.Name

    <input class="btn btn-default" type="button" value="Details" id="@item.id" onclick="Details(this.id);" />

Modal title

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    @Html.Raw(item.Code);

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

}

Thank you!

A: Eg. This is the your html after the complete the forLoop

Item Name - 1

          <button type="button" data-item="Item Name - 1" class="btn btn-default clsDetails">Details</button>

Item Name - 2

          <button type="button" data-item="Item Name - 2" class="btn btn-default clsDetails">Details</button>

Item Name - 3

          <button type="button" data-item="Item Name - 3" class="btn btn-default clsDetails">Details</button>

HTML Modal

Modal title

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

Scripts
$(document).ready(function(){
    $(document).on("click",".clsDetails",OpenModalPopUp);
});

function OpenModalPopUp(){
   var itemName = $(this).data("item");
   alert(itemName);
   $('#dvData').html(itemName);
   $("#myModal").modal();
}


text:
Q: FabricJS CurvedText object (extended) is not getting displayed on updating spacing and text properties I have updated fabric CurvedText extension because of our requirement is something different. I want to set auto spacing between characters as it covers full circle. I got solutions after updating code in fabric CurvedText extension. While I am changing text of the object (on keyup event of textbox), I recalculate spacing and setting that spacing and text via setText and set("spacing", val) properties. In some situations, I can not see object on canvas but I can see pointer of the object on canvas mouse hover effect.
Remove characters from the textbox in this snippet and object will be hide after you will remove some characters.
Same thing happens when I add characters in the textbox.
Updated curved text extension.

var radius = 100;
var circum = Math.floor(2 * Math.PI * radius);
var spacing = 0;
var fontFamily = 'Arial';
var fontSize = 30;

var text;
var lineHeight = 1;
var topa = 100;
var left = 200;

var char = 0;
var textWidth = 0;

var obj;
var canvas, ctx;

$(document).ready(function () {

    canvas = new fabric.Canvas('c');
    ctx = canvas.getContext("2d");

    text = $('#uppertext').val();

    spacingOperation();

    var upperText = new fabric.CurvedText(text, {
        radius: radius,
        top: topa,
        left: left,
        fontFamily: fontFamily,
        fontSize: fontSize,
        lineHeight: lineHeight,
        spacing: spacing,
        originX: 'center',
        hasControls: true,
        hasBorders: true,
        selectable: true,
        textAlign: 'center'
    });
    canvas.add(upperText).renderAll();

    $('#uppertext').on('keyup', function () {
        text = $('#uppertext').val();

        setObjects();
        if (spacingOperation())
        {
            setProps();
            canvas.renderAll();
        }
    });
});

function spacingOperation() {
    textWidth = getTotalTextWidth();
    spacing = 0;
    textWidth = getTotalTextWidth();
    var diff = Math.ceil(circum - textWidth);
    spacing = Math.ceil(diff / char);
    return true;
}

function getTotalTextWidth()
{
    ctx.font = fontSize + 'px ' + fontFamily;
    char = text.length;
    txtWidth = Math.ceil(ctx.measureText(text).width + (spacing * char));
    return txtWidth;
}

function setObjects() {
    canvas.setActiveObject(canvas.item(0));
    obj = canvas.getActiveObject();
}

function setProps() {
    obj.set('spacing', spacing);
    obj.setText(text);
    obj.setCoords();
}
<!DOCTYPE html>

        <canvas id="c" width="400" height="400" style="border:1px dotted #000;"></canvas>

        Upper Text : <input type="text" id="uppertext" value="UTXXXXXXXXXXXXXUTXXXXXaaaaaaaawwwwwwwwwXXXXXXXXUTXXXXXXXXXXXXXUTXXXXXXXXXXXXX" />

A: I have looked into you code and changed one line in fabric curvedtext extension from ctx = new fabric.Canvas('c').getContext('2d'); to ctx = fabric.util.createCanvasElement().getContext('2d'); and it is working perfectly fine.


text:
Q: Sending live update notifications for website This might be a bit of a raw question (as in I haven't got much to work with), but here it is anyways:
I have a website with news added regularly. I would like to create an app that notifies the user when a news story is added. Any idea how this can be achieved? I don't have much server side programming experience.
I did a bit of searching around and found GCM for android and read through the setup process but it seems more for individual notifications rather than live updates because you need to use a registration ID and can only send to 1000 at once (I will have over 50,000 users day one)(Also, what happens if two devices have the same registration ID?). It is also somewhat complicated to understand, especially setting up the server side of it. I also found APN for iOS but it also seems similar and way too complicated to set up. I would love for someone to point me in the right direction.
Or a way to give live RSS updates will do as well because I have RSS set up.
I could check the RSS for any modifications at a set time interval but I want to avoid downloading the RSS feed repeatedly. (I will have to do that if nothing else works...)
Thanks in advance.

A: Here are some links that can help you out!!
http://kyleroderick.com/writing/live-stream-notifications/
http://www.airbop.com/
http://www.theverge.com/2015/3/26/8293353/periscope-live-streaming-twitter-meerkat
https://parse.com/


text:
Q: Detecting multiple QR codes with ZXing for javascript form camera I'm using the code here: https://www.dynamsoft.com/codepool/html5-barcode-reader-javascript-webassembly.html to detect QR codes from camera. Everything is fine with a single QR code, but I want to be able to detect multiple QR codes so I change the code ZXing._decode_qr(decodePtr); to ZXing._decode_qr_multi(decodePtr); without success, it seems it detects only the first seen QR code.
That's weird because if instead I load (like here: https://github.com/yushulx/zxing-cpp-emscripten) an image with multiple QR codes and call ZXing._decode_qr_multi(decodePtr);, all QR codes are detected.
Can you help me, please?
TIA

A: Solved!
The camera resolution was too low. Increasing the resolution fixed everything


text:
Q: How to keep track of the index in an array I need to create a stats sheet that records the amount of touchdowns performed by a certain team. I have it working for the first round when it records all 8 teams, however in the semifinals since only 4 teams make it, it does not keep track of what index the winning teams were on and just couts the stats in a regular order from 0 - 4. Ive been thinking for a couple days now on how I could possibly overcome this but I havent been able to find a solution yet.
the stats table that is outputted
Please let me know if i can contribute anymore information to make my question less vague and easier for you to understand. I appreciate all the help, thank you.


text:
Q: How to ensure that LaTeX-generated pdfs print correctly from print-on-demand services I've just bought printed copies of a pdf-booklet I've made using luaLaTeX. The "print ready copy" created during the Lulu upload process looks fine in the electronic version and when printed on my local printer. However, the printed copies from Lulu lack some characters from one of the fonts used in the document.
The document is typeset in Biolinum with a couple of symbols from MarVoSym and FontAwesome and a couple of characters from Computer Modern. The font-information extracted using pdffonts on the "print ready copy" from Lulu indicates that all fonts are embedded and subsetted:

name                                 type              emb sub uni object ID
------------------------------------ ----------------- --- --- --- ---------
QNTGDG+LinBiolinumO                  CID Type 0C       yes yes yes      9  0
YCZZZO+LinBiolinumOB                 CID Type 0C       yes yes yes     16  0
TIILYD+LinBiolinumOI                 CID Type 0C       yes yes yes     32  0
NJDZPD+MarVoSym                      Type 1            yes yes no      39  0
ZRZEPL+FontAwesome                   CID Type 0C       yes yes yes     43  0
KVFQUZ+CMSY8                         Type 1            yes yes no      71  0
YGYBQB+CMMI8                         Type 1            yes yes no      75  0
TXCQMU+LinBiolinumOBO                CID Type 0C       yes yes yes    106  0

The missing characters are from FontAwesome. Specifically, the two used symbols from FontAwesome are InfoSign (U+F05A) and ExclamationSign (U+F06A). These symbols are the only two symbols used from FontAwesome and were inserted in the document using the \faInfoSign and \faExclamationSign commands from the fontawesome package. Can I do something from the LaTeX-end to ensure that all fonts in my pdf will show up in the printed copy?
Some forum posts on the Lulu.com site indicate that fonts must not only be embedded as a subset but rather be fully embedded. Is it possible to configure luaLaTeX to not subset the embedded fonts?
Any other advice on ensuring compatibility with online print on demand services is greatly appreciated.

A: I do not know of such an option within any tex editor. But if you need a quick fix, try saving the document as a .png using GIMP (www.gimp.org). It will rule out any font problems but introduces large file size problems as mentioned by cfr. Providing them with an image for every page rules out any problems other than mismatched rgb/cymk and such.

A: When facing such a problem some time ago (in my case, the main font was not recognized at all by the printer), I decided to convert all fonts to curves.
Of course, this blows up file-size (can be more than ten times the original size), and the resulting pdf is no longer a good choice for on-screen reading, but printing on paper is absolutely safe.
Although I am sure there are also open-source solutions for automatically performing such a text-->curves conversion, I used Adobe Acrobat for that. (See e.g. https://forums.adobe.com/thread/319641)

A: I suppose that you load the marvosym and awesome packe not before fontspec. This works without a problem with lualatex (up-to-date TL2014):
\documentclass{article}
\usepackage{fontawesome}
\usepackage{marvosym}
\usepackage{fontspec}
\usepackage{libertine}
\usepackage[english]{babel}

\begin{document}
\sffamily
foo \Telefon\ from MArvoSym,
\faInfoSign\ and \faExclamationSign\ commands from the awesome package

\end{document}

name                     type              encoding         emb sub uni object ID
------------------------ ----------------- ---------------- --- --- --- ---------
ALMMHG+LinBiolinumO      CID Type 0C       Identity-H       yes yes yes      4  0
EDYICZ+MarVoSym          Type 1            Builtin          yes yes no       5  0
ZRZEPL+FontAwesome       CID Type 0C       Identity-H       yes yes yes      6  0
EUQFZF+LinLibertineO     CID Type 0C       Identity-H       yes yes yes      7  0

A: For whatever it's worth, this is still a problem with TeXLive 2018. I included symbols from the current version of FontAwesome, according to pdffonts, the font is properly embedded, but Lulu still won't print those characters for some reason.


text:
Q: Using MovingMap to calculate percentage changes Bug introduced in 10.0 and fixed in 10.1

MovingMap (new in version 10) applies a function to discrete data over a moving window. This is very convenient for calculating the percentage change of a series.
But the error returned by the following code bothers me:
series = Range[5];
MovingMap[#[[2]]/#[[1]] - 1 &, series, {2}]

(* Power::infy: Infinite expression 1/0. encountered. >>\*)
(* {1, 1/2, 1/3, 1/4} *)

However, this code returns the result with no error:
MovingMap[f, series, {2}] /. f -> Function[#[[2]]/#[[1]] - 1]

(* {1, 1/2, 1/3, 1/4} *)

What causes this problem?

A: Update
In version 10.1 the overhang problem described below has been removed. (In the default form; with Method -> "Legacy" the behavior below returns.)  I am therefore tagging this as a bug.
Beware that MovingMap syntax has incompatibly changed in 10.1 as well.

This appears to be a bug in MovingMap.  The function is applied beyond the left edge of the list and then the result is discarded:
echo[x_] := (Print[x]; x)

MovingMap[echo, Range@5, {2}]

{0,1}
{1,2}
{2,3}
{3,4}
{4,5}
{{1, 2}, {2, 3}, {3, 4}, {4, 5}}

I can see no reason to use the padding element 0 here.  Interestingly when one specifies a different padding element that first result is not discarded:
MovingMap[Identity, Range@5, {2}, foo]

{{foo, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}}

The documentation for the padding parameter is:

So supposedly the default is no padding, but that is not true; the default padding is 0, and then the result is discarded.  Again:
MovingMap[echo, Range@5, {5}]

{0,0,0,0,1}
{0,0,0,1,2}
{0,0,1,2,3}
{0,1,2,3,4}
{1,2,3,4,5}
{{1, 2, 3, 4, 5}}

There is no reason for the function (echo) to be applied the first four times, and in fact this directly contradicts the documentation which states that "no padding" is the default.
Also weird is this case:
MovingMap[echo, Range@5, {5, 2}]

{0,0,0,0,1}
{0,0,0,1,3}
{0,0,1,3,5}
MovingMap[echo, {1, 2, 3, 4, 5}, {5, 2}]

So even though it appears that the parameters are invalid and the entire MovingMap expression is returned unevaluated, the echo function is still applied to three times.

A: IMHO this is a Bug. You can prevent the error message in V10 using Quiet:
series = Range[5];
MovingMap[Quiet[#[[2]]/#[[1]] - 1 &], series, {2}]

You can also use Internal`PartitionMap, without Quiet:
Developer`PartitionMap[#[[2]]/#[[1]]-1&, Range@5, 2, 1]

{1,1/2,1/3,1/4}

Post about PartitionMap
UPDATE
Fixed in 10.1


text:
Q: How can view the changes of a constantly updating variable that is inserted into a text box So I want to create a textbox that allows me to show messages that are constantly being updated. However, with my below code it only shows the first loaded message in the variable msg. How can I fix this?
import tkinter
import threading
import time

global msg

def gui():
    root = tkinter.Tk()

    box = tkinter.Text(width=90, height=30, font=("Lucida Console", 10))
    box.pack(pady=20)
    box.insert(tkinter.END, msg) #this updated msg should be shown

    box.configure(state=tkinter.DISABLED)
    root.mainloop()

def loop():
    global msg
    for x in range(100):
        msg = str(x)
        time.sleep(1)

if __name__ == '__main__':
    p1 = threading.Thread(target=gui)
    p2 = threading.Thread(target=loop)

    p1.start()
    p2.start()

A: *

*You couldn't change the text when the config of the Text widget is disabled.

*In your code, insert(tkinter.END, msg) would only insert the text only once.You could use .after to insert the text each time.(If you didn't want to use insert method in the .after , you could bind a StringVar for your box.)

To fix those issues, try this:
import tkinter
import threading
import time
global msg

def gui():
    def insert():
        global msg
        box.configure(state=tkinter.NORMAL)
        box.insert(tkinter.END, msg)
        box.configure(state=tkinter.DISABLED)
        root.after(1000, insert)

    root = tkinter.Tk()

    box = tkinter.Text(width=90, height=30, font=("Lucida Console", 10))
    box.pack(pady=20)
    insert()

    root.mainloop()

def loop():
    global msg
    for x in range(100):
        msg = str(x)
        time.sleep(1)

if __name__ == '__main__':
    p1 = threading.Thread(target=gui)
    p2 = threading.Thread(target=loop)

    p1.start()
    p2.start()

I don't recommend you use a global variable msg though.You may could consider to use a thread queue.


text:
Q: how to do a relative import from subpackage to top folder workdirectory with python 3.75? Project_folder
│
├───Tests
│   │   __init__.py
│   │
│   │
│   ├───features
│   │       smallcircle.feature
│   │
│   ├───steps_tests
│   │   │   test_smallcircle.py
│   │   │   __init__.py
│   __init__.py
│   a.py

I'm triying to make a relative import from test_smallcircle.py to a.py as shown bellow
import sys
import os
sys.path.append(os.path.dirname("C:\\Users\\Manuel\\Desktop\\solution\\a.py"))
from a import smallest_circle # JUST HERE
from pytest_bdd import (
    given,
    scenario,
    then,
    when,
)
import pytest_bdd
from functools import partial

but it shows the next error
Unable to import 'a'

A: If you want a relative import, you need to go up a level:
from ..a import smallest_circle

A: I found the error, it was at the absulte path C:\\Users\\Manuel\\Desktop\\solution\\a.py
that I append to the sys.path variable, the absolute path should be to the directory, not to the target file, so the solution was replacing it for C:\\Users\\Manuel\\Desktop\\solution


text:
Q: Send an SMS via Skype with PHP Does anyone have any experience using PHP to send an sms via skype
I want the user off the website to use one the forms and give them a choice if they want to send an SMS to do a request. First it will have to check for the availabillity of Skype on the clients computer, if so it should send an SMS. I already have the users mobile number in the database when he logs to the website.
Maybe, I have to use a combination off Javascript and PHP?
I see that Skype has a call.php script, but I can't seem to understand how it is supposed to be used. And also how to ajust it to send sms messages.
If anyone can give me some pointers, that would be helpfull.
If Skype is to closed off then does anyone know a good sms service to implement on the website that would allow me to achieve the same goal?

A: If you're running PHP on Windows, you can use the COM wrapper for PHP to interface with Skype4COM. I haven't tested it, but following the examples from the Skype4COM documentation, this should work:
$skype = new COM("Skype4COM.Skype");
$skype->sendSms("+1234567890", "SMS text goes here");

However, this would use the instance of Skype running on your server. It is certainly impossible to interface with the instance of Skype running on your client's machine using client-side JavaScript. Some basic interfacing can be done with MSIE and VBScript, but I think that this way the functionality would be very limited as well, because it would be very insecure if it wasn't limited.

A: no, php is a server side scripting language, you cannot access your clients' pcs with it. and i doubt it is possible to call skype from javascript …

A: TRUE..However, this would use the instance of Skype running on your server.
NOT TRUE..It is certainly impossible to interface with the instance of Skype running on your client's machine using client-side JavaScript
^ The client side javascript CAN make server calls via javascript ajax, hell you can even make server side calls WITHOUT using javascript by embedding the call in an image tag!
ie.  img src="myskype_server.com/announcestatus.php?session=23eedwrwe23323&status=viewing mortgage documents"
announcestatus.php
// connect to server actually running skype
//do a series of security checks
// connect to the actual windows pc running skype (It's host name can be fixed by using a service like www.dyndns.com)
//
If anybody is particularly interested, I can package up the wobbly code I used to implement this and post it.


text:
Q: How will I make a pendrive write protected? I just want to make my pendrive write protected just to make sure, when I insert it public PCs like in cyber cafes in order to just read the files, it doesn't get virus affected. How can I do this?

A: Unless your USB drive has a physical switch, this is not possible. You cannot enforce something like this using a software solution, especially when you do not control the system.

A: If your stick uses the NTFS filesystem, you can do the following. If not, consider copying the files off of the drive, then format as NTFS.
Do the following:

*

*Open your explorer and select the driveletter of your USB drive.\

*Right click and select Properties

*Open the tab Security

*Click the Change button, and answer yes to the UAC prompt if applicable.

*Look if there's an Everyone user. It is likely not there. If it is, skip step 8.

*Click on Add...

*Type in Everyone and click Ok

*Select the Everyone user

*Set a checkmark in the column deny for Write.

From this moment on, no one can change the drive anymore. If you want to make changes, Repeat the above steps and remove the checkbox for write in the deny column.
Although the screenshot is dutch, it is showing the endresult.

A: You could always try locking the drive using diskpart.
Open CMD as admin and type diskpart.
When diskpart loads - type list disk
This will give you a list of drives in your machine.
Select your USB device using the select disk 1 command (where 1 is the number of your USB)
Use attributes disk set readonly to set the drive as read only.


text:
Q: What will Google App Inventor mean for mobile software development? Google Labs will be rolling out something called Google App Inventor (for Android). CNet says:

"To use App Inventor, you do not need
  to be a developer. App Inventor
  requires NO programming knowledge.
  This is because instead of writing
  code, you visually design the way the
  app looks and use blocks to specify
  the app's behavior," the Google
  project description states.

I sense a big, big development here. This is big. The Android platform is really gaining ground on a big range of devices: phones/pda's, netbooks, tablet pc's and embedded systems.
The underlying Android SDK is a well-written framework, but only a reasonable java-programmer has the knowledge to use the components to build a proposed piece of software.
I spoke a lot of people about the android platform. A phone with Android is not a phone. It's a device with wireless and 3G internet capabilities, bluetooth capabilities, a camera, a speaker, a microphone, a touchscreen, a motion sensor and a GPS receiver. These components can be combined in endless ways, the sky is the limit.
Until now, you would need to hire a Java programmer to build that 'genius app' for you.
But now, everyone and his sister will be building them, publishing them, and improving them.
Don't you think this is going to be big?

A: No, I don't think that it is going to be big. Not really.
It's not going to be nearly as big as the hype, which will fade. There have been dozens and dozens of programs that have tried to make it possible for non-programmers to create applications. They have all dramatically under-delivered, and even though I respect the heck out of Google, there is no special reason to think that they have solved the intransigent problem of programming being hard.
Also, it is important to remember that Google LOVES to release products that are still immature and requiring significant polish. They also kill under-performing products without any sentimentality. This looks tyo me like a classic Google trial balloon app. Don't be surprised or heart-broken if it suddenly disappears with no fafare.

A: I take issue with the statement that developing a program will require "NO programming knowledge".  This is bordering on marchitecture.
So-called "programming knowledge" is more than just being able to remember syntax and string together text that can be compiled into something a machine can execute.  It requires problem solving skills, the ability to develop and analyze algorithms, wrangle with complexity, modularization, so on and so on.  These are essential skills of a programmer more so than the ability to recall syntax.
If anything this may make simple programming tasks more approachable to people that have problems understanding/remembering precise syntax, but it will hardly eliminate the need for programming skills. I can see it being useful in an educational environment where the goal is to lower the barrier to entry for understanding programming topics without syntactical nuances getting in the way.
Actually, I would be tempted to use this topic as an interview question and weed out any candidates who claim it allows you to develop a program without any programming knowledge or otherwise level the playing field between programmers and non-programmers.

A: I don't think this is going to be big but I do think that this will open the door for non-programmers to be introduced to programming and possibly increase the supply of programmers after non-programmers get a taste for software design. As other posters have mentioned this has been done before. What makes this different is the popularity of Android. My guess is that this will bring in 3 different types of people:

*

*Business men and women who have
an idea for an app and want to avoid
hiring a programmer,

*Non-developers that are interested
in learning how to program and use
this as an introduction to the
mindset, and

*Existing developers that just use
this as a means to develop apps
faster and easier.

I don't think this will change the way people program though. My guess is that this will only allow you to create basic apps and in order to get into the more complicated stuff you'll need to dive into the code. This will open the door to more "developers" though.

A: While I think the other answers have got it right that programming is a slowly learned skill that cannot be replaced overnight with a nifty interface, there are a couple of things that may yet make this pretty interesting:

*

*Built-in support for interfacing with popular services like twitter, etc..

*The ability for power-users to do crazy and interesting stuff by stringing together some formulas. Sometimes a power-user with a crude tool can be more in tune with solving real problems than a programmer who is trying to brainstorm an app that will sell. I'm thinking primarily of Excel here, where a business user can learn a powerful mini-language to solve their personal problems, often in ways that are either brilliant or horrifying.
Will it result in tons of crappy apps? Probably. But it will also put pressure on Java developers to up their game and produce better stuff - or get buried in the flood.

A: There's been exactly one really successful end-user "programming environment" since Basic that I can think of and it's not Visual Basic on Windows or Rexx on the Amiga or even Logo for kids. It's HyperCard.
HyperCard spawned a huge number of people doing stacks for their own needs and for others like I've never seen. There were even commercial programs (even games) written using it as an environment.
So how well does this emulate the things that made HyperCard a success?

*

*Well, HyperCard came with new Macs
and was reasonably cheap unbundled,
App Inventor is free so that's even
better.

*HC had a very simple paradigm
that was easy to understand, I've yet
to see what the programming
environment is like for App Inventor,
but it's hopefully not too bad.

*HC could be hooked to almost anything
via various extensions. App Inventor
is Java under the covers, I think we
can safely say that it is a full
powered language with connectivity to
everything under the sun.

The biggest problem with Google is that they lack the things Apple is best at, hand holding, packaging, removing layers that might intimidate newcomers, sizzle. You only have to watch (perhaps cringe) through one of Google's I/O conference keynotes and compare it to the slickly produced product rollouts that Apple has done for years to get a sense for how well they can sell things. Selling is not their forte, and that, more than anything else, can temper the adoption of App Inventor even if it's great.

A: I think that this could be problematic... I mean even seasoned java developers are creating apps that interfere with the main thing that the platform is there for ... the users phone.
App inventor might be useful for games, but do you really think that it can be used to create media player apps, security apps, etc?

A: General purpose visual programming tools have been attempted and subsequently failed, hard, since the 60s. Possibly even the '50s.
The only ones that have done "okay" - to my knowledge - are ladder logic tools and Labview. They are fairly limited in scope.
So Google App Inventor probably will mean the rise of a few nifty widgets, a slew of "meh" ones, and a long tail of failures. Much like other programs. But I don't think it'll Radically Change The World. I could, of course, be wrong. Google may have gotten with a disruptive idea and has a realistic visual programming model. They have the money and the brain trust to find or happen upon one.

A: This sounds like an advertisement or something. No, I think App Inventor is subset of what MIT's Scratch is and I think this will just be a vehicle to deliver millions of useless porn clips and wallpapers. I found Google's video to be laughable, of all the things, a woman makes a cat wallpaper app that purrs? I think it is very naive to think that this will "democratize programming" or whatever cliches people like Seth Goden are likely to bandy about.


text:
Q: for/if PHP omitindo elemento estou com um grande problema. Tenho um sistema em PHP/LARAVEL que emite relatório em PDF. O sistema ela está omitindo um elemento na hora de colocá-lo em um array.
Acredito que seja na hora de montar o loop e fazer as comparações de if estou deixando passar algo.
Tenho uma lista de pessoas e tenho que listar 9 pessoas por página, a 10 pessoa que deveria estra na próxima página não aparece ele pula essa pessoa e o fato se repete de 10 em 10 elementos. A solução pode ser simples mas não estou conseguindo pensar.
OBS: O retorno dos elementos na base de dados trás todas as pessoas.

$serv[$p][$j] = $servidor; Onde [$p] é a página e o [$j] o elemento na página

Espero que vocês possam me ajudar.
$i = 0;
$j = 0;
$p = 0;
$dep = '';
$pdep = '';

$aux = count($servidores);

foreach ($servidores as $value => $servidor) {

    $servidor->ferias = $ferias[$value]->ferias;

    if($value == 0){
        $pdep = $servidor->cd_departamento;
        $dep = $servidor->cd_departamento;
        $serv[$p][$j] = $servidor;
        $j++;
    }else{
        if($dep == $servidor->cd_departamento){
            if ($j < 9) {
                $serv[$p][$j] = $servidor;
                $j++;
            } else {
                $p++;
                $j = 0;
                $serv[$p][$j] = $servidor;
            }
        }else{
            $dep = $servidor->cd_departamento;
            $p++;
            $j = 0;
            $serv[$p][$j] = $servidor;
        }
    }

}

A: $pagina = 0;
$departament_do_servidor_anterior = null;
$servidores_paginados = [];
foreach ($servidores as $index => $servidor) {
    if ($index > 0 && $departament_do_servidor_anterior !== $servidor->cd_departamento) {
        $pagina++;
    }

    $servidores_paginados[$pagina][] = $servidor;
    $departament_do_servidor_anterior = $servidor->cd_departamento;

    if (count($servidores_paginados[$pagina]) === 9) {
        $pagina++;
    }
}

A: Douglas, eu atualizei o código que você postou com mais legibilidade para ficar fácil de identificar o erro.
$depByPage = '';

foreach ($servidores as $value => $servidor) {

    $servidor->ferias = $ferias[$value]->ferias;
    $dep = $servidor->cd_departamento;

    if($value === 0){
        $pdep = $dep;
        $depByPage = $dep;
    }

    /* Criar mais um array de elementos caso atinja o limite de servidores
     * por página ou se o departamento é diferente
     */
    if ($j >= 9 || $dep != $depByPage) {
        $j = 0;
        $p++;
        $depByPage = $dep;

        $serv[$p][$j] = $servidor;
        continue; //Vai diretamente para o inicio do loop
    }

    $serv[$p][$j] = $servidor;

    $j++;
}

Atualize o seu código e veja se o erro persiste.


text:
Q: How do I open a file attachment from Outlook with my winform application? I have written a winform app and have created a installation program using Inno Setup so that a custom file extension is associated with it.
The application is setup so that if the associated file type is double clicked then the application automatically opens and loads the file.  This works fine from if the file is double clicked from the desktop or file explorer.
However, we have noticed an issue when trying to open a file attachment from inside Outlook.  This error is being generated:
System.UnauthorizedAccessException

I have caught the error in my application and checked the file path that is supplied to the program. It doesn't exist in the file system (when I try to browse to it).
C:\User\MyUserName\AppData\Local\Microsoft\Windows\INetCache\Content.Outlook\MXIIIP00\MyFilename.CustomExtension

The section after ...\Microsoft\Windows\ doesn't exist (as far as I can see).
Has anyone else encountered this issue and know how to solve it?
UPDATE:
If I open a dos prompt - I can actually get to this location even though it is not shown in Windows Explorer.
UPDATE 2:
If I copy the path directly into Windows Explorer I can see the files here too.  However if I double click the file from here - my application still cannot load the file.
UPDATE 3:
The file saved by Outlook (and that my app is trying to open) appears to be empty.  Which would explain why my app can't process it.  Outlook appears to be doing something to the file when I send it.  It starts off as 72KB when I send it, but when I receive it - it is 252B.

A: It´s a problem of AUTHORIZATION.
You may try to run your app AND the Outlook in ADMIN MODE to get success - at least it´s mandatory, run both at the same authorization level.
Or even try to open your attachment in the Windows TEMP folder... but I guess you won´t get it from within Outlook if you don´t, programatically, extract the attachment to that folder and open it.

A: Okay so as it turns out there was two issues here.
The first was to do with how I was testing this feature.  To simulate the file being sent to a customer I used Outlook to send an email with my file as an attachment to myself.  For some (as yet unknown) reason, Outlook takes it upon itself to send me an empty file.  When I logged into an external email client and sent the file to Outlook the file remained intact.
However, my application still wouldn't open it.
The second issue was the temporary file being created with the Read Only attribute being set.  Once I set up my application to turn this off, it all worked fine.


text:
Q: IOS: Drag and Drop interaction without hiding the keyboard Setting:
I do have a class MyView derived from UIView which is properly setup for drag (and drop, but drop does not matter for this question). This means that a UIDragInteraction has been registered view view.addInteraction and the drag and drop action is working fine (the specific drag items and other implementation does not matter).
Let's say the keyboard is shown on screen (for example because a UITextField is selected and has become first responder), initiating a drag interaction by touching and dragging the object always dismisses the keyboard. The dismissal takes place after the drag item has been lifted and is moved by the user.
My quesiton: How can I avoid dismissing the keyboard when a drag interaction takes place?
Further investigations:
I assumed that the drag interaction somehow calls resignFirstResponder() for the UITextField, but even disabling the resignFirstResponder by overriding it in a subclass and let the substitute do nothing does not prevent the keyboard from being dismissed.

A: For enable splitView and multitask to custom view(UKWebView) drag and drop interaction
Full Source and Document available
http://blogs.specialapps.in/SplitView_MultiTasking
.

A: Say, in your scenario, you have a UITextField inside a UIScrollView that is selected. You can access the keyboardDismissMode from the corresponding UIScrollView and set its value to .none.
Example
Inside your UIViewController, declare a reference to the UIScrollView and connect it through your storyboard.
@IBOutlet weak var scrollView: UIScrollView!

Then, inside the viewDidLoad() method, set the property as declared above.
override func viewDidLoad() {

    super.viewDidLoad()

    // Configure UIScrollView
    self.scrollView.keyboardDismissMode = .none

}


text:
Q: Do I need to nest observation windows in each trial as a random effect? The study is as follows:

*

*Participants are observed at three ages.

*Observations at each age involves 10 trials (i.e., stimuli they are presented with while their eye gaze is measured).

*Each trial is split into 3 time windows.
Would it be correct to use a nested random effects structure, with windows nested within trials, trials nested within age, and age nested within participants?

A: Very often the correlation structure in the data is simpler than the one the design of the study suggests. Hence, I would suggest that you start with a simple random intercept term per participant, include then a random slope for age, and then a nested random effect for trials. At each step, you can use likelihood ratio tests to see if the additional random effects improve the model.


text:
Q: Why does my Image stretch when I crop it? I am using the following code snippet in order to crop a image?
   function crop($width,$height) {
       $new_image = imagecreatetruecolor($width, $height);
       imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $this->getWidth(), $this->getHeight(), $width, $height );
       $this->image = $new_image;
   }

Here, $this->image is the original image $this->getWidth() and $this->getHeight() holds the original dimensions of the picture, where as $width and $height, is the crop area.
But for some reason, the crop image is resized(we can almost say it is resized).
How to fix this?

A: Well, the problem is giving the source dimensions. Giving the dimensions of entire image will re size instead of cropping.
This should solve the problem
   function crop($width,$height) {
       $new_image = imagecreatetruecolor($width, $height);
       imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $width, $height );
       $this->image = $new_image;
   }

A: Yes i have a solution for uploaded image crop and resize without starch
please Following this steps:
step 1: you make a new index.php file.
<html>
    <body>
        <form action="image_upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="submit"/>
</form>
    </body>
</html>

step 2 : then make a new file resize.php
<?php

        Class resize
        {
            // *** Class variables
            private $image;
            private $width;
            private $height;
            private $imageResized;

            function __construct($fileName)
            {

                // *** Open up the file
               $this->image = $this->openImage($fileName);

                // *** Get width and height
                $this->width  = imagesx($this->image);
                $this->height = imagesy($this->image);
            }

            ## --------------------------------------------------------
            public static function openImage($file)
            {

                // *** Get extension
                $extension = strtolower(strrchr($file, '.'));

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        $img = @imagecreatefromjpeg($file);
                        break;
                    case '.gif':
                        $img = @imagecreatefromgif($file);
                        break;
                    case '.png':
                        $img = @imagecreatefrompng($file);
                        break;
                    default:
                        $img = false;
                        break;
                }

                return $img;
            }

            ## --------------------------------------------------------

            public function resizeImage($newWidth, $newHeight, $option="auto")
            {
                // *** Get optimal width and height - based on $option
                $optionArray =  $this->getDimensions($newWidth, $newHeight, $option);

                $optimalWidth  = $optionArray['optimalWidth'];
                $optimalHeight = $optionArray['optimalHeight'];

                // *** Resample - create image canvas of x, y size
                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);

                // *** if option is 'crop', then crop too
                if ($option == 'crop') {
                    $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                }
            }

            ## --------------------------------------------------------

            public function getDimensions($newWidth, $newHeight, $option)
            {
               switch ($option)
                {
                    case 'exact':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                        break;
                    case 'portrait':
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                        break;
                    case 'landscape':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                        break;
                    case 'auto':
                        $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                    case 'crop':
                        $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                }
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            public static function getSizeByFixedHeight($newHeight)
            {
                $ratio = $this->width / $this->height;
                $newWidth = $newHeight * $ratio;
                return $newWidth;
            }

            public static function getSizeByFixedWidth($newWidth)
            {
                $ratio = $this->height / $this->width;
                $newHeight = $newWidth * $ratio;
                return $newHeight;
            }

            public static function getSizeByAuto($newWidth, $newHeight)
            {
                if ($this->height < $this->width)
                // *** Image to be resized is wider (landscape)
                {
                    $optimalWidth = $newWidth;
                    $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                }
                elseif ($this->height > $this->width)
                // *** Image to be resized is taller (portrait)
                {
                    $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                    $optimalHeight= $newHeight;
                }
                else
                // *** Image to be resizerd is a square
                {
                    if ($newHeight < $newWidth) {
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                    } else if ($newHeight > $newWidth) {
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                    } else {
                        // *** Sqaure being resized to a square
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                    }
                }

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            public function getOptimalCrop($newWidth, $newHeight)
            {

                $heightRatio = $this->height / $newHeight;
                $widthRatio  = $this->width /  $newWidth;

                if ($heightRatio < $widthRatio) {
                    $optimalRatio = $heightRatio;
                } else {
                    $optimalRatio = $widthRatio;
                }

                $optimalHeight = $this->height / $optimalRatio;
                $optimalWidth  = $this->width  / $optimalRatio;

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            public function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
            {
                // *** Find center - this will be used for the crop
                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

                $crop = $this->imageResized;
                //imagedestroy($this->imageResized);

                // *** Now crop from center to exact requested size
                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
            }

            ## --------------------------------------------------------

            public function saveImage($savePath, $imageQuality="100")
            {
                // *** Get extension
                $extension = strrchr($savePath, '.');
                $extension = strtolower($extension);

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        if (imagetypes() & IMG_JPG) {
                            imagejpeg($this->imageResized, $savePath, $imageQuality);
                        }
                        break;

                    case '.gif':
                        if (imagetypes() & IMG_GIF) {
                            imagegif($this->imageResized, $savePath);
                        }
                        break;

                    case '.png':
                        // *** Scale quality from 0-100 to 0-9
                        $scaleQuality = round(($imageQuality/100) * 9);

                        // *** Invert quality setting as 0 is best, not 9
                        $invertScaleQuality = 9 - $scaleQuality;

                        if (imagetypes() & IMG_PNG) {
                             imagepng($this->imageResized, $savePath, $invertScaleQuality);
                        }
                        break;

                    // ... etc

                    default:
                        // *** No extension - No save.
                        break;
                }

                imagedestroy($this->imageResized);
            }

            ## --------------------------------------------------------

        }
?>

step 3 : you also make a new two folder 1) image and 2) image_thumb
step 4 : then after make a new file image_upload.php
<?php
include('resize.php');
if(isset($_FILES['image'])){

    //set a folder move to orignal images
    $destinationPath = "image/";

    //set a folder move to crop and resizeable images
    $destinationThumbPath = "image_thumb/";

    //uploaded files extension
    $extension = strtolower(strrchr($_FILES['image']['name'], '.'));

    //set a new custom name of uploaded file
    $file_name = "image_".rand('1111','9999').$extension;

    //move orignal image in Destination Path
    move_uploaded_file($_FILES['image']['tmp_name'],"image/".$file_name);

    //set a new thumbnail width
    $newWidth = 96;
    //set a new thumbnail height
    $newHeight = 96;
    //profile image resize
    $resizeObj = new resize($destinationPath . $file_name);
    // *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
    $resizeObj->resizeImage($newWidth, $newHeight, 'crop');

    //crop and resize image save in destination path
    $resizeObj->saveImage($destinationThumbPath . $file_name, 100);

}
?>

A: This is what imagecopyresampled does: it rescales the image and does not crop it. Try imagecopy instead.


text:
Q: ASP .NET MVC 5 Html.ValidationMessageFor not working Following is .cshtml code:
using (Ajax.BeginForm("UploadEdit", "Widget", new { Type = "SampleSurvey" }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "SampleSurvey-widget", LoadingElementId = "report-loader", OnBegin = "$('#report-loader').show();", OnSuccess = "$('#report-loader').hide();" }, new { enctype = "multipart/form-data", id = "SampleSurvey" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.Type)
    @Html.HiddenFor(model => model.IsDealer)
    @Html.HiddenFor(model => model.Filter)

        <fieldset class="">

                    @Html.LabelFor(Model => Model.FirstName, new { @class = "field__label" })

                        @Html.EditorFor(model => model.FirstName)
                        @Html.ValidationMessageFor(model => model.FirstName)

                    @Html.LabelFor(model => model.LastName, new { @class = "field__label" })

                        @Html.EditorFor(model => model.LastName)
                        @Html.ValidationMessageFor(model => model.LastName)

                    @Html.LabelFor(model => model.Email, new { @class = "field__label" })

                        @Html.EditorFor(model => model.Email)
                        @Html.ValidationMessageFor(model => model.Email)

        </fieldset>

            <button id="btnSubmit" class="btn icon icon-location-arrow" type="submit" onclick="$('#report-loader').show();">Send invitation</button>

}

And following is my model:
public class SampleSurvey : WidgetBase
{
    [Required]
    [StringLength(100, ErrorMessage = "Maximum 100 characters are allowed in field")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "Maximum 100 characters are allowed in field")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress, ErrorMessage = "Invalid field.")]
    [Display(Name = "Email Address")]
    public string Email { get; set; }

}

But still validation is not working upon clicking the submit button, help will highly be appreciated.


text:
Q: How to save the size of the window and restore it in the next session in winforms in Visual studios c++ 2008? I want to save the size of the window and restore it in winforms using c++, However I couldnt find any information about that. I dont know what events to use to save the size.
Any help would be greatly appreciated!
Thanks

A: You have various choices here:  put the position and size of the window into a registry key, updated every time the window size or position is moved, or put the position and size of the window into your own settings file (which you create or open at startup, somewhere in the user settings directory), also updated whenever the window size or position is moved.  Read these values in when the form is loaded and move and size the window accordingly.
Personally I would never use managed C++.  It seems to me to be the worst of both worlds.  In C# and VB.NET, you'd have a settings file generated for the project, which is automagically deployed for you with your application.
Anyway, here's a good article on managing configuration files with C++/CLI.  It's a more complicated business than just writing the values out into your own little config file, however.


text:
Q: ActiveRecord Custom Field Method Lets imagine that I have a custom image upload for a particular record and I add two columns into the model.
thumbnail_url
thumbnail_path
Now lets imagine that I have a form with a :file field which is the uploaded file in multipart form. I would need to somehow have the model pickup the file within the given hash and then issue it over to a custom method which performs the upload and saves it as apart of the model.
Right now I'm doing this:
def initialize(options = nil)
  if options
    if options[:file]
      self.upload_thumbnail(options[:file])
      options.delete(:file)
    end
    super options
  else
    super
  end
end

def update_attributes(options = nil)
  if options
    if options[:file]
      self.upload_thumbnail(options[:file])
      options.delete(:file)
    end
    super options
  else
    super
  end
end

It works, but I am doing some unnecessary overriding here. Is there a simpler way of doing this? Something that would only require overriding perhaps one method?

A: You are looking for virtual attributes. Just define:
def file
  # Read from file or whatever
end

def file=(value)
  # Upload thumbnail and store file
end

and initialize, update_attributes and cousins will pick the methods for you.
That, or save the hassle and use paperclip as Kandada suggested.

A: Have you considered using using paperclip gem? It performs the functions you describe in your question.


text:
Q: PHP to iOS RegEx expression i found this cool PHP function to extract the URL name from a url string. Now i would like to recreate the same function in Objective-C code. I'm still trying but without success... Can someone help me recreate this function?
Here is the PHP code:
function __extractName($url)
{
  $domain = parse_url($url , PHP_URL_HOST);
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $list)) {
    return substr($list['domain'], 0,strpos($list['domain'], "."));
  }
  return false;
}

A: Why would you even bother with this?
NSURL *exampleURL = [NSURL URLWithString:@"<.....>"];
NSString *host = [exampleURL host];
if (host) NSLog(@"host is %@", host);

That will return the hostname. If you need to do further processing, e.g. return "google" for both "google.com" and "google.co.uk", then that is just some more simple string processing.


text:
Q: Invisible (transparent) font color with css on all major browsers Is it possible to make the font (font-color) transparent while using any color like black or white? Just have the font slowly disappear, like display:none. Thanks

A: You can use RGBA colors, where the last level is alpha (transparency), e.g.:
color:rgba(255,0,0,0.3);
Which is red at 30% opacity. RGBA values are supported by IE9+, Firefox 3+, Chrome, Safari, and in Opera 10+.
You also have HSLA, e.g.:
color: hsla(0,100%,50%,0.6);
Again, the last value, alpha, sets the transparency

A: You can use css property
opacity: 0;

and you will not be able to select the text,
or
color: transparent;

and you will have the chance to select the text.
If you want to make this slowly look at jQuery functions .fadeOut() http://api.jquery.com/fadeOut/ or .animate() http://api.jquery.com/animate/


text:
Q: Seed data in mySQL container after start up I have a requirement where I need to wait for a few commands before I seed the data for the database:
I have some Migration scripts that create the schema in the database (this command runs from my app container). After this executes, I want to seed data to the database.
As I read, the docker-entrypoint-initdb scripts is executed when the container is initialized. If I mount my seed.sql script to it, the data is seeded before the Migrate scripts. (The Migrate scripts actually drop all tables and create them from scratch). The seeded data is therefore lost.
How can I achieve this? (I cannot change the Migrate scripts)
Here's my docker-compose.yml file
version: '3'
services:
  app:
    build: .
    # mount the current directory (on the host) to /usr/src/app on the container, any changes in either would be reflected in both the host and the container
    volumes:
      - .:/usr/src/app
    # expose application on localhost:36081
    ports:
      - "36081:36081"
    # application restarts if stops for any reason - required for the container to restart when the application fails to start due to the database containers not being ready
    restart: always
    environment:
      MIGRATE: Y
      <some env variables here>
  config-dev:
    image: mysql/mysql-server:5.7
    environment:
      MYSQL_DATABASE: config_dev
      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    volumes:
      # to persist data
      - config-dev-volume:/var/lib/mysql
    restart: always
    # to connect locally from SequelPro
    ports:
      - "1200:3306"
  <other database containers>

My Dockerfile for app container has the following ENTRYPOINT
# start the application
ENTRYPOINT /usr/src/app/docker-entrypoint.sh

Here's the docker-entrypoint.sh file
#!/bin/bash

if [ "$MIGRATE" = "Y" ];
then
    <command to start migration scripts>
    echo "------------starting application--------------"
    <command to start application>
else
    echo "------------starting application--------------"
    <command to start application>
fi

Edit: Is there a way I can run a script in config-db container from the docker-entrypoint.sh file in app container?

A: This can be solved in two steps:

*

*You need to wait until your db container is started and is ready.

Wait until started can be handled by adding depends_on in docker-compose file:
version: '3'
services:
  app:
    build: .
    # mount the current directory (on the host) to /usr/src/app on the container, any changes in either would be reflected in both the host and the container
    depends_on:
      - config-dev
      - <other containers (if any)>
    volumes:
      - .:/usr/src/app
    # expose application on localhost:36081
    ports:
      - "36081:36081"
    # application restarts if stops for any reason - required for the container to restart when the application fails to start due to the database containers not being ready
    restart: always
    environment:
      MIGRATE: Y
      <some env variables here>
  config-dev:
    image: mysql/mysql-server:5.7
    environment:
      MYSQL_DATABASE: config_dev
      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    volumes:
      # to persist data
      - config-dev-volume:/var/lib/mysql
    restart: always
    # to connect locally from SequelPro
    ports:
      - "1200:3306"
  <other database containers>

Wait until db is ready is another case because sometimes it takes time for the db process to start listening on the tcp port.
Unfortunately, Docker does not provide a way to hook onto container state. There are many tools and scripts to have a workaround this.
You can go through this to implement the workaround.
https://docs.docker.com/compose/startup-order/
TL;DR
Download https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh inside the container and delete the ENTRYPOINT field (Not required for your use case) and use CMD field instead:
CMD ["./wait-for-it.sh", "<db_service_name_as_per_compose_file>:<port>", "--", "/usr/src/app/docker-entrypoint.sh"]

*Now, That this is complete. Next part is to execute your seed.sql script.
That is easy and can be executed by adding following line into your /usr/src/app/docker-entrypoint.sh script.
sqlcmd -S  -U  -P  -i inputquery_file_name -o outputfile_name
Place above command after migrate script in /usr/src/app/docker-entrypoint.sh


text:
Q: C# MySQL query result Visual Studio public ArrayList P2a(string sql)
{
    ArrayList result = new ArrayList();

    MySqlCommand cmd = new MySqlCommand();
    MySqlConnection mysqlconnection = new MySqlConnection(xxx);
    cmd.Connection = mysqlconnection;
    cmd.CommandText = sql;
    try
    {
        cmd.Connection.Open();
        MySqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            for (int count = 0; (count <= (reader.FieldCount - 1)); count++)
            {
                dict.Add(reader.GetName(count), reader[count]);
            }
                result.Add(dict);
        }

        return result;
    } catch {
        return result;
    } finally {
        cmd.Connection.Close();
    }
}

C# Visual Studio 2017 MySQL void return echo problem.
I want to make sure that I print out the result properly.
Example:
ArrayList query = P2a("select id,site,comment from sites");

MessageBox.Show(query[0]["site"].toString());

To use it this way.
Can you make the necessary corrections in the function?

A: I recommend as a start to change your catch block.

*

*You should be throwing the exception, ideally with more information.

*I also recommend that you have an optional list of MySqlParameters (defaults to null), while its not obvious here, since there are no parameters, more than likely you have SQL that is suspectible to SQL injection.  In most cases, if you have a where block and its not null, you have done something incorrectly.

*Your code does not cleanup the disposable objects, so using will take care of that.

*Use generics instead as the list item will now be a dictionary.
public List<Dictionary<String, object>> P2a(string sql, MySqlParameter[] parameters)
{
    List<Dictionary<String, object>> result = new List<Dictionary<String, object>>();

    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlConnection mysqlconnection = new MySqlConnection(xxx))
        {
            cmd.Connection = mysqlconnection;
            cmd.CommandText = sql;

            if (parameters != null)
            {
                foreach (MySqlParameter p in parameters)
                {
                    cmd.Parameters.Add(p);
                }
            }

            try
            {
                cmd.Connection.Open();
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Dictionary<string, object> dict = new Dictionary<string, object>();
                        for (int count = 0; (count <= (reader.FieldCount - 1)); count++)
                        {
                            dict.Add(reader.GetName(count), reader[count]);
                        }
                        result.Add(dict);
                    }
                }

                return result;
            }
            catch (ApplicationException ex)
            {
                throw new ApplicationException("Error Executing " + sql, ex);
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
    }
}

A: I solved the problem myself
I wrote a new function
  public DataTable query(string sql) {

            DataTable table = new DataTable();
            MySqlConnection connection = null;
            MySqlDataReader reader = null;

            try {
                connection = new MySqlConnection(xxx);
                connection.Open();
                MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
                dataAdapter.SelectCommand = new MySqlCommand(sql, connection);
                dataAdapter.Fill(table);

                return table;
            } catch {
                return table;
            } finally {

                if (reader != null)
                    reader.Close();
                if (connection != null)
                    connection.Close();
            }}

use off
DataTable list = query("select * from tablename");

MessageBox.Show(list.Rows["rowsname"]["cellname"].ToString());