问:
Jquery datatables - How count numbers of rows?
I am using to Jquery datables to create a table with row details . Everything working fine Only the number of entries

The current logic is counting the parents row + child rows. I want to count only parents rows which are 4. My result should be Showing 1 to 10 of 4 entries.

In my Json file, I have recordsTotal: 16 which is the total rows parents + child. When I change to 4 which is number of parents rows the table will show me only first record (Ticket id 1 + its 3 child rows ) as it's counted as 4 entries.

Any suggestions please how can I update ? Thank you.

$(document).ready(function() {

function format ( d ) {

d.Items.sort(function compare(a,b) {
  if (a.Line_No  b.Line_No)
    return 1;
  return 0;
});

   var x = '

Line No	Line Level Issue	Created Date	Created By

' ;

$.each(d.Items, function( index, value ) {
  x += '
' + d.Items[index].Line_No + '	' + d.Items[index].Line_Level_Issue + '	' + d.Items[index].Created_Date + '	' + d.Items[index].Created_By + '
';
});

        x +='

';
        return x;
}

    var dt = $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "deferRender": true,
        "lengthChange": true,
        "pageLength": 10,
        "language": { "emptyTable": "No matching records found",
        "info": "Showing _START_ to _END_ of _TOTAL_ entries",
        "zeroRecords": "No matching records found" },
        "ajax": "https://api.myjson.com/bins/vwjfc",
        "columns": [
            {
                "class":          "details-control",
                "data":           "Ticket_id"
                ,render : function(data, type, row) {
              return '     ' + data;
          }
            },
            { "data": "Order_Level_Issue" },
            { "data": "Geo" },
            { "data": "Region" },
            { "data": "Territory" },
            { "data": "Market" },
            { "data": "Country" },
            { "data": "SoldTo_Number" },
            { "data": "SoldTo_Name" },
            { "data": "Order_Numer" }

        ],
        "order": [[0, 'asc'],[1, 'asc']]
    } );

    var detailRows = [];

    $('#example tbody').on( 'click', 'tr td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = dt.row( tr );
        var idx = $.inArray( tr.attr('id'), detailRows );

        if ( row.child.isShown() ) {
            tr.removeClass( 'details' );
            row.child.hide();

            detailRows.splice( idx, 1 );
        }
        else {
            tr.addClass( 'details' );
            row.child( format( row.data() ) ).show();

            if ( idx === -1 ) {
                detailRows.push( tr.attr('id') );
            }
        }
    } );

    dt.on( 'draw', function () {
        $.each( detailRows, function ( i, id ) {
            $('#'+id+' td.details-control').trigger( 'click' );
        } );
    } );

} );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td.details-control {
    background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center left;
    cursor: pointer;
}
tr.details td.details-control {
    background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center left;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>

                TicketT id
                Order Level Issue
                Geo
                Region
                Territory
                Market
                Country
                SoldTo Number
                SoldTo Name
                Order Numer

                Ticket id
                Order Level Issue
                Geo
                Region
                Territory
                Market
                Country
                SoldTo Number
                SoldTo Name
                Order Numer

```

答:
I assume the problem was not dataTables at all but your ajax call, since you are using serverSide your server side is the one who sends the data the table will display including the total of records so in your ajax response you have:

{draw: 1, recordsTotal: 16, recordsFiltered: 16, data: Array(4)}

So all you have to do is work in your server side script in order the reflect the expected output.

Hope it helps

Body:
I am using to Jquery datables to create a table with row details . Everything working fine Only the number of entries

The current logic is counting the parents row + child rows. I want to count only parents rows which are 4. My result should be Showing 1 to 10 of 4 entries.

In my Json file, I have recordsTotal: 16 which is the total rows parents + child. When I change to 4 which is number of parents rows the table will show me only first record (Ticket id 1 + its 3 child rows ) as it's counted as 4 entries.

Any suggestions please how can I update ? Thank you.

$(document).ready(function() {

function format ( d ) {

d.Items.sort(function compare(a,b) {
  if (a.Line_No  b.Line_No)
    return 1;
  return 0;
});

   var x = '

Line No	Line Level Issue	Created Date	Created By

' ;

$.each(d.Items, function( index, value ) {
  x += '
' + d.Items[index].Line_No + '	' + d.Items[index].Line_Level_Issue + '	' + d.Items[index].Created_Date + '	' + d.Items[index].Created_By + '
';
});

        x +='

';
        return x;
}

    var dt = $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "deferRender": true,
        "lengthChange": true,
        "pageLength": 10,
        "language": { "emptyTable": "No matching records found",
        "info": "Showing _START_ to _END_ of _TOTAL_ entries",
        "zeroRecords": "No matching records found" },
        "ajax": "https://api.myjson.com/bins/vwjfc",
        "columns": [
            {
                "class":          "details-control",
                "data":           "Ticket_id"
                ,render : function(data, type, row) {
              return '     ' + data;
          }
            },
            { "data": "Order_Level_Issue" },
            { "data": "Geo" },
            { "data": "Region" },
            { "data": "Territory" },
            { "data": "Market" },
            { "data": "Country" },
            { "data": "SoldTo_Number" },
            { "data": "SoldTo_Name" },
            { "data": "Order_Numer" }

        ],
        "order": [[0, 'asc'],[1, 'asc']]
    } );

    var detailRows = [];

    $('#example tbody').on( 'click', 'tr td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = dt.row( tr );
        var idx = $.inArray( tr.attr('id'), detailRows );

        if ( row.child.isShown() ) {
            tr.removeClass( 'details' );
            row.child.hide();

            detailRows.splice( idx, 1 );
        }
        else {
            tr.addClass( 'details' );
            row.child( format( row.data() ) ).show();

            if ( idx === -1 ) {
                detailRows.push( tr.attr('id') );
            }
        }
    } );

    dt.on( 'draw', function () {
        $.each( detailRows, function ( i, id ) {
            $('#'+id+' td.details-control').trigger( 'click' );
        } );
    } );

} );

td.details-control {
    background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center left;
    cursor: pointer;
}
tr.details td.details-control {
    background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center left;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>

                TicketT id
                Order Level Issue
                Geo
                Region
                Territory
                Market
                Country
                SoldTo Number
                SoldTo Name
                Order Numer

                Ticket id
                Order Level Issue
                Geo
                Region
                Territory
                Market
                Country
                SoldTo Number
                SoldTo Name
                Order Numer


来源: stackexchange

问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答:
The opposite of A or B or C is not A and not B and not C, so use:

```<code>if(c != ' ' && c != '\n' && c != '\t')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}

Body:
The opposite of A or B or C is not A and not B and not C, so use:

if(c != ' ' && c != '\n' && c != '\t')


问:
JavaFX: why text is blurred?
Im starting with JavaFX, but immediately noticed that labels are blurred
(Do you see these pink edging around letters?)

I tried changing fonts, size, weight, but same...

It's offending to the eye, looks bulky, is there any way to make it appear without blurring effect?

I'm using OpenFx 13, tried with previous versions of JavaFx.

scene.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.StackPane?>

<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.openjfx.FXMLController">
   <children>
      <Label fx:id="label" text="Label" />
   </children>
</StackPane>
</code>```

FXMLController

```<code>package org.openjfx;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;

public class FXMLController {

    @FXML
    private Label label;

    public void initialize() {
        String javaVersion = System.getProperty("java.version");
        String javafxVersion = System.getProperty("javafx.version");
        label.setFont(Font.font("Menlo", FontWeight.BOLD, 20));
        label.setText("Hello, JavaFX " + javafxVersion + "\nRunning on Java " + javaVersion + ".");
    }
}
</code>```

MainApp

```<code>package org.openjfx;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

        stage.setTitle("JavaFX and Gradle");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

答:
Try using the LCD anti-aliasing on the MainApp :

```<code>public class MainApp extends Application {
    System.setProperty("prism.lcdtext", "false");
    ... The rest of your code ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: JavaFX: why text is blurred?

Body:
Im starting with JavaFX, but immediately noticed that labels are blurred
(Do you see these pink edging around letters?)

I tried changing fonts, size, weight, but same...

It's offending to the eye, looks bulky, is there any way to make it appear without blurring effect?

I'm using OpenFx 13, tried with previous versions of JavaFx.

scene.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.StackPane?>

<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.openjfx.FXMLController">
   <children>

   </children>
</StackPane>

FXMLController

package org.openjfx;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;

public class FXMLController {

    @FXML
    private Label label;

    public void initialize() {
        String javaVersion = System.getProperty("java.version");
        String javafxVersion = System.getProperty("javafx.version");
        label.setFont(Font.font("Menlo", FontWeight.BOLD, 20));
        label.setText("Hello, JavaFX " + javafxVersion + "\nRunning on Java " + javaVersion + ".");
    }
}

MainApp

package org.openjfx;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

        stage.setTitle("JavaFX and Gradle");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Body:
Try using the LCD anti-aliasing on the MainApp :

public class MainApp extends Application {
    System.setProperty("prism.lcdtext", "false");
    ... The rest of your code ...
}


问:
Identical bases conflict in multiple empty member optimization
I want to use an empty member optimization with a class having two members of user-defined types. As far as I know, the only way to achieve this is two make them my class' parents.

template<class Callback1, class Callback2>
struct S: Callback1, Callback2
{
    S(Callback1 c1, Callback2 c2): Callback1(c1), Callback2(c2) {}
    void Method()
    {
        Callback1::operator()();
        Callback2::operator()();
    }
    int field;
};
struct Functor {};
struct Functor2 {};
static_assert(sizeof(S<Functor, Functor2>) == sizeof(int));
```

The problem of this solution is that I cannot instantiate something like S<Functor, Functor>. When these two arguments are of the same type, I get a compiler error about two identical parents.
What is the best way to work around this problem?

Edit: There must always be two instances of callbacks even if they are of the same type. Any of these callbacks may be empty or not empty (stateful), but the cases when any of them or both are empty should be optimized.

答:
The straight forward solution for getting around the problem is to specialize.

```<code>template<class Functor>
struct S<Functor, Functor> : Functor {
  int field;
};
</code>```

If that causes too much repetition, you can reuse the code for the two functor version by introducing a special "null functor".

```<code>struct NullFunctor { /* Whatever implementation makes sense in your domain */ };

template<class Functor>
struct S<Functor, Functor> : S<Functor, NullFunctor> {};
</code>```

Alternatively, if your goal is to allow client code to use S with either a single functor or two different ones, you can specialize on a template parameter pack.

```<code>template<class ...Functors>
struct S;

template<class Functor>
struct S<Functor> : Functor {
};

template<class Functor1, class Functor2>
struct S<Functor1, Functor2> : Functor1, Functor2 {
};

template<class Functor>
struct S<Functor, Functor>; // Same functor used twice.
</code>```

Body:
I want to use an empty member optimization with a class having two members of user-defined types. As far as I know, the only way to achieve this is two make them my class' parents.

template<class Callback1, class Callback2>
struct S: Callback1, Callback2
{
    S(Callback1 c1, Callback2 c2): Callback1(c1), Callback2(c2) {}
    void Method()
    {
        Callback1::operator()();
        Callback2::operator()();
    }
    int field;
};
struct Functor {};
struct Functor2 {};
static_assert(sizeof(S<Functor, Functor2>) == sizeof(int));

The problem of this solution is that I cannot instantiate something like S<Functor, Functor>. When these two arguments are of the same type, I get a compiler error about two identical parents.
What is the best way to work around this problem?

Edit: There must always be two instances of callbacks even if they are of the same type. Any of these callbacks may be empty or not empty (stateful), but the cases when any of them or both are empty should be optimized.

Body:
The straight forward solution for getting around the problem is to specialize.

template<class Functor>
struct S<Functor, Functor> : Functor {
  int field;
};

If that causes too much repetition, you can reuse the code for the two functor version by introducing a special "null functor".

struct NullFunctor { /* Whatever implementation makes sense in your domain */ };

template<class Functor>
struct S<Functor, Functor> : S<Functor, NullFunctor> {};

Alternatively, if your goal is to allow client code to use S with either a single functor or two different ones, you can specialize on a template parameter pack.

template<class ...Functors>
struct S;

template<class Functor>
struct S<Functor> : Functor {
};

template<class Functor1, class Functor2>
struct S<Functor1, Functor2> : Functor1, Functor2 {
};

template<class Functor>
struct S<Functor, Functor>; // Same functor used twice.


问:
VBA Code that will subtract a number from the same row in multiple columns

I have a sheet like this, it goes down for a lot of rows, but this is just a snippet. I want the user to input a value, call it "x" and in the first row starting from March I want to subtract the "x" from the value in March. If march the value in March goes to 0, I want to move on to February and subtract whatever amount is remaining in X from Feb. This keeps going until we hit January.

Stop either if x is 0 or if there is no more left to subtract from march, feb and jan. The Jan through march values cant go below 0. I have experience coding in python but I am unfamiliar with VBA syntax. My issue is getting the recursion aspect.

```<code>Sub variance_sub()

Dim reduce As Double

reduce = InputBox("what is the Variance required?")

If reduce = 0 Then

    MsgBox ("No further action required")

ElseIf reduce > 0 Then

    subtraction_factor = Range("T7").Value

    Range("T7").Value = WorksheetFunction.Max(Range("T7").Value - reduce, 0)

    reduce = WorksheetFunction.Max(reduce - subtraction_factor, 0)

Else

    Range("T7").Value = Range("T7").Value + reduce

End If

End Sub
</code>```

答:
A simple loop is fine here - no recursion required:</p>

```<code>Sub variance_sub()

    Dim reduce As Double, c As Range, diff As Double

    reduce = InputBox("what is the Variance required?")

    Set c = ActiveSheet.Range("T7") 'march cell

    If reduce = 0 Then
        MsgBox "No further action required"
    ElseIf reduce > 0 Then
        Do
            If c.Value >= reduce Then
                c.Value = c.Value - reduce
                reduce = 0
            Else
                diff = reduce - c.Value
                c.Value = 0
                reduce = diff
            End If
            If c.Column > 1 Then Set c = c.Offset(0, -1) 'move left if we can
        Loop While reduce > 0 And c.Column >= 18
    Else
        c.Value = c.Value + reduce
    End If

End Sub
</code>```

Body:
I have a sheet like this, it goes down for a lot of rows, but this is just a snippet. I want the user to input a value, call it "x" and in the first row starting from March I want to subtract the "x" from the value in March. If march the value in March goes to 0, I want to move on to February and subtract whatever amount is remaining in X from Feb. This keeps going until we hit January.

Stop either if x is 0 or if there is no more left to subtract from march, feb and jan. The Jan through march values cant go below 0. I have experience coding in python but I am unfamiliar with VBA syntax. My issue is getting the recursion aspect.

Sub variance_sub()

Dim reduce As Double

reduce = InputBox("what is the Variance required?")

If reduce = 0 Then

    MsgBox ("No further action required")

ElseIf reduce > 0 Then

    subtraction_factor = Range("T7").Value

    Range("T7").Value = WorksheetFunction.Max(Range("T7").Value - reduce, 0)

    reduce = WorksheetFunction.Max(reduce - subtraction_factor, 0)

Else

    Range("T7").Value = Range("T7").Value + reduce

End If

End Sub

Body:
A simple loop is fine here - no recursion required:

Sub variance_sub()

    Dim reduce As Double, c As Range, diff As Double

    reduce = InputBox("what is the Variance required?")

    Set c = ActiveSheet.Range("T7") 'march cell

    If reduce = 0 Then
        MsgBox "No further action required"
    ElseIf reduce > 0 Then
        Do
            If c.Value >= reduce Then
                c.Value = c.Value - reduce
                reduce = 0
            Else
                diff = reduce - c.Value
                c.Value = 0
                reduce = diff
            End If
            If c.Column > 1 Then Set c = c.Offset(0, -1) 'move left if we can
        Loop While reduce > 0 And c.Column >= 18
    Else
        c.Value = c.Value + reduce
    End If

End Sub


问:
How to produce MASM format assembly from C code
I am writing a C program and I would like to compile to assembly, make modifications, and then compile it to an executable using the MASM assembler that's included with MSVS.

I know that MSVS itself allows for assembly output from C programs, but I have found that these outputs seem to add or omit code in such a way that they cannot be assembled by MASM without significant modification.

Is there a way to produce MASM syntax formatted assembly from some  C code that I can assemble with MASM with minimal to none modification?

答:
Think of it this way: when you use MASM you are using a completely different language, which, coincidently, had some overlapping in the assembly code.

You can ask the c compiler to show you the generated assembly, but the feature is not designed to be for cross planting the assembly code: it is just a courtesy to avoid you the hassle to spawn the disassembler, and manually extract the bits you need.

The c compiler is designed to turn your c code, plus the many features you might not even be aware of, into some machine code that does what you ask for. This means that the generated code may include much more stuff (e.g. Helpers) and can be linked to other libraries (e.g. The msvc runtime)  because this is what the msvc compiler has been designed to work.

On the other hand, if you use MASM, the audience is someone who requires to control everything. Thus you no longer benefit for the features and limits of the c language and runtime.

Having said that, if you need to do that, try to focus on using online assembly if you can, as you can still use a higher level language like c or c++ while retaining the ability to mess with assembly code when you need it.


问:
picamera: capture a frame while continuous capture in background
I'm capturing a timelapse with the picamera module for python:

```<code>from picamera import PiCamera, Color
class EggAlertCam:

    def __init__(self):
        self.camera = PiCamera()
        self.camera.start_preview()

    def capture_thread_task(self):

        filename = os.path.join(self.SAVEPATH, self.safe_camname + '_{timestamp:%Y%m%d-%H%M%S}-{counter:03d}' + '.jpg' )
        starttime = dt.datetime.now()
        current_time = dt.datetime.now()

        for filename in self.camera.capture_continuous(filename):
            print('Captured {}'.format(filename))
            self.wait(current_time)
            current_time = dt.datetime.now()

    def get_frame(self, size=None):
        if size is None:
            size = (640,480)
        output = io.BytesIO()
        self.camera.capture(output, format='jpeg', resize=size, use_video_port=True)
        output.seek(0)
        return output
</code>```

This capture_thread_task runs in a thread, and I have a Flask application allowing to capture frames from the camera through a REST call which calls get_frame.

I'm using video_port=True with the hope that I can fetch an (higher noise, but I don't care) image even while capturing the timelapse, but I get an exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/dist-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.7/dist-packages/xxx/webapp.py", line 53, in get_frame
    jpg = scheduler.cam.get_frame(size=size)
  File "/usr/local/lib/python3.7/dist-packages/xxx/xxx.py", line 124, in get_frame
    self.camera.capture(output, format='jpeg', resize=size, use_video_port=True)
  File "/usr/local/lib/python3.7/dist-packages/picamera/camera.py", line 1409, in capture
    camera_port, output_port = self._get_ports(use_video_port, splitter_port)
  File "/usr/local/lib/python3.7/dist-packages/picamera/camera.py", line 562, in _get_ports
    'The camera is already using port %d ' % splitter_port)
picamera.exc.PiCameraAlreadyRecording: The camera is already using port 0
```

I thought I'd be using another port for that capture, but alas it doesn't seem to work.

From the documentation here: https://picamera.readthedocs.io/en/release-1.10/fov.html?highlight=splitter#under-the-hood I figured that the capture_continuous function used port 0, and I should be able to use the port 1 which is the one used when telling use_video_port=True.
But the exception message tells me it still wants to use port 0..

EDIT: I tried with splitter port 2, and for some of my Pi's it seems to work, and for others the port 2 seems used. After a few minutes, the port starts to be avaiable and I can fetch a frame from it.

This looks like a capture that takes a too long time, but I don't know how to properly ask the port 2 to free itself for a new capture.

What am I doing wrong ?

答:
Where you declared EggAlertCam object - inside or outside of a view method?

Try outside or use singleton.

Or you can run that in separate thread/process and send commands from Flask to it.

Body:
I'm capturing a timelapse with the picamera module for python:

from picamera import PiCamera, Color
class EggAlertCam:

    def __init__(self):
        self.camera = PiCamera()
        self.camera.start_preview()

    def capture_thread_task(self):

        filename = os.path.join(self.SAVEPATH, self.safe_camname + '_{timestamp:%Y%m%d-%H%M%S}-{counter:03d}' + '.jpg' )
        starttime = dt.datetime.now()
        current_time = dt.datetime.now()

        for filename in self.camera.capture_continuous(filename):
            print('Captured {}'.format(filename))
            self.wait(current_time)
            current_time = dt.datetime.now()

    def get_frame(self, size=None):
        if size is None:
            size = (640,480)
        output = io.BytesIO()
        self.camera.capture(output, format='jpeg', resize=size, use_video_port=True)
        output.seek(0)
        return output

This capture_thread_task runs in a thread, and I have a Flask application allowing to capture frames from the camera through a REST call which calls get_frame.

I'm using video_port=True with the hope that I can fetch an (higher noise, but I don't care) image even while capturing the timelapse, but I get an exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/dist-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.7/dist-packages/xxx/webapp.py", line 53, in get_frame
    jpg = scheduler.cam.get_frame(size=size)
  File "/usr/local/lib/python3.7/dist-packages/xxx/xxx.py", line 124, in get_frame
    self.camera.capture(output, format='jpeg', resize=size, use_video_port=True)
  File "/usr/local/lib/python3.7/dist-packages/picamera/camera.py", line 1409, in capture
    camera_port, output_port = self._get_ports(use_video_port, splitter_port)
  File "/usr/local/lib/python3.7/dist-packages/picamera/camera.py", line 562, in _get_ports
    'The camera is already using port %d ' % splitter_port)
picamera.exc.PiCameraAlreadyRecording: The camera is already using port 0

I thought I'd be using another port for that capture, but alas it doesn't seem to work.

From the documentation here: https://picamera.readthedocs.io/en/release-1.10/fov.html?highlight=splitter#under-the-hood I figured that the capture_continuous function used port 0, and I should be able to use the port 1 which is the one used when telling use_video_port=True.
But the exception message tells me it still wants to use port 0..

EDIT: I tried with splitter port 2, and for some of my Pi's it seems to work, and for others the port 2 seems used. After a few minutes, the port starts to be avaiable and I can fetch a frame from it.

This looks like a capture that takes a too long time, but I don't know how to properly ask the port 2 to free itself for a new capture.

What am I doing wrong ?


问:
Java Queue for Scheduler
I am wondering how would I implement a queue of schedules?

For example, I have a ScheduledExecutorService that would perform a task every 30 seconds until success. Sometimes this task would succeed in 30 seconds, sometimes it would take a few minutes. ScheduledExecutorService would be given a job periodically. I would like it so that ScheduledExecutorService would move onto the next job only if its current job is successful. How would I implement this?

答:
As per the official documentation, you can use scheduleAtFixedDelay to impose a delay between execution:

Creates and executes a periodic action that becomes enabled first
  after the given initial delay, and subsequently with the given delay
  between the termination of one execution and the commencement of the
  next.

Not exactly how you worded your question, but it looks like its what you are trying to do.

See more at https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)

Title: Java Queue for Scheduler


问:
How can I force a TD with no content to render its border?
The TD has a DIV inside which I removed using jQuery's fadeOut function, but when it finishes the border disappears too.

I want to avoid that, is there any way other than adding a " " (which causes it to be ugly)?

EDIT: I am using Internet Explorer (6 and 7)

答: I ended up adding a transparent 1px image to the cell as  suggested by Jukka "Yucca" Korpela. For now I'll use this solution if there is no better alternative</p>

OwnerDisplayName: Juan Manuel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Graeme Perrow

LastEditorDisplayName: Patrick McElhaney


问:
Bash: Spurious "command not found" messages (I think)
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

```<code>inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}
</code>```

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

```<code>$ inDir "/tmp" "touch hi"
</code>```

correctly creates the file /tmp/hi, but also gives the error:

```<code>[2: command not found
</code>```

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

答:
Despite what it might look like, '[' is actually a command called test, so:

```<code>if [$# -le 1]; then
</code>```

should be:

```<code>if [ $# -le 1 ]; then
</code>```

Note the space between the '[' and the next bit of code. Without it, the code reads as

```<code>test$#
</code>```

which I think is obviously wrong. You also need a space before the closing square-bracket, which isn't a command, but is a delimiter.

Body:
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

$ inDir "/tmp" "touch hi"

correctly creates the file /tmp/hi, but also gives the error:

[2: command not found

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

Body:
Despite what it might look like, '[' is actually a command called test, so:

if [$# -le 1]; then

should be:

if [ $# -le 1 ]; then

Note the space between the '[' and the next bit of code. Without it, the code reads as

test$#

which I think is obviously wrong. You also need a space before the closing square-bracket, which isn't a command, but is a delimiter.


问:
How to deal with this website in a webscraping format?
I am trying to webscrape this website.

I am applying the same code that I always use to webscrape pages:

```<code>url_dv1 <- "https://ec.europa.eu/commission/presscorner/detail/en/qanda_20_171?fbclid=IwAR2GqXLmkKRkWPoy3-QDwH9DzJiexFJ4Sp2ZoWGbfmOR1Yv8POdlLukLRaU"

url_dv1 <- paste(html_text(html_nodes(read_html(url_dv1), "#inline-nav-1 .ecl-paragraph")), collapse = "")
</code>```

For this website, thought, the code doesn't seem to be working. In fact, I get Error in UseMethod("read_xml") :
  no applicable method for 'read_xml' applied to an object of class "c('xml_document', 'xml_node')".

Why is it so? How can I fix it?

Thanks a lot!

答:
The problem is that the web page is dynamically rendered. You can overcome this using phantomjs (can be downloaded here https://phantomjs.org/download.html). You will also need a custom javascript script (see below). The below R code works for me.</p>

```<code>library(tidyverse)
library(rvest)

dir_js <- "path/to/a/directory" # JS code needs to be inserted here, the name of the file needs to be javascript.js
url <- "https://ec.europa.eu/commission/presscorner/detail/en/qanda_20_171?fbclid=IwAR2GqXLmkKRkWPoy3-QDwH9DzJiexFJ4Sp2ZoWGbfmOR1Yv8POdlLukLRaU"

system2("path/to/where/you/have/phantomjs.exe", # directory to phantomJS
        args = c(file.path(dir_js, "javascript.js"), url))

read_html("myhtml.html") %>%
  html_nodes("#inline-nav-1 .ecl-paragraph") %>%
  html_text()

# this is the javascript code to be saved in javascript directory as javascript.js
// create a webpage object
var page = require('webpage').create(),
system = require('system')

// the url for each country provided as an argument
country= system.args[1];

// include the File System module for writing to files
var fs = require('fs');

// specify source and path to output file
// we'll just overwirte iteratively to a page in the same directory
var path = 'myhtml.html'
</code>```

Body:
I am trying to webscrape this website.

I am applying the same code that I always use to webscrape pages:

url_dv1 <- "https://ec.europa.eu/commission/presscorner/detail/en/qanda_20_171?fbclid=IwAR2GqXLmkKRkWPoy3-QDwH9DzJiexFJ4Sp2ZoWGbfmOR1Yv8POdlLukLRaU"

url_dv1 <- paste(html_text(html_nodes(read_html(url_dv1), "#inline-nav-1 .ecl-paragraph")), collapse = "")

For this website, thought, the code doesn't seem to be working. In fact, I get Error in UseMethod("read_xml") :
  no applicable method for 'read_xml' applied to an object of class "c('xml_document', 'xml_node')".

Why is it so? How can I fix it?

Thanks a lot!

Body:
The problem is that the web page is dynamically rendered. You can overcome this using phantomjs (can be downloaded here https://phantomjs.org/download.html). You will also need a custom javascript script (see below). The below R code works for me.

library(tidyverse)
library(rvest)

dir_js <- "path/to/a/directory" # JS code needs to be inserted here, the name of the file needs to be javascript.js
url <- "https://ec.europa.eu/commission/presscorner/detail/en/qanda_20_171?fbclid=IwAR2GqXLmkKRkWPoy3-QDwH9DzJiexFJ4Sp2ZoWGbfmOR1Yv8POdlLukLRaU"

system2("path/to/where/you/have/phantomjs.exe", # directory to phantomJS
        args = c(file.path(dir_js, "javascript.js"), url))

read_html("myhtml.html") %>%
  html_nodes("#inline-nav-1 .ecl-paragraph") %>%
  html_text()

# this is the javascript code to be saved in javascript directory as javascript.js
// create a webpage object
var page = require('webpage').create(),
system = require('system')

// the url for each country provided as an argument
country= system.args[1];

// include the File System module for writing to files
var fs = require('fs');

// specify source and path to output file
// we'll just overwirte iteratively to a page in the same directory
var path = 'myhtml.html'


问:
Trying to sum the values of a dynamic HTML table column
I'm trying to sum the values in the second column (title heading='Value'), however it currently always outputs 0. What am I missing??

(Also the table is populated from a javascript function, which I have included at the bottom of this question).

HTML:

```<code><table id="output_table">
        <tr>
            <th>Name</th>
            <th>Value</th>
        </tr>
        <tfoot>
            <tr>
                <th id="total" colspan="1">Total CPC:</th>
                <td id="sum1"></td>
            </tr>
    </tfoot>
    </table>
</code>```

JS:

```<code>// code to sum CPC column
        var sum1 = 0;
        $("#output_table Value").each(function() {
          sum1 +=  getnum($(this).find("td:eq(1)").text());
          function getnum(t){
            if(isNumeric(t)){
                return parseInt(t,10);
            }
            return 0;
                function isNumeric(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
                }
          }
        });
        $("#sum1").text(sum1);
</code>```

JS which populates table:

```<code> $('#sales_order_form_button').click(function(){
    let table_info = [];
    $('.campaignstrategy input[type=checkbox]').each(
        function(index, value){
        if($(this).is(':checked')){
            table_info.push(
                {
                    name: $(this).attr('name'),
                    value: $(this).attr('value'),
                }
            );
        }
    });
    let base64str=btoa(JSON.stringify(table_info));

    window.location = "sales_order_form.html?table_data=" + base64str;
});

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i=0;i<data_from_page_1.length;i++){
            let row = $("<tr></tr>");
            let recordName = $("<td></td>").text(data_from_page_1[i].name);
            let recordValue = $("<td></td>").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }
</code>```

答:
You will want to use tr > td:nth-child(2) selector to select elements in the second column of a table row. Code edited to be as simple as possible - it's simpler to use Number(x) || 0 for the same logic as your two functions.

var sum1 = 0;

$("#output_table tr > td:nth-child(2)").each(
  (_,el) => sum1 += Number($(el).text()) || 0
);

$("#sum1").text(sum1);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="output_table">
  <tr>
    <th>Name</th>
    <th>Value</th>
  </tr>
  <tr>
    <td>Bananas</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Apples</td>
    <td>5</td>
  </tr>
  <tfoot>
    <tr>
      <th id="total" colspan="1">Total CPC:</th>
      <td id="sum1"></td>
    </tr>
  </tfoot>
</table></code>```

Body:
I'm trying to sum the values in the second column (title heading='Value'), however it currently always outputs 0. What am I missing??

(Also the table is populated from a javascript function, which I have included at the bottom of this question).

HTML:

            Name
            Value

                Total CPC:

JS:

// code to sum CPC column
        var sum1 = 0;
        $("#output_table Value").each(function() {
          sum1 +=  getnum($(this).find("td:eq(1)").text());
          function getnum(t){
            if(isNumeric(t)){
                return parseInt(t,10);
            }
            return 0;
                function isNumeric(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
                }
          }
        });
        $("#sum1").text(sum1);

JS which populates table:

 $('#sales_order_form_button').click(function(){
    let table_info = [];
    $('.campaignstrategy input[type=checkbox]').each(
        function(index, value){
        if($(this).is(':checked')){
            table_info.push(
                {
                    name: $(this).attr('name'),
                    value: $(this).attr('value'),
                }
            );
        }
    });
    let base64str=btoa(JSON.stringify(table_info));

    window.location = "sales_order_form.html?table_data=" + base64str;
});

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i=0;i<data_from_page_1.length;i++){
            let row = $("

");
            let recordName = $("	").text(data_from_page_1[i].name);
            let recordValue = $("	").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

Body:
You will want to use tr > td:nth-child(2) selector to select elements in the second column of a table row. Code edited to be as simple as possible - it's simpler to use Number(x) || 0 for the same logic as your two functions.

var sum1 = 0;

$("#output_table tr > td:nth-child(2)").each(
  (_,el) => sum1 += Number($(el).text()) || 0
);

$("#sum1").text(sum1);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="output_table">
  <tr>
    <th>Name</th>
    <th>Value</th>
  </tr>
  <tr>
    <td>Bananas</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Apples</td>
    <td>5</td>
  </tr>
  <tfoot>
    <tr>
      <th id="total" colspan="1">Total CPC:</th>
      <td id="sum1"></td>
    </tr>
  </tfoot>
</table>


问:
How to use Http.GetJsonAsync() in Blazor Server App?
As I’m currently evaluating Blazor (Server) I made a simple POC application
In VS2019 (Version 16.3.8) for ordering pizzas. I created a Blazor Server App which get’s it’s data from
a Web API Core 3.0 Project, nothing fency, getting data at startup in the Index razor page is
implemented as next:

And the service which hides the external API-call is implemented as next:

So I’m using the regular GetStringAsync()  method on the created http client instance which returns
The requested data as a json-string which is finally deserialized to the required object-type.
But, unfortunately I can NOT use the GetJsonAsync() method here, as shown from the GitHub samples
which can be found here:

https://github.com/software-architects/learn-blazor/tree/master/samples/RestApi

After searching for a while, I came through next site :

https://learn-blazor.com/architecture/rest-api

which explained me I had to use the “HttpClientJsonExtensions”, as mentioned in next fragment from the site:

So, after downloading the samples and having a quick look at the “RestApi.Client” project (which contains the
WebAssembly hosted App), I see next referenced dependencies:

Which has (apparently) the extension method on the “Http” class for using GetJsonAsync() method from within the Client App.

So, my question is quit obvious, how can I have the same behavior in my Blazor Server based app, because there are no
Microsoft.AspNetCore.Blazor dependencies in my Blazor Server based app, as you can see next:

And because my PizzaMenuService lives in the “Services” folder of my Blazor Server app and makes the call to the Rest API
(as shown at the beginning of my request), it doesn’t have the extension method for executing GetJsonAsync() …
How can this be achieved then on a Blazor Server based app ?

Thx for any response !

Emmanuel Nuyttens.

答:
The GetJsonAsync() method is an extension method for HttpClient, but it looks like what you are really trying to achieve here is one level of abstractiobn higher - i.e. deserialization to an array of Customers. RestClient.Net can do that in Blazor without the extra step.

Here is a similar call in a Blazor page:

```<code>private List<RestCountry> countries;

protected override async Task OnInitializedAsync()
{
    countries = await new Client(new NewtonsoftSerializationAdapter(), baseUri: new Uri("https://restcountries.eu/rest/v2/")).GetAsync<List<RestCountry>>();
}
</code>```

Code Reference

This code works on both the server-side and client-side rendering and avoids the need to call GetJsonAsync. This  article explains how to get the sample working.

Body:
The GetJsonAsync() method is an extension method for HttpClient, but it looks like what you are really trying to achieve here is one level of abstractiobn higher - i.e. deserialization to an array of Customers. RestClient.Net can do that in Blazor without the extra step.

Here is a similar call in a Blazor page:

private List<RestCountry> countries;

protected override async Task OnInitializedAsync()
{
    countries = await new Client(new NewtonsoftSerializationAdapter(), baseUri: new Uri("https://restcountries.eu/rest/v2/")).GetAsync<List<RestCountry>>();
}

Code Reference

This code works on both the server-side and client-side rendering and avoids the need to call GetJsonAsync. This  article explains how to get the sample working.


问:
Laravel CKEditor5 - ClassicEditor is not Defined
I'm trying to replace an old version of CKEditor in a Laravel app due to dependency incompatibility with unisharp/laravel-ckeditor and Laravel 6. I've found the CKEditor 5 page with NPM installation instructions, but haven't been able to get it working. Here is my code:

resources/main.js

```<code>require('@ckeditor/ckeditor5-build-classic');

$(document).ready(function(){
  ClassicEditor.create($('#edit_about_text').get()[0]);
});
</code>```

webpack.mix.js

```<code>mix.js('resources/assets/js/main.js', 'public/js');
</code>```

layouts/master.blade.php

```<code><!doctype html>
<html>
  <head></head>
<body>
  <script src="{{ asset('js/main.js') }}"></script>
</body>
</html>
</code>```

jQuery is included (somehow; somewhat unfamiliar with webpack), but running a page that extends @extends('layouts.master') results in the following:

Uncaught ReferenceError: ClassicEditor is not defined

If I remove the require() statement from main.js and simply use the CDN link, everything works as expected:

```<code><script src="https://cdn.ckeditor.com/ckeditor5/16.0.0/classic/ckeditor.js"></script>
<script src="{{ asset('js/main.js') }}"></script>
</code>```

I'm doing something wrong, but I'm at a loss... Has anyone seen this issue before?

答:
Regarding Laravel included libraries examples in boostrap.js file such as pusher, axios, etc...

You may use

```<code>window.ClassicEditor = require('@ckeditor/ckeditor5-build-classic');

$(document).ready(function(){
  ClassicEditor.create($('#edit_about_text').get()[0]);
});
</code>```

Body:
I'm trying to replace an old version of CKEditor in a Laravel app due to dependency incompatibility with unisharp/laravel-ckeditor and Laravel 6. I've found the CKEditor 5 page with NPM installation instructions, but haven't been able to get it working. Here is my code:

resources/main.js

require('@ckeditor/ckeditor5-build-classic');

$(document).ready(function(){
  ClassicEditor.create($('#edit_about_text').get()[0]);
});

webpack.mix.js

mix.js('resources/assets/js/main.js', 'public/js');

layouts/master.blade.php

<!doctype html>

jQuery is included (somehow; somewhat unfamiliar with webpack), but running a page that extends @extends('layouts.master') results in the following:

Uncaught ReferenceError: ClassicEditor is not defined

If I remove the require() statement from main.js and simply use the CDN link, everything works as expected:

I'm doing something wrong, but I'm at a loss... Has anyone seen this issue before?

Body:
Regarding Laravel included libraries examples in boostrap.js file such as pusher, axios, etc...

You may use

window.ClassicEditor = require('@ckeditor/ckeditor5-build-classic');

$(document).ready(function(){
  ClassicEditor.create($('#edit_about_text').get()[0]);
});


问:
Select for login and update at the same time
Is it possible to use SQL command for login and update at the same time? I mean when the Login is done, I want to change logat in 1. Do I have to create a new if with OpenConnection()?

```<code>public bool IsLogin(string user, string pass) {
            string query = $"SELECT * from utiliz WHERE username='{user}' AND password='{GetSha1(pass)}'";
            string query_update = $"UPDATE utiliz SET logat='{1}' WHERE username='{user}'";
            try
            {
                if (OpenConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    MySqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        reader.Close();
                        conn.Close();
                        return true;
                    }
                    else
                    {
                        reader.Close();
                        conn.Close();
                        return false;
                    }
                }
                else {
                    conn.Close();
                    return false;
                }
            }
            catch (Exception ex) {
                conn.Close();
                return false;
            }
            }
</code>```

EDITED

Guys, I have edited my code, following parameters procedure. Is it good what I did?

```<code>if (String.IsNullOrEmpty(textBox_pass_login.Text) && String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_pass_login.Text))
            {
                System.Windows.Forms.MessageBox.Show("Both fields (username,password) are required");
            }
            else
            {
                string user = textBox_usr_login.Text;
                string password = textBox_pass_login.Text;
                string encryptedpass = GetSha1(password);
                try
                {
                    using (var connection = conn)
                    {
                        string query = "SELECT * from utiliz WHERE username=@user AND password=@password";
                        using (var command = new MySqlCommand(query, conn))
                        {
                            command.Parameters.AddWithValue("@user", user);
                            command.Parameters.AddWithValue("@password", encryptedpass);
                            MySqlDataAdapter sda = new MySqlDataAdapter(command);
                            DataTable dt = new DataTable();
                            sda.Fill(dt);
                            conn.Open();
                            int i = command.ExecuteNonQuery();
                            conn.Close();
                            if (dt.Rows.Count > 0)
                            {
                                this.Hide();
                                var form2 = new Form1();
                                form2.Closed += (s, args) => this.Close();
                                form2.Show();
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show("Wrong credentials");
                                textBox_usr_login.Clear();
                                textBox_pass_login.Clear();
                            }
                        }
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Wrong credentials");
                    textBox_usr_login.Clear();
                    textBox_pass_login.Clear();
                }
            }
</code>```

答:
As recommended (and demonstrated) by Felipe Oriani, you should use parameterized queries.

Let me pinpoint, however, that you can do this with a single update query. The trick is to filter the update query on both user name and password:

```<code>UPDATE utiliz SET logat = @logat WHERE username = @username AND password = @password
</code>```

You want to run the query with method ExecuteNonQuery, which returns the number of rows affected.

If credentials are valid, the where cause selects the relevant record and the update happens, returning 1 as the count of records affected. Else, no record is updated, and the method returns 0.

Body:
Is it possible to use SQL command for login and update at the same time? I mean when the Login is done, I want to change logat in 1. Do I have to create a new if with OpenConnection()?

public bool IsLogin(string user, string pass) {
            string query = $"SELECT * from utiliz WHERE username='{user}' AND password='{GetSha1(pass)}'";
            string query_update = $"UPDATE utiliz SET logat='{1}' WHERE username='{user}'";
            try
            {
                if (OpenConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    MySqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        reader.Close();
                        conn.Close();
                        return true;
                    }
                    else
                    {
                        reader.Close();
                        conn.Close();
                        return false;
                    }
                }
                else {
                    conn.Close();
                    return false;
                }
            }
            catch (Exception ex) {
                conn.Close();
                return false;
            }
            }

EDITED

Guys, I have edited my code, following parameters procedure. Is it good what I did?

if (String.IsNullOrEmpty(textBox_pass_login.Text) && String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_pass_login.Text))
            {
                System.Windows.Forms.MessageBox.Show("Both fields (username,password) are required");
            }
            else
            {
                string user = textBox_usr_login.Text;
                string password = textBox_pass_login.Text;
                string encryptedpass = GetSha1(password);
                try
                {
                    using (var connection = conn)
                    {
                        string query = "SELECT * from utiliz WHERE username=@user AND password=@password";
                        using (var command = new MySqlCommand(query, conn))
                        {
                            command.Parameters.AddWithValue("@user", user);
                            command.Parameters.AddWithValue("@password", encryptedpass);
                            MySqlDataAdapter sda = new MySqlDataAdapter(command);
                            DataTable dt = new DataTable();
                            sda.Fill(dt);
                            conn.Open();
                            int i = command.ExecuteNonQuery();
                            conn.Close();
                            if (dt.Rows.Count > 0)
                            {
                                this.Hide();
                                var form2 = new Form1();
                                form2.Closed += (s, args) => this.Close();
                                form2.Show();
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show("Wrong credentials");
                                textBox_usr_login.Clear();
                                textBox_pass_login.Clear();
                            }
                        }
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Wrong credentials");
                    textBox_usr_login.Clear();
                    textBox_pass_login.Clear();
                }
            }

Body:
As recommended (and demonstrated) by Felipe Oriani, you should use parameterized queries.

Let me pinpoint, however, that you can do this with a single update query. The trick is to filter the update query on both user name and password:

UPDATE utiliz SET logat = @logat WHERE username = @username AND password = @password

You want to run the query with method ExecuteNonQuery, which returns the number of rows affected.

If credentials are valid, the where cause selects the relevant record and the update happens, returning 1 as the count of records affected. Else, no record is updated, and the method returns 0.


问:
How to read in line from file, split after the second space so name and score are separated?
Not sure where it is that this is throwing an exception, but basically I'm trying to isolate the score so I can call the scores in a comparable function and print out the associated name and score in order of the score.

```<code>public void loadDataFromFile(String fileName) throws FileNotFoundException {
    FileReader reader = new FileReader(fileName);
    Scanner in = new Scanner(reader);

    while(in.hasNextLine()) {
        String line = in.nextLine();
        String name = line.substring(0, line.indexOf(' ', line.indexOf(' ') + 1));
        String score = line.substring(line.indexOf(name));
        int studentScore = Integer.parseInt(score);

        Student s = new Student(name, studentScore);
        student_list.add(s);
    }
}

public void printInOrder() {
    Collections.sort(this.student_list);
    for(Student s : student_list) {
        s.toString();
    }
}
</code>```

Text file that I'm reading from

答:
First, you never close your Scanner (and you can pass a File to the Scanner constructor, so no need for a FileReader) - I would use try-with-Resources to ensure that file handle is closed. Second, you need to consume (and skip) the header in your file. Finally, I would use String.lastIndexOf(String) instead of trying to find the second space (just find the last one). Something like,

```<code>public void loadDataFromFile(String fileName) throws FileNotFoundException {
    try (Scanner in = new Scanner(new File(fileName))) {
        if (in.hasNextLine()) {
            in.nextLine(); // consume header
        }
        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line.isEmpty()) {
                continue; // skip empty lines.
            }
            int p = line.lastIndexOf(" ");
            String name = line.substring(0, p);
            int studentScore = Integer.parseInt(line.substring(p + 1));
            Student s = new Student(name, studentScore);
            student_list.add(s);
        }
    }
}
</code>```

Body:
Not sure where it is that this is throwing an exception, but basically I'm trying to isolate the score so I can call the scores in a comparable function and print out the associated name and score in order of the score.

public void loadDataFromFile(String fileName) throws FileNotFoundException {
    FileReader reader = new FileReader(fileName);
    Scanner in = new Scanner(reader);

    while(in.hasNextLine()) {
        String line = in.nextLine();
        String name = line.substring(0, line.indexOf(' ', line.indexOf(' ') + 1));
        String score = line.substring(line.indexOf(name));
        int studentScore = Integer.parseInt(score);

        Student s = new Student(name, studentScore);
        student_list.add(s);
    }
}

public void printInOrder() {
    Collections.sort(this.student_list);
    for(Student s : student_list) {
        s.toString();
    }
}

Text file that I'm reading from

Body:
First, you never close your Scanner (and you can pass a File to the Scanner constructor, so no need for a FileReader) - I would use try-with-Resources to ensure that file handle is closed. Second, you need to consume (and skip) the header in your file. Finally, I would use String.lastIndexOf(String) instead of trying to find the second space (just find the last one). Something like,

public void loadDataFromFile(String fileName) throws FileNotFoundException {
    try (Scanner in = new Scanner(new File(fileName))) {
        if (in.hasNextLine()) {
            in.nextLine(); // consume header
        }
        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line.isEmpty()) {
                continue; // skip empty lines.
            }
            int p = line.lastIndexOf(" ");
            String name = line.substring(0, p);
            int studentScore = Integer.parseInt(line.substring(p + 1));
            Student s = new Student(name, studentScore);
            student_list.add(s);
        }
    }
}


问:
comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

```<code>>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False
</code>```

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

答:
To find if a word word is - for a lack of better word - "embedded" in a string s you need to find the position of the first letter of the word in the string, then the second letter in the remainder of the string (i.e. past the position of the first letter), etc. If at any stage you fail to find the next letter, you return False. This code does it:

```<code>def occurs_within(s, word):
    pos = 0
    for letter in word:
        i = s.find(letter, pos)
        if i == -1:
            return False
        pos = i+1
    return True
</code>```

Body:
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

Body:
To find if a word word is - for a lack of better word - "embedded" in a string s you need to find the position of the first letter of the word in the string, then the second letter in the remainder of the string (i.e. past the position of the first letter), etc. If at any stage you fail to find the next letter, you return False. This code does it:

def occurs_within(s, word):
    pos = 0
    for letter in word:
        i = s.find(letter, pos)
        if i == -1:
            return False
        pos = i+1
    return True


问:
Divide the data of array to two arrays
I’m getting a series of data from a json like it

```<code>   [
  {
   "name": "david",
    "gender": "Male"
  },
  {
    "name": "Sara",
    "gender": "Female"
  },
  {
    "name": "Philipp",
    "gender": "Male"
  },
  {
    "name": "Marry",
    "gender": "Female"
  }
]
</code>```

I get this data and store them into one array

Lets call it names

Now I want to create two other arrays

```<code>femaleNames

maleNames
</code>```

And I want to save all the female name in femaleNames and all the male names in maleNames based on the gender type of data.
I don’t that how I can implement this condition in swift 5. Could you please help me?
Thanks

答:
You can use filter over the array;

struct YourStruct: Decodable {
    let name: String
    let gender: String
}

let femaleNames = names.filter( { $0.gender == "Female"})
let maleNames = names.filter( { $0.gender == "Male"})
```

Title: Divide the data of array to two arrays

Body:
I’m getting a series of data from a json like it

   [
  {
   "name": "david",
    "gender": "Male"
  },
  {
    "name": "Sara",
    "gender": "Female"
  },
  {
    "name": "Philipp",
    "gender": "Male"
  },
  {
    "name": "Marry",
    "gender": "Female"
  }
]

I get this data and store them into one array

Lets call it names

Now I want to create two other arrays

femaleNames

maleNames

And I want to save all the female name in femaleNames and all the male names in maleNames based on the gender type of data.
I don’t that how I can implement this condition in swift 5. Could you please help me?
Thanks


问:
Regex C++: extract substring
I would like to extract a substring between two others.

ex: /home/toto/FILE_mysymbol_EVENT.DAT

or just FILE_othersymbol_EVENT.DAT

And I would like to get : mysymbol and othersymbol

I don't want to use boost or other libs. Just standard stuffs from C++, except CERN's ROOT lib, with TRegexp, but I don't know how to use it...

答:
I would study corner cases before trusting it.

But This is a good candidate:

```<code>std::string text = "/home/toto/FILE_mysymbol_EVENT.DAT";
std::regex reg("(.*)(FILE_)(.*)(_EVENT.DAT)(.*)");
std::cout << std::regex_replace(text, reg, "$3") << '\n';
</code>```

Title: Regex C++: extract substring

Body:
I would study corner cases before trusting it.

But This is a good candidate:

std::string text = "/home/toto/FILE_mysymbol_EVENT.DAT";
std::regex reg("(.*)(FILE_)(.*)(_EVENT.DAT)(.*)");
std::cout << std::regex_replace(text, reg, "$3") << '\n';


问:
How could I handle rest-client 500 error response and keep scraping through my loop?
I need to scrape 10k URLs from this website and some of them are out of service (I think... it's an error that does not return the JSON I'm looking for, so rest-client returns 500 Internal Server error in my program)

Error syntax: `exception_with_response': 500 Internal Server Error (RestClient::InternalServerError)

To loop through the URLs, I'm using a range (1..30).each do |id|. I concatenate the URL with the current iteration of this range.

```<code>response = RestClient.get(url+id)
</code>```

The problem is some times the URL I'm storing in the response variable does not exist and/or the webpage returns some error.
How could I protect my code so I can just pass through this problematic URL and keep the scraping?

Here's my current code (I put every code of the loop in a begin/rescue block, but I do not know how do write the code to do such thing):

```<code>require 'nokogiri'
require 'csv'
require 'rest-client'
require 'json'

link = "https://webfec.org.br/Utils/GetCentrobyId?cod="
CSV.open('data2.csv', 'ab') do |csv|
    csv << ['Name', 'Street', 'Info', 'E-mail', 'Site']
    (1..30).each do |id|
        begin
            response = RestClient.get(link+id.to_s)
            json = JSON.parse(response)
            html = json["Data"]
            doc = Nokogiri::HTML.parse(html)

            name = doc.xpath("/html/body/table/tbody/tr[1]").text
            street = doc.xpath("/html/body/table/tbody/tr[2]").text.gsub(Regexp.union(REMOVER), " ")
            info = doc.xpath("/html/body/table/tbody/tr[3]").text.gsub(Regexp.union(REMOVER), " ")
            email = doc.xpath("/html/body/table/tbody/tr[4]").text.gsub(Regexp.union(REMOVER), " ")
            site = doc.xpath("/html/body/table/tbody/tr[5]").text.gsub(Regexp.union(REMOVER), " ")

            csv << [name, street, info, email, site]
        rescue

        end
    end
end
</code>```

You can see I put everything in the loop inside a begin block and there is the rescue block at the end but I'm kind lost on how do to such thing.

答:
You should just rescue the exception for exmaple:

```<code>[*1..3].each{|i| RestClient.get('https://fooboton.free.beeceptor.com') rescue RestClient::InternalServerError; next}
</code>```

So for your case do:

```<code>CSV.open('data2.csv', 'ab') do |csv|
    csv << ['Name', 'Street', 'Info', 'E-mail', 'Site']
    (1..30).each do |id|
      begin
        response = RestClient.get(link+id.to_s)
      rescue RestClient::InternalServerError
        next # skip this iteration in your loop
      end
    ... # rest of your code
</code>```

Body:
I need to scrape 10k URLs from this website and some of them are out of service (I think... it's an error that does not return the JSON I'm looking for, so rest-client returns 500 Internal Server error in my program)

Error syntax: `exception_with_response': 500 Internal Server Error (RestClient::InternalServerError)

To loop through the URLs, I'm using a range (1..30).each do |id|. I concatenate the URL with the current iteration of this range.

response = RestClient.get(url+id)

The problem is some times the URL I'm storing in the response variable does not exist and/or the webpage returns some error.
How could I protect my code so I can just pass through this problematic URL and keep the scraping?

Here's my current code (I put every code of the loop in a begin/rescue block, but I do not know how do write the code to do such thing):

require 'nokogiri'
require 'csv'
require 'rest-client'
require 'json'

link = "https://webfec.org.br/Utils/GetCentrobyId?cod="
CSV.open('data2.csv', 'ab') do |csv|
    csv << ['Name', 'Street', 'Info', 'E-mail', 'Site']
    (1..30).each do |id|
        begin
            response = RestClient.get(link+id.to_s)
            json = JSON.parse(response)
            html = json["Data"]
            doc = Nokogiri::HTML.parse(html)

            name = doc.xpath("/html/body/table/tbody/tr[1]").text
            street = doc.xpath("/html/body/table/tbody/tr[2]").text.gsub(Regexp.union(REMOVER), " ")
            info = doc.xpath("/html/body/table/tbody/tr[3]").text.gsub(Regexp.union(REMOVER), " ")
            email = doc.xpath("/html/body/table/tbody/tr[4]").text.gsub(Regexp.union(REMOVER), " ")
            site = doc.xpath("/html/body/table/tbody/tr[5]").text.gsub(Regexp.union(REMOVER), " ")

            csv << [name, street, info, email, site]
        rescue

        end
    end
end

You can see I put everything in the loop inside a begin block and there is the rescue block at the end but I'm kind lost on how do to such thing.

Body:
You should just rescue the exception for exmaple:

[*1..3].each{|i| RestClient.get('https://fooboton.free.beeceptor.com') rescue RestClient::InternalServerError; next}

So for your case do:

CSV.open('data2.csv', 'ab') do |csv|
    csv << ['Name', 'Street', 'Info', 'E-mail', 'Site']
    (1..30).each do |id|
      begin
        response = RestClient.get(link+id.to_s)
      rescue RestClient::InternalServerError
        next # skip this iteration in your loop
      end
    ... # rest of your code


问:
What is the difference between WS_POPUP and WS_OVERLAPPED without titlebar?
If I handle WM_NCCALCSIZE for a window with the style WS_OVERLAPPED, I just simply return 0 when the WPARAM value is TRUE. This removes the window borders.

What is the difference between doing that, rather than creating a WS_POPUP window? Are the actual frames different if I try to extend the frames using DwmExtendFrameIntoClientArea? And when should I try to use each style?

答: WS_POPUP is not nearly as relevant as it once was, it is a hint to the OS that the window is not likely to be long-lived and thus to save the display area under the window rather than require repainting when the window is dismissed. The window handled by the popup menu loop for example, or dialogs. This used to be a major performance benefit (particularly in the days of win16) when used appropriately, I am not aware of any difference in the actual mechanics between overlapped and popup windows.</p>


问:
C - how to add a char to an array
I'm trying to figure out how to add a simple char to an array created with malloc.

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    char *array = malloc(2);
    array[0] = "h";
    printf("%s", array);
    return 0;
}
</code>```

It gives the warning:

```<code> warning: assignment makes integer from pointer without a cast [-Wint-conversion]
array[0] = "h";
</code>```

and if I run the program anyway, it just prints out 3 random symbols.

答:
You're assigning a string to a character. Instead, assign a character:

```<code>array[0] = 'h';
</code>```

After that you need to null-terminate your string:

```<code>array[1] = '\0';
</code>```

Alternatively, you can copy the string in using strcpy:

```<code>strcpy(array, "h");
</code>```

Title: C - how to add a char to an array

Body:
I'm trying to figure out how to add a simple char to an array created with malloc.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *array = malloc(2);
    array[0] = "h";
    printf("%s", array);
    return 0;
}

It gives the warning:

 warning: assignment makes integer from pointer without a cast [-Wint-conversion]
array[0] = "h";

and if I run the program anyway, it just prints out 3 random symbols.

Body:
You're assigning a string to a character. Instead, assign a character:

array[0] = 'h';

After that you need to null-terminate your string:

array[1] = '\0';

Alternatively, you can copy the string in using strcpy:

strcpy(array, "h");


问:
previous value using DAX

I have three columns: date, companyID & Users. Below is a sample table:

```<code>Date         CompanyID     Users
2/14/2020        1           20
1/30/2020        1           45
12/30/2019       1           55
</code>```

What I am looking to do is create a DAX measure, that will look up the previous value. For example:

```<code>Date         CompanyID     Users       Pre_value
2/14/2020        1           20           45
1/30/2020        1           45           55
12/30/2019       1           55            0
</code>```

The date add functions are not working, because my dates are inconsistent. My date column will show today date & the end of month date for previous months.

答:
Perhaps something like this:

```<code>Pre_Value =
    VAR CompanyID = 'Table'[CompanyID]
    VAR Date1 = 'Table'[Date]
    VAR Pre_Date = CALCULATE(MAX('Table'[Date]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]<Date1))
    VAR Prev_Val = CALCULATE(MAX('Table'[Users]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]=Pre_Date))
RETURN IF(Prev_Val=BLANK(),0,Prev_Val)
</code>```

The idea is to get the previous date from the current row (VAR pre_date) and use that to get the corresponding value. Hope this helps.

Edit: If you want to go back 2 records:

```<code>Pre_Value_2 =
    VAR CompanyID = 'Table'[CompanyID]
    VAR Date1 = 'Table'[Date]
    VAR Pre_Date = CALCULATE(MAX('Table'[Date]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]<Date1))
    VAR Pre_Date_2 = CALCULATE(MAX('Table'[Date]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]<Pre_date))
    VAR Prev_Val_2 = CALCULATE(MAX('Table'[Users]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]=Pre_Date_2))
RETURN IF(Prev_Val_2=BLANK(),0,Prev_Val_2)
</code>```

I have created another variable to go back one more date (pre_date_2).

Title: previous value using DAX

Body:
I have three columns: date, companyID & Users. Below is a sample table:

Date         CompanyID     Users
2/14/2020        1           20
1/30/2020        1           45
12/30/2019       1           55

What I am looking to do is create a DAX measure, that will look up the previous value. For example:

Date         CompanyID     Users       Pre_value
2/14/2020        1           20           45
1/30/2020        1           45           55
12/30/2019       1           55            0

The date add functions are not working, because my dates are inconsistent. My date column will show today date & the end of month date for previous months.

Body:
Perhaps something like this:

Pre_Value =
    VAR CompanyID = 'Table'[CompanyID]
    VAR Date1 = 'Table'[Date]
    VAR Pre_Date = CALCULATE(MAX('Table'[Date]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]<Date1))
    VAR Prev_Val = CALCULATE(MAX('Table'[Users]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]=Pre_Date))
RETURN IF(Prev_Val=BLANK(),0,Prev_Val)

The idea is to get the previous date from the current row (VAR pre_date) and use that to get the corresponding value. Hope this helps.

Edit: If you want to go back 2 records:

Pre_Value_2 =
    VAR CompanyID = 'Table'[CompanyID]
    VAR Date1 = 'Table'[Date]
    VAR Pre_Date = CALCULATE(MAX('Table'[Date]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]<Date1))
    VAR Pre_Date_2 = CALCULATE(MAX('Table'[Date]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]<Pre_date))
    VAR Prev_Val_2 = CALCULATE(MAX('Table'[Users]),FILTER('Table','Table'[CompanyID]=CompanyID),FILTER('Table','Table'[Date]=Pre_Date_2))
RETURN IF(Prev_Val_2=BLANK(),0,Prev_Val_2)

I have created another variable to go back one more date (pre_date_2).


问:
Trouble with how to declare (or define) a function in a header
I'm struggling with implementation of a function that I define in my header file of my c++ program. I think I am misunderstanding how it works, but most reading on the web doesn't spell it out clear enough for my peon brain to understand.

I'm trying to make a 'sort_name' function that sorts an array of private classes based on the c-string "name" when the function is invoked.

Unfortunately I keep running into errors when trying to use it.

Here's my courses_main.cpp's main function:

```<code>int main()
{
    Course* courses[10] = {};
    int selection;

    int size = 0;
    do
    {
        selection = menu();

        if (selection == 1)
        {
            if (size < 10)
                add(courses, size);
            else
                std::cout << "\nUnable to add more classes.";
        }
        else if (selection == 2)
        {
            edit(courses, size);
        }
        else if (selection == 3)
        {

        }
        else if (selection == 4)
        {
            sort_name(courses, size);
            for (int i = 0; i < size; i++)
            {
                courses[i]->display();
            }
        }
        else if (selection == 5)
        {

        }
        else if (selection == 6)
        {

        }
        else if (selection == 7)
        {
            break;
        }
        else
        {
            std::cout << "\nInvalid selection.";
        }
    } while (selection != 7);

    std::cout << "\nPress any key to exit.";
    (void)_getch();
    return 0;
}
</code>```

Here is my courses_functions.cpp where I define the sort_name function:

```<code>void swap_ptrs(Course*& pt1, Course*& pt2) //Passes the pointers by reference
{
    Course* tmp = pt1;
    pt1 = pt2;
    pt2 = tmp;
}

void Course::sort_name(Course* co_ptr[], int size) //has to be apart of the class (Course::) to have access to the name data
{
    bool swap;

    do
    {
        swap = false;
        for (int i = 0; i < size - 1; i++)
        {
            if (strcmp(co_ptr[i]->name, co_ptr[i + 1]->name) > 0) //We're now comparing and swapping pointers
            {
                swap_ptrs(co_ptr[i], co_ptr[i + 1]);
                swap = true;
            }
        }
    } while (swap);
}
</code>```

And here is my courses.h header where I define(?) the function:

```<code>#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <conio.h>
#include <iomanip>
#include <stdio.h>
#include <string.h>
#include <ctime>
#include <fstream>
#include <cstdlib>

class Course
{
private:
    char name[10] = "", grade;
    int units;
public:
    Course()
    {
        name;
        grade;
        units = 0;
    }

    void read() //Initializes course and collects information from user
    {
        std::cout << "\nEnter course name: ";
        std::cin.getline(name, 10, '\n');
        std::cout << "\nEnter number of units: ";
        std::cin >> units;
        std::cout << "\nEnter grade received: ";
        std::cin >> grade;
        std::cin.ignore();
    }

    void display() const //Displays course to user
    {
        std::cout << name << ' ' << units << ' ' << grade << std::endl;
    }

    ~Course() //Destructor frees allocated dynamic memory
    {
        std::cout << "\nDeleting any dynamically created object";
    }

    void sort_name(Course* co_ptr[], int size);
};

#endif // COURSE_H
</code>```

I'm not understanding much about classes outside of how they're extremely similar to structs, so any direction would be welcome thanks!

答:
A better code organization would be to declare the functions in the .h file and implement them in the.cpp.

Here is a working sample without .cpp for simplification. Only Courses.h and main.

With .cpp your program should be somethong like this:

Course.h

```<code>#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;  //<-- for test pusposes, you should use std:: scope

class Course
{
private:
    string name;
    int units, grade;

public:
    Course(); //<-- the code you have inside the constructor, only units = 0,
              // does somenthing, you should initialize all the members.
    Course(string name);
    void read();
    void display() const;
    ~Course(); //<-- to dealocate dynamic memory you need to really dealocate it with delete.
    string getName() const;
};

#endif // COURSE_H
</code>```

And in your .ccp the implementation:

Course.cpp

```<code>#include "Course.h"

Course::Course(){ /*do stuff*/ }

Course::Course(string name) : name(name) { /*do stuff*/ } //<-- initializing name here

void Course::read() {/*do stuff*/ }

void Course::display() const {/*do stuff*/ }

Course::~Course() {/*do stuff*/ }

string Course::getName() const { return name; }
</code>```

For sorting you don't need anything fancy you have sorting tools and data structures in the C++ libraries that make your job easy, like vector for objects container and sort for sorting.

Main

```<code>#include "Course.h"

 bool sorting(Course course1, Course course2) { //conditional function for sort (#include <algorithm>)
    return course1.getName() < course2.getName();
}

int main() {

    vector<Course> courses = { Course("zed"), Course("albert")}; // adding courses
    courses.push_back(Course("mary")); // adding some more
    courses.push_back(Course("john"));
    courses.push_back(Course("ana"));
    courses.push_back(Course("charles"));

    sort(courses.begin(), courses.end(), sorting); //<-- sorting

    for (Course c : courses) {
        cout << c.getName() << " ";
    }
}
</code>```

Output:

```<code>albert ana charles john mary zed
</code>```

Body:
I'm struggling with implementation of a function that I define in my header file of my c++ program. I think I am misunderstanding how it works, but most reading on the web doesn't spell it out clear enough for my peon brain to understand.

I'm trying to make a 'sort_name' function that sorts an array of private classes based on the c-string "name" when the function is invoked.

Unfortunately I keep running into errors when trying to use it.

Here's my courses_main.cpp's main function:

int main()
{
    Course* courses[10] = {};
    int selection;

    int size = 0;
    do
    {
        selection = menu();

        if (selection == 1)
        {
            if (size < 10)
                add(courses, size);
            else
                std::cout << "\nUnable to add more classes.";
        }
        else if (selection == 2)
        {
            edit(courses, size);
        }
        else if (selection == 3)
        {

        }
        else if (selection == 4)
        {
            sort_name(courses, size);
            for (int i = 0; i < size; i++)
            {
                courses[i]->display();
            }
        }
        else if (selection == 5)
        {

        }
        else if (selection == 6)
        {

        }
        else if (selection == 7)
        {
            break;
        }
        else
        {
            std::cout << "\nInvalid selection.";
        }
    } while (selection != 7);

    std::cout << "\nPress any key to exit.";
    (void)_getch();
    return 0;
}

Here is my courses_functions.cpp where I define the sort_name function:

void swap_ptrs(Course*& pt1, Course*& pt2) //Passes the pointers by reference
{
    Course* tmp = pt1;
    pt1 = pt2;
    pt2 = tmp;
}

void Course::sort_name(Course* co_ptr[], int size) //has to be apart of the class (Course::) to have access to the name data
{
    bool swap;

    do
    {
        swap = false;
        for (int i = 0; i < size - 1; i++)
        {
            if (strcmp(co_ptr[i]->name, co_ptr[i + 1]->name) > 0) //We're now comparing and swapping pointers
            {
                swap_ptrs(co_ptr[i], co_ptr[i + 1]);
                swap = true;
            }
        }
    } while (swap);
}

And here is my courses.h header where I define(?) the function:

#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <conio.h>
#include <iomanip>
#include <stdio.h>
#include <string.h>
#include <ctime>
#include <fstream>
#include <cstdlib>

class Course
{
private:
    char name[10] = "", grade;
    int units;
public:
    Course()
    {
        name;
        grade;
        units = 0;
    }

    void read() //Initializes course and collects information from user
    {
        std::cout << "\nEnter course name: ";
        std::cin.getline(name, 10, '\n');
        std::cout << "\nEnter number of units: ";
        std::cin >> units;
        std::cout << "\nEnter grade received: ";
        std::cin >> grade;
        std::cin.ignore();
    }

    void display() const //Displays course to user
    {
        std::cout << name << ' ' << units << ' ' << grade << std::endl;
    }

    ~Course() //Destructor frees allocated dynamic memory
    {
        std::cout << "\nDeleting any dynamically created object";
    }

    void sort_name(Course* co_ptr[], int size);
};

#endif // COURSE_H

I'm not understanding much about classes outside of how they're extremely similar to structs, so any direction would be welcome thanks!

Body:
A better code organization would be to declare the functions in the .h file and implement them in the.cpp.

Here is a working sample without .cpp for simplification. Only Courses.h and main.

With .cpp your program should be somethong like this:

Course.h

#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;  //<-- for test pusposes, you should use std:: scope

class Course
{
private:
    string name;
    int units, grade;

public:
    Course(); //<-- the code you have inside the constructor, only units = 0,
              // does somenthing, you should initialize all the members.
    Course(string name);
    void read();
    void display() const;
    ~Course(); //<-- to dealocate dynamic memory you need to really dealocate it with delete.
    string getName() const;
};

#endif // COURSE_H

And in your .ccp the implementation:

Course.cpp

#include "Course.h"

Course::Course(){ /*do stuff*/ }

Course::Course(string name) : name(name) { /*do stuff*/ } //<-- initializing name here

void Course::read() {/*do stuff*/ }

void Course::display() const {/*do stuff*/ }

Course::~Course() {/*do stuff*/ }

string Course::getName() const { return name; }

For sorting you don't need anything fancy you have sorting tools and data structures in the C++ libraries that make your job easy, like vector for objects container and sort for sorting.

Main

#include "Course.h"

 bool sorting(Course course1, Course course2) { //conditional function for sort (#include <algorithm>)
    return course1.getName() < course2.getName();
}

int main() {

    vector<Course> courses = { Course("zed"), Course("albert")}; // adding courses
    courses.push_back(Course("mary")); // adding some more
    courses.push_back(Course("john"));
    courses.push_back(Course("ana"));
    courses.push_back(Course("charles"));

    sort(courses.begin(), courses.end(), sorting); //<-- sorting

    for (Course c : courses) {
        cout << c.getName() << " ";
    }
}

Output:

albert ana charles john mary zed


问:
obtain a strictly increasing sequence of the elements of array
So the task is this:
You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.

EXAMPLE:

input_array = [1, 1, 1], the output should be
array_change(input_array) = 3

this is my code and it works fine, it counts the moves correctly but for larger arrays it operates very slow. how can i optimize my code to do the same but faster? or is there just a better and faster way to do it?
MY CODE:

```<code>def array_change(input_array):
    l = len(input_array)
    k = 0
    for i in range(1, l):
        while input_array[i - 1] >= input_array[i]:
            input_array[i] += 1
            k += 1
            if input_array[i - 1] == input_array[i]:
                input_array[i] += 1
                k += 1

    return k
</code>```

答:
ok i just got the right way to do this.</p>

```<code>def arrayChange(iA):
    c = 0
    for i in range(len(iA) - 1):
        if iA[i] >= iA[i + 1]:
            d = iA[i] - iA[i + 1]
            iA[i + 1] += d + 1
            c += d + 1
    return c
</code>```

Body:
So the task is this:
You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.

EXAMPLE:

input_array = [1, 1, 1], the output should be
array_change(input_array) = 3

this is my code and it works fine, it counts the moves correctly but for larger arrays it operates very slow. how can i optimize my code to do the same but faster? or is there just a better and faster way to do it?
MY CODE:

def array_change(input_array):
    l = len(input_array)
    k = 0
    for i in range(1, l):
        while input_array[i - 1] >= input_array[i]:
            input_array[i] += 1
            k += 1
            if input_array[i - 1] == input_array[i]:
                input_array[i] += 1
                k += 1

    return k

Body:
ok i just got the right way to do this.

def arrayChange(iA):
    c = 0
    for i in range(len(iA) - 1):
        if iA[i] >= iA[i + 1]:
            d = iA[i] - iA[i + 1]
            iA[i + 1] += d + 1
            c += d + 1
    return c


问:
Rounding behavior of updateSliderInput in R shiny
I am trying to use the following R Shiny code to use the first slider to for updates in the second slider. However, when the updateSliderInput function is called, it seems to overwrite the round = T in the original sliderInput. I know that, since I am dividing by 9 in the updateSliderInput function, the step size will not be an integer for some values of the first slider, but is there a way to show a rounded value in the recalculated slider so that I don't get 16 digits of precision?

```<code>ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      p("The first slider controls the second"),
      sliderInput(inputId = "value", label = "The independent slider",
                  min = 1000, max = 1500, value = 1000, step = 100, round = T
      ),
      sliderInput(inputId = "value2", label = "The dependent slider",
                      min = 5, max = 500, value = 50, round = T
      )
    ),
    mainPanel()
  )
)

server <- function(input, output, session) {
  observe({
    val <- input$value

    updateSliderInput(session, "value2", value = (val * 0.3),
                      min = (val * 0.005),
                      max = (val * 0.5),
                      step = floor((val * 0.5) - floor(val * 0.005))/9)

  })
}

shinyApp(ui, server)
</code>```

Right now, I see this, no matter what I try:

答:
Is it as simple as just rounding your step= values?

```<code>server <- function(input, output, session) {
  observe({
    val <- input$value

    updateSliderInput(session, "value2", value = (val * 0.3),
                      min = (val * 0.005),
                      max = (val * 0.5),
                      step = round(floor((val * 0.5) - floor(val * 0.005))/9, 1))

  })
}
</code>```

You could also floor or ceiling, or even use signif to get a total number of digits (instead of round, which does digits after the decimal).

Body:
I am trying to use the following R Shiny code to use the first slider to for updates in the second slider. However, when the updateSliderInput function is called, it seems to overwrite the round = T in the original sliderInput. I know that, since I am dividing by 9 in the updateSliderInput function, the step size will not be an integer for some values of the first slider, but is there a way to show a rounded value in the recalculated slider so that I don't get 16 digits of precision?

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      p("The first slider controls the second"),
      sliderInput(inputId = "value", label = "The independent slider",
                  min = 1000, max = 1500, value = 1000, step = 100, round = T
      ),
      sliderInput(inputId = "value2", label = "The dependent slider",
                      min = 5, max = 500, value = 50, round = T
      )
    ),
    mainPanel()
  )
)

server <- function(input, output, session) {
  observe({
    val <- input$value

    updateSliderInput(session, "value2", value = (val * 0.3),
                      min = (val * 0.005),
                      max = (val * 0.5),
                      step = floor((val * 0.5) - floor(val * 0.005))/9)

  })
}

shinyApp(ui, server)

Right now, I see this, no matter what I try:

Body:
Is it as simple as just rounding your step= values?

server <- function(input, output, session) {
  observe({
    val <- input$value

    updateSliderInput(session, "value2", value = (val * 0.3),
                      min = (val * 0.005),
                      max = (val * 0.5),
                      step = round(floor((val * 0.5) - floor(val * 0.005))/9, 1))

  })
}

You could also floor or ceiling, or even use signif to get a total number of digits (instead of round, which does digits after the decimal).