问:
Use multiple SQL query results in one SQL query
I have a project with two MySQL tables;

LedgerSchedule

GeneralLedger

The first table LedgerSchedule contains the possible types which are used in GeneralLedger. Each record from GeneralLedger can be a CREDIT or DEBIT transaction (from type LedgerSchedule).

Now if i want to create a transaction survey with GeneralLedger transactions i run three queries in my project;

Select possible LedgerSchedule's

Select CREDIT GeneralLedgers for each LedgerSchedule

Select DEBIT GeneralLedgers for each LedgerSchedule

After this three queries i save the (DEBIT-CREDIT) amounts back to each LedgerSchedule.
This works, but it is slow (especially when there are many LedgerSchedule's).
To speed things up, i want to accomplish this with one MySQL query.

Summarised i want to Select LedgerSchedule's with their CREDIT/DEBIT GeneralLedgers amounts in one query.

A first attempt (in this example i select only the ID from LedgerSchedule);

But this selects only the GeneralLedgers with DEBIT and CREDIT transactions. Changing this to

```<code>WHERE LS.ID = DEBIT.ID
OR LS.ID = CREDIT.ID
</code>```

Isn't working either. Next to this i also want to select the LedgerSchedule's without any GeneralLedgers DEBIT/CREDIT transactions.

```<code>| LedgerSchedule | Debit   | Credit  |
|       1        | €30.00  |         |
|       2        |         | €23.45  |
|       3        |         |         |
|       4        | €15.15  | €10.00  |
|       5        |         |         |
</code>```

How can i accomplish this? Maybe even without multiple Selects in one query ...

答:
If I understand correctly, you just want conditional aggregation:

```<code>select gl.ledger_schedule_id,
       sum(case when gl.debit_credit = 1 then gl.amount else - gl.amount
           end) as net
from GeneralLedger gl
group by gl.ledger_schedule_id;
</code>```

If debit_credit could take on a value other than 0 or 1, you'll want a where clause to prevent overcounting.

If you want the amounts separately:

```<code>select gl.ledger_schedule_id,
       sum(case when gl.debit_credit = 1 then gl.amount end) as credit,
       sum(case when gl.debit_credit = 0 then gl.amount end) as debit
from GeneralLedger gl
group by gl.ledger_schedule_id;
</code>```

Body:
I have a project with two MySQL tables;

LedgerSchedule

GeneralLedger

The first table LedgerSchedule contains the possible types which are used in GeneralLedger. Each record from GeneralLedger can be a CREDIT or DEBIT transaction (from type LedgerSchedule).

Now if i want to create a transaction survey with GeneralLedger transactions i run three queries in my project;

Select possible LedgerSchedule's

Select CREDIT GeneralLedgers for each LedgerSchedule

Select DEBIT GeneralLedgers for each LedgerSchedule

After this three queries i save the (DEBIT-CREDIT) amounts back to each LedgerSchedule.
This works, but it is slow (especially when there are many LedgerSchedule's).
To speed things up, i want to accomplish this with one MySQL query.

Summarised i want to Select LedgerSchedule's with their CREDIT/DEBIT GeneralLedgers amounts in one query.

A first attempt (in this example i select only the ID from LedgerSchedule);

But this selects only the GeneralLedgers with DEBIT and CREDIT transactions. Changing this to

WHERE LS.ID = DEBIT.ID
OR LS.ID = CREDIT.ID

Isn't working either. Next to this i also want to select the LedgerSchedule's without any GeneralLedgers DEBIT/CREDIT transactions.

| LedgerSchedule | Debit   | Credit  |
|       1        | €30.00  |         |
|       2        |         | €23.45  |
|       3        |         |         |
|       4        | €15.15  | €10.00  |
|       5        |         |         |

How can i accomplish this? Maybe even without multiple Selects in one query ...

Body:
If I understand correctly, you just want conditional aggregation:

select gl.ledger_schedule_id,
       sum(case when gl.debit_credit = 1 then gl.amount else - gl.amount
           end) as net
from GeneralLedger gl
group by gl.ledger_schedule_id;

If debit_credit could take on a value other than 0 or 1, you'll want a where clause to prevent overcounting.

If you want the amounts separately:

select gl.ledger_schedule_id,
       sum(case when gl.debit_credit = 1 then gl.amount end) as credit,
       sum(case when gl.debit_credit = 0 then gl.amount end) as debit
from GeneralLedger gl
group by gl.ledger_schedule_id;


来源: stackexchange

问:
How to access classes with on one instance?
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

```<code>generalService.AbcService.MethodName();
generalService.AbcService.MethodName();
</code>```

How do I do this in the best possible way?

答:
Unfortunately in C# you can NOT inherit from two classes at once so something like

```<code>public class CombinedService : AbcService, XyzService {

}
</code>```

is not possible.

You can however use static methods to have only one instance per service like this:

```<code>public static class ServiceManager {
    // The variable holding the instance
    private static AbcService _abcService = null;
    // Access to the instance and single instance creator
    public static AbcService AbcServiceInstance {
        get {
            if (_abcService == null) {
                // Create your Instance here
                _abcService = new AbcService();
            }
            return _abcService;
        }
    }

    // The variable holding the instance
    private static XyzService _xyzService = null;
    // Access to the instance and single instance creator
    public static XyzService XyzServiceInstance {
        get {
            if (_xyzService == null) {
                // Create your Instance here
                _xyzService = new XyzService();
            }
            return _xyzService;
        }
    }
}
</code>```

Because they are static you can access them from everywhere in the code just by calling the static class properties like this:

```<code>ServiceManager.AbcServiceInstance.SomeMethod();
ServiceManager.XyzServiceInstance.SomeMethod();
</code>```

You can also shorten the instantiation and accessor like this:

```<code>private static AbcService _abcService = new AbcService();
public static XyzService XyzServiceInstance {
    get { return _abcService; }
}
</code>```

If the instances can just be created like this and don't need any more parameters or configuration.

ContentLicense: CC BY-SA 3.0

Body:
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

generalService.AbcService.MethodName();
generalService.AbcService.MethodName();

How do I do this in the best possible way?

Body:
Unfortunately in C# you can NOT inherit from two classes at once so something like

public class CombinedService : AbcService, XyzService {

}

is not possible.

You can however use static methods to have only one instance per service like this:

public static class ServiceManager {
    // The variable holding the instance
    private static AbcService _abcService = null;
    // Access to the instance and single instance creator
    public static AbcService AbcServiceInstance {
        get {
            if (_abcService == null) {
                // Create your Instance here
                _abcService = new AbcService();
            }
            return _abcService;
        }
    }

    // The variable holding the instance
    private static XyzService _xyzService = null;
    // Access to the instance and single instance creator
    public static XyzService XyzServiceInstance {
        get {
            if (_xyzService == null) {
                // Create your Instance here
                _xyzService = new XyzService();
            }
            return _xyzService;
        }
    }
}

Because they are static you can access them from everywhere in the code just by calling the static class properties like this:

ServiceManager.AbcServiceInstance.SomeMethod();
ServiceManager.XyzServiceInstance.SomeMethod();

You can also shorten the instantiation and accessor like this:

private static AbcService _abcService = new AbcService();
public static XyzService XyzServiceInstance {
    get { return _abcService; }
}

If the instances can just be created like this and don't need any more parameters or configuration.


问:
Multiple HTTP request using ajax
I am new to js and ajax.
I want a code that calls a disp.php file and display its output in load.php. The ajax code should pass a value from load.php to disp.php and there must be a five second delay between each call.

Basically I want to replace the below php code which will fail due to script timeout. load() and disp() are functions of disp.php

```<code>require("disp.php");

for($i = 1; $i <= $pt[1]; $i++)
{
    load($mat,$i);
    disp();
    sleep(5);
}
</code>```

答:
To make an Ajax call from Javascript see this How to make an AJAX call without jQuery?

And to make the call after every five seconds use setTimeout

```<code><script>
   function callLoad() {
       ......write logic to call the PHP file here...
   }

   var callCount = 0;

   function callLoop() {
       callLoad();
       callCount ++;

       if(callCount == 5) return; // Stop the loop

       setTimeout(function() {
           callLoop();
      }, 5000); // Wait for 5 second to make the call again

   }

   window.onload = callLoop; // Start the loop after the page has finished loading
</script>
</code>```

Title: Multiple HTTP request using ajax

Body:
I am new to js and ajax.
I want a code that calls a disp.php file and display its output in load.php. The ajax code should pass a value from load.php to disp.php and there must be a five second delay between each call.

Basically I want to replace the below php code which will fail due to script timeout. load() and disp() are functions of disp.php

require("disp.php");

for($i = 1; $i <= $pt[1]; $i++)
{
    load($mat,$i);
    disp();
    sleep(5);
}

Body:
To make an Ajax call from Javascript see this How to make an AJAX call without jQuery?

And to make the call after every five seconds use setTimeout

<script>
   function callLoad() {
       ......write logic to call the PHP file here...
   }

   var callCount = 0;

   function callLoop() {
       callLoad();
       callCount ++;

       if(callCount == 5) return; // Stop the loop

       setTimeout(function() {
           callLoop();
      }, 5000); // Wait for 5 second to make the call again

   }

   window.onload = callLoop; // Start the loop after the page has finished loading
</script>


问:
Iterate through populated rows, Match based on criteria, add value to specific cell in another sheet in Excel using VBA
I am trying to select a value in column hours in tab Time and put it in the appropriate column in tab Month. I would like to iterate through every row in sheet Time and add all of the Data to tab Month.

For every line in Tab TIME add the Hours to the appropriate engagement in Tab Month based on Engagement Number, Engagement Phase, Staff Level. I do this manually every month. I create a copy of last months tab and add on to that each month. Most columns have cells with something like this in them: =1+3+6+4+14+5+2+5 which are the hours that have been worked on that engagement. For cells with something in them i would just like to add on to what is there. For cells with nothing in them i would like to make the new value: = 1 if the value was 1. I want to automate this as it takes up a few days every first of the month, This one just so happens to be on a weekend so guess what I'll be doing. :)

This is where I am at.

```<code>Sub Recon()

'Macro to add time to reconciliation report

'Declare variables

Dim Last_Row_TIME As Double
Dim Last_Row_MONTH As Double
Dim wb As Workbook
Dim ws As Worksheet
Dim rw As Range
Dim wstime As

Set wb = ActiveWorkbook
Set wstime = Sheets("TIME")
Set wsmonth = Sheets("MONTH")

wstime.Select

'Find the last non-blank cell in column A(1)
Last_Row_wstime = wstime.Cells(Rows.Count, 1).End(xlUp).Row

'Find the first blank cell in column A
First_Empty_Row_wstime = Last_Row_wstime + 1

I_Col = 1

For i = 1 To Last_Row_wstime

For Each rw In wstime.Rows

If wstime.Cells(rw.Row,1).Value = wsmonth.Cells(rw.Row, 3).Value
And

End Sub
</code>```

I am stuck at the if statement and not sure how to make this work.

```<code>IF
TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = PARTNER or MANAGING DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Partner/MD (Column I)

'If blank then "=TIME.Hours) elseif add to the previous value "previous     addition statement +(hours)"

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SR. MANAGER/DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Director (Column J)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = MANAGER

THEN

Add Value TIME.Hours (Column Y) to  Month.Manager (Column K)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SENIOR ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Sr.Assoc (Column L)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Associate (Column M)

ELSEIF

'Create a new line after the biggest primary key, located in Month.Primary Key (Column A)

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Eng. Description (Column B) = Month.Project Name (Column D)

End If
</code>```

答:
This is how I read your problem.

You want to go through each row in the TIME worksheet.

For each row, you want to find a two column matching row in the MONTH worksheet. The first match compares the Eng. No. (TIME!A:A) with the Eng. no in MONTH!B:B and a secondary match on the Phase (Column C) with MONTH!C:C.

If a two column MATCH is found, append the rudimentary SUM formula (e.g. =n+=n+=n+=n+=n...) in the MONTH worksheet with the current value from TIME!Y:Y. This would go into one of the columns in MONTH!I:M depending on the salary position in TIME!M:M.

If no match is found, create a new entry in MONTH and fill in the time to the appropriate column in the new entry.

In a standard code module sheet:

```<code>Option Explicit

Sub Recon()
    Dim timeRow As Long, monthCol As Long, monthRow As Variant
    Dim wsTime As Worksheet, wsMonth As Worksheet, wb As Workbook
    Dim rw As Range

    Set wb = ActiveWorkbook
    Set wsTime = wb.Worksheets("TIME")
    Set wsMonth = wb.Worksheets("MONTH")

    With wsTime
        For timeRow = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
            'preload the next available row in MONTH
            With wsMonth
                monthRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
            End With
            'evaluate for a two-column MATCH
            Debug.Print "=MATCH(" & wsTime.Cells(timeRow, "A").Address(external:=True) & Chr(38) & wsTime.Cells(timeRow, "C").Address(external:=True) & ", " & wsMonth.Columns("B").Resize(monthRow, 1).Address(external:=True) & Chr(38) & wsMonth.Columns("C").Resize(monthRow, 1).Address(external:=True) & ", 0)"
            monthRow = Application.Evaluate("MATCH(" & wsTime.Cells(timeRow, "A").Address(external:=True) & Chr(38) & wsTime.Cells(timeRow, "C").Address(external:=True) & ", " & wsMonth.Columns("B").Resize(monthRow, 1).Address(external:=True) & Chr(38) & wsMonth.Columns("C").Resize(monthRow, 1).Address(external:=True) & ", 0)")
            'if there is no two-column matching record, create one
            If IsError(monthRow) Then
                With wsMonth
                    monthRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
                    .Cells(monthRow, "A") = Application.Max(.Columns("A")) + 1   'you need something in MONTH!A:A for this to work
                    .Cells(monthRow, "B") = wsTime.Cells(timeRow, "A").Value2
                    .Cells(monthRow, "C") = wsTime.Cells(timeRow, "C").Value2
                    .Cells(monthRow, "D") = wsTime.Cells(timeRow, "B").Value2
                End With
            End If

            'at this point we know we have a matching record in the MONTH worksheet
            'choose the MONTH column to add TIME to according to the position in TIME!M:M
            monthCol = 0
            Select Case UCase(.Cells(timeRow, "M").Value2)
                Case "PARTNER", "MANAGING DIRECTOR"
                    monthCol = 9    'MONTH!I:I
                Case "SR. MANAGER/DIRECTOR"
                    monthCol = 10   'MONTH!J:J
                Case "MANAGER"
                    monthCol = 11   'MONTH!K:K
                Case "SENIOR ASSOCIATE"
                    monthCol = 12   'MONTH!L:L
                Case "ASSOCIATE"
                    monthCol = 13   'MONTH!M:M
                Case Else
                    'do nothng - no match on staff level
            End Select

            'if monthCol is not zero then we matched the staff level
            If CBool(monthCol) Then
                With wsMonth
                    'is there already a formula in the cell?
                    If .Cells(monthRow, monthCol).HasFormula Then
                        .Cells(monthRow, monthCol).Formula = _
                            .Cells(monthRow, monthCol).Formula & Chr(43) & wsTime.Cells(timeRow, "Y").Value2
                    Else
                        .Cells(monthRow, monthCol).Formula = _
                            Chr(61) & wsTime.Cells(timeRow, "Y").Value2
                    End If
                End With
            End If

        Next timeRow
    End With

End Sub
</code>```

I've added comments throughout the code.

Body:
I am trying to select a value in column hours in tab Time and put it in the appropriate column in tab Month. I would like to iterate through every row in sheet Time and add all of the Data to tab Month.

For every line in Tab TIME add the Hours to the appropriate engagement in Tab Month based on Engagement Number, Engagement Phase, Staff Level. I do this manually every month. I create a copy of last months tab and add on to that each month. Most columns have cells with something like this in them: =1+3+6+4+14+5+2+5 which are the hours that have been worked on that engagement. For cells with something in them i would just like to add on to what is there. For cells with nothing in them i would like to make the new value: = 1 if the value was 1. I want to automate this as it takes up a few days every first of the month, This one just so happens to be on a weekend so guess what I'll be doing. :)

This is where I am at.

Sub Recon()

'Macro to add time to reconciliation report

'Declare variables

Dim Last_Row_TIME As Double
Dim Last_Row_MONTH As Double
Dim wb As Workbook
Dim ws As Worksheet
Dim rw As Range
Dim wstime As

Set wb = ActiveWorkbook
Set wstime = Sheets("TIME")
Set wsmonth = Sheets("MONTH")

wstime.Select

'Find the last non-blank cell in column A(1)
Last_Row_wstime = wstime.Cells(Rows.Count, 1).End(xlUp).Row

'Find the first blank cell in column A
First_Empty_Row_wstime = Last_Row_wstime + 1

I_Col = 1

For i = 1 To Last_Row_wstime

For Each rw In wstime.Rows

If wstime.Cells(rw.Row,1).Value = wsmonth.Cells(rw.Row, 3).Value
And

End Sub

I am stuck at the if statement and not sure how to make this work.

IF
TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = PARTNER or MANAGING DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Partner/MD (Column I)

'If blank then "=TIME.Hours) elseif add to the previous value "previous     addition statement +(hours)"

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SR. MANAGER/DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Director (Column J)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = MANAGER

THEN

Add Value TIME.Hours (Column Y) to  Month.Manager (Column K)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SENIOR ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Sr.Assoc (Column L)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Associate (Column M)

ELSEIF

'Create a new line after the biggest primary key, located in Month.Primary Key (Column A)

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Eng. Description (Column B) = Month.Project Name (Column D)

End If

Body:
This is how I read your problem.

You want to go through each row in the TIME worksheet.

For each row, you want to find a two column matching row in the MONTH worksheet. The first match compares the Eng. No. (TIME!A:A) with the Eng. no in MONTH!B:B and a secondary match on the Phase (Column C) with MONTH!C:C.

If a two column MATCH is found, append the rudimentary SUM formula (e.g. =n+=n+=n+=n+=n...) in the MONTH worksheet with the current value from TIME!Y:Y. This would go into one of the columns in MONTH!I:M depending on the salary position in TIME!M:M.

If no match is found, create a new entry in MONTH and fill in the time to the appropriate column in the new entry.

In a standard code module sheet:

Option Explicit

Sub Recon()
    Dim timeRow As Long, monthCol As Long, monthRow As Variant
    Dim wsTime As Worksheet, wsMonth As Worksheet, wb As Workbook
    Dim rw As Range

    Set wb = ActiveWorkbook
    Set wsTime = wb.Worksheets("TIME")
    Set wsMonth = wb.Worksheets("MONTH")

    With wsTime
        For timeRow = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
            'preload the next available row in MONTH
            With wsMonth
                monthRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
            End With
            'evaluate for a two-column MATCH
            Debug.Print "=MATCH(" & wsTime.Cells(timeRow, "A").Address(external:=True) & Chr(38) & wsTime.Cells(timeRow, "C").Address(external:=True) & ", " & wsMonth.Columns("B").Resize(monthRow, 1).Address(external:=True) & Chr(38) & wsMonth.Columns("C").Resize(monthRow, 1).Address(external:=True) & ", 0)"
            monthRow = Application.Evaluate("MATCH(" & wsTime.Cells(timeRow, "A").Address(external:=True) & Chr(38) & wsTime.Cells(timeRow, "C").Address(external:=True) & ", " & wsMonth.Columns("B").Resize(monthRow, 1).Address(external:=True) & Chr(38) & wsMonth.Columns("C").Resize(monthRow, 1).Address(external:=True) & ", 0)")
            'if there is no two-column matching record, create one
            If IsError(monthRow) Then
                With wsMonth
                    monthRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
                    .Cells(monthRow, "A") = Application.Max(.Columns("A")) + 1   'you need something in MONTH!A:A for this to work
                    .Cells(monthRow, "B") = wsTime.Cells(timeRow, "A").Value2
                    .Cells(monthRow, "C") = wsTime.Cells(timeRow, "C").Value2
                    .Cells(monthRow, "D") = wsTime.Cells(timeRow, "B").Value2
                End With
            End If

            'at this point we know we have a matching record in the MONTH worksheet
            'choose the MONTH column to add TIME to according to the position in TIME!M:M
            monthCol = 0
            Select Case UCase(.Cells(timeRow, "M").Value2)
                Case "PARTNER", "MANAGING DIRECTOR"
                    monthCol = 9    'MONTH!I:I
                Case "SR. MANAGER/DIRECTOR"
                    monthCol = 10   'MONTH!J:J
                Case "MANAGER"
                    monthCol = 11   'MONTH!K:K
                Case "SENIOR ASSOCIATE"
                    monthCol = 12   'MONTH!L:L
                Case "ASSOCIATE"
                    monthCol = 13   'MONTH!M:M
                Case Else
                    'do nothng - no match on staff level
            End Select

            'if monthCol is not zero then we matched the staff level
            If CBool(monthCol) Then
                With wsMonth
                    'is there already a formula in the cell?
                    If .Cells(monthRow, monthCol).HasFormula Then
                        .Cells(monthRow, monthCol).Formula = _
                            .Cells(monthRow, monthCol).Formula & Chr(43) & wsTime.Cells(timeRow, "Y").Value2
                    Else
                        .Cells(monthRow, monthCol).Formula = _
                            Chr(61) & wsTime.Cells(timeRow, "Y").Value2
                    End If
                End With
            End If

        Next timeRow
    End With

End Sub

I've added comments throughout the code.


问:
nodejs route.get to SEND a post request
The get to this route works fine.

But how do I take my route.get() and make it do a post?
If the post is written in jquery, or express, or something else I don't care.  Below I just used the jquery as an example.

```<code>router.get('/', function (req, res, next) {
    var url = 'blabla'
    $.post('anotherBlaBla'
        , { app: url }
    );
});
</code>```

答:
```<code>const request = require('request');

var url = 'blabla';

request.post(
    url
    , { json: { api: url } }
    , function (err, res, bdy) {
        if (!err && res.statusCode == 200)
            console.log(bdy)
    }
);
</code>```

Title: nodejs route.get to SEND a post request

Body:
The get to this route works fine.

But how do I take my route.get() and make it do a post?
If the post is written in jquery, or express, or something else I don't care.  Below I just used the jquery as an example.

router.get('/', function (req, res, next) {
    var url = 'blabla'
    $.post('anotherBlaBla'
        , { app: url }
    );
});


答:
The top command has no option to output as XML, so you'd have a lot of parsing to do (and such a request would be too broad for this site as such).

However, sysstat comes with sadf which has a -x option that might meet your needs.  There are DTD and XSD files available on their download page.

Title: How to save the output of top command in XML format?

Body:
top -o %MEM -b > file.txt

The file.txt is like:

top - 15:49:36 up 32 min,  2 users,  load average: 1.56, 1.40, 1.01
Tasks:  83 total,   2 running,  79 sleeping,   2 stopped,   0 zombie
%Cpu(s): 24.4 us,  8.1 sy,  0.0 ni, 55.0 id,  0.0 wa,  0.0 hi, 12.5 si,  0.0 st
KiB Mem:    195252 total,   191568 used,     3684 free,     3200 buffers
KiB Swap:   901116 total,       44 used,   901072 free.    66940 cached Mem

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
  485 root      20   0   68160  61420   4552 R 58.7 31.5   5:06.10 python3
  712 www-data  20   0  230940   4436   2044 S 26.1  2.3   3:54.04 apache2
  819 root      20   0    8488   4400   3856 S  6.5  2.3   1:06.85 tcpdump
  713 www-data  20   0  230780   4344   2044 S 13.0  2.2   2:34.97 apache2
  868 root      20   0    6352   3976   2720 S  0.0  2.0   0:00.07 bash
  785 root      20   0    6340   3876   2636 S  0.0  2.0   0:00.06 bash
  707 root      20   0    6056   3704   2580 S  0.0  1.9   0:00.59 apache2
  137 root      20   0    8284   3256   2996 S  0.0  1.7   0:00.34 systemd-journal
    1 root      20   0    5476   3112   2072 S  0.0  1.6   0:01.04 systemd
  456 ntp       20   0    5820   3012   2576 S  0.0  1.5   0:00.71 ntpd
  865 root      20   0    4008   2792   2360 S  0.0  1.4   0:00.04 login
  938 nobody    20   0    5244   2756   2404 S  0.0  1.4   0:00.04 vsftpd
  941 nobody    20   0    5244   2756   2404 S  0.0  1.4   0:00.03 vsftpd
  457 root      20   0   31220   2740   2080 S  0.0  1.4   0:00.01 rsyslogd
  484 root      20   0    4008   2692   2268 S  0.0  1.4   0:00.05 login
  944 root      20   0    5076   2620   2352 R  0.0  1.3   0:00.00 top
  903 root      20   0    5080   2580   2236 T  0.0  1.3   0:00.00 top
  908 root      20   0    5052   2560   2288 T  0.0  1.3   0:00.08 top
  425 root      20   0    5416   2420   2100 S  0.0  1.2   0:00.00 cron
  406 root      20   0    5012   2348   2120 S  0.0  1.2   0:00.00 cron
  148 root      20   0   12272   2320   1856 S  0.0  1.2   0:00.09 systemd-udevd
  414 message+  20   0    5244   2268   1960 S  0.0  1.2   0:00.00 dbus-daemon
  390 statd     20   0    4576   2264   1764 S  0.0  1.2   0:00.00 rpc.statd

I should save the information in XML format instead of txt file! How to do it?

I would like to read file.txt and convert it to XML.

I think I could use Python but I dont know how:

#coding:utf-8

from xml.dom.minidom import Document

doc = Document()
root = doc.createElement('InfoMemoria')


问:
Cant start new activity. It keeps crashing
When pressing the button, new activity should open but app instantly crashes. I have searched for answer and making a few adjustments to my code and only thing i dont know how to do is Manifest, can u help me with that?

```<code>  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="Starting.Programm"
  android:versionCode="1"
  android:versionName="1.0">
<application android:label="@string/app_name"
android:icon="@drawable/ic_launcher">
    <activity android:name="MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="InformationActivity"
              android:label="@string/app_name"
              >
        </activity>
</application>
</code>```

MainActivity:

```<code>package Starting.Programm;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends InformationActivity
{

/** Called when the activity is first created. */
@Override
 protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}
 public void startJourney(View view) {
     Intent intent = new Intent(this, InformationActivity.class);
     startActivity(intent);

}
}
</code>```

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<Button android:id="@+id/button_StartApp"
    android:layout_width="100dp"
    android:layout_height="60dp"
    android:text="@string/button_StartApp"
    android:layout_gravity="center"
    android:layout_marginTop="70dp"
    android:layout_marginLeft="115dp"
    android:onClick="startJourney"
/>

</LinearLayout>
</code>```

And next activity which should be opening

```<code>package Starting.Programm;

import android.app.Activity;
import android.os.Bundle;

class InformationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.information);

}

}
</code>```

答:
Add dot to end of pacakager name
    package="Starting.Programm."

Body:
When pressing the button, new activity should open but app instantly crashes. I have searched for answer and making a few adjustments to my code and only thing i dont know how to do is Manifest, can u help me with that?

  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="Starting.Programm"
  android:versionCode="1"
  android:versionName="1.0">
<application android:label="@string/app_name"
android:icon="@drawable/ic_launcher">
    <activity android:name="MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="InformationActivity"
              android:label="@string/app_name"
              >
        </activity>
</application>

MainActivity:

package Starting.Programm;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends InformationActivity
{

/** Called when the activity is first created. */
@Override
 protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}
 public void startJourney(View view) {
     Intent intent = new Intent(this, InformationActivity.class);
     startActivity(intent);

}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<Button android:id="@+id/button_StartApp"
    android:layout_width="100dp"
    android:layout_height="60dp"
    android:text="@string/button_StartApp"
    android:layout_gravity="center"
    android:layout_marginTop="70dp"
    android:layout_marginLeft="115dp"
    android:onClick="startJourney"
/>

</LinearLayout>

And next activity which should be opening

package Starting.Programm;

import android.app.Activity;
import android.os.Bundle;

class InformationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.information);

}

}


问:
C++ function missing after change in main
Just for clarification, currently using Repl.it. If this problem is due to Repl.it, that'll be it.

I am trying to make multiple state machines that influence each other through different states (Happy, Sad, or Mad). Each machine can talk: say what state they're in; or interact with a different machine, thus changing one of the machine's states;

The problem I have with my code is the everyone function, allowing every state machine in an array to say their states. Whenever something is changed in the main function, the everyone function just doesn't run anymore. I'm sorry that this post is really long, mostly due to any omissions causes the function to break.

This is my code:

```<code>using namespace std;

enum Mood {Happy, Sad, Mad, Default};

class StateMac {
  Mood state;      //The machine's current state

  /* Other methods no shown */

  //Returns a string relative to their current state
  string talk() {
    switch(state) {
      case Happy : return "I'm happy!";
      case Sad : return "I'm sad...";
      case Mad : return "I'm Mad!!!";
      case Default : return "...";
    }
  }

  //Compares the states between two machines
  bool compare(StateMac aStateMachine) {
    if (state == aStateMachine.getState()) {
      return true;
    }
    return false;
  }
};

//Gets size of a state machine array by comparing each to a default machine
int getSMarSize(StateMac SMar[]) {
  int counter = 0;
  for (int i = 0; i < 100; i++) {
    if (SMar[i].compare(StateMac())) {
      break;
    } else {
      counter += 1;
    }
  }
  return counter;
}

//Receives an array of state machines and makes each of them say their states,
void everyone(StateMac SMar[]) {
  for (int i; i < getSMarSize(SMar); i++) {
    cout << "SM" << i << ": " << SMar[i].talk() << endl;
  }
}

int main() {
  //Array with 4 state machines
  StateMac ar[] = {StateMac(Happy), StateMac(Sad), StateMac(Mad), StateMac()};

  //Have everyone say their states
  everyone(ar);

  //Does same as above but line-by-line for each machine
  cout << "SM0: " << ar[0].talk() << endl;
  cout << "SM1: " << ar[1].talk() << endl;
  cout << "SM2: " << ar[2].talk() << endl;

  //Other functions
  string response = ar[0].interact(&ar[2]);
  cout << "SM0 to SM1: " << response << endl;
  cout << "SM1: " << ar[1].talk() << endl;
  response = ar[0].interact(&ar[2]);
  cout << "SM0 to SM2: " << response << endl;
  cout << "SM2: " << ar[2].talk() << endl;
  response = ar[1].interact(&ar[2]);
  cout << "SM0 to SM2: " << response << endl;
  cout << "SM0: " << ar[0].talk() << endl;
  cout << "SM1: " << ar[1].talk() << endl;
  cout << "SM2: " << ar[2].talk() << endl;
}
</code>```

Producing this result:

```<code>SM0: I'm happy!   //From everyone function
SM1: I'm sad...
SM2: I'm Mad!!!
SM0: I'm happy!   //From line-by-line
SM1: I'm sad...
SM2: I'm Mad!!!
SM0 to SM1: There's nothing to be mad about!   //Other functions
SM1: I'm sad...
SM0 to SM2: That guy!!!
SM2: I'm happy!
SM0 to SM2: You look happy, might as well forget about that.
SM0: I'm Mad!!!
SM1: I'm sad...
SM2: I'm happy!
</code>```

Everything looks good in the result as of now. However, if I am to add, change, or delete any line in the main function, all of a sudden, the everyone function doesn't run anymore.

For example, I changed one of the responses in the main function:

```<code>everyone(ar);
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;
string response = "";                       //Changed here
cout << "SM0 to SM1: " << response << endl;
cout << "SM1: " << ar[1].talk() << endl;
response = ar[0].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM2: " << ar[2].talk() << endl;
response = ar[1].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;
</code>```

Creating this result, notice the missing everyone function call:

```<code>SM0: I'm happy!    //Line-by-line
SM1: I'm sad...
SM2: I'm Mad!!!
SM0 to SM1:        //Changed response
SM1: I'm sad...
SM0 to SM2: There's nothing to be mad about!
SM2: I'm happy!
SM0 to SM2: You look happy, might as well forget about that.
SM0: I'm happy!
SM1: I'm sad...
SM2: I'm happy!
</code>```

答:
The problem is in your function

```<code>void everyone(StateMac SMar[]) {
  for (int i; i < getSMarSize(SMar); i++) {
    cout << "SM" << i << ": " << SMar[i].talk() << endl;
  }
}
</code>```

This code does not initialize the variable i, and so it has undefined behavior. Changing this to int i = 0 should solve your problem.

BTW, I am also puzzled by your use of the function int getSMarSize(StateMac SMar[]) to determine the size of the array of state machines. Your strategy seems to be to leave a "blank" state machine at the end of the array and counts the array length by iterating until it finds this blank state machine, much like the terminating character in a C string. Since you cannot automatically enforce that the array should end in StateMac(), unlike C/C++ can do with a C string, this is error-prone. There is no good reason to use this technique for an array in C++ -- you should either pass the length of the array as a parameter to the function, or better yet use the std::vector container.

Body:
Just for clarification, currently using Repl.it. If this problem is due to Repl.it, that'll be it.

I am trying to make multiple state machines that influence each other through different states (Happy, Sad, or Mad). Each machine can talk: say what state they're in; or interact with a different machine, thus changing one of the machine's states;

The problem I have with my code is the everyone function, allowing every state machine in an array to say their states. Whenever something is changed in the main function, the everyone function just doesn't run anymore. I'm sorry that this post is really long, mostly due to any omissions causes the function to break.

This is my code:

using namespace std;

enum Mood {Happy, Sad, Mad, Default};

class StateMac {
  Mood state;      //The machine's current state

  /* Other methods no shown */

  //Returns a string relative to their current state
  string talk() {
    switch(state) {
      case Happy : return "I'm happy!";
      case Sad : return "I'm sad...";
      case Mad : return "I'm Mad!!!";
      case Default : return "...";
    }
  }

  //Compares the states between two machines
  bool compare(StateMac aStateMachine) {
    if (state == aStateMachine.getState()) {
      return true;
    }
    return false;
  }
};

//Gets size of a state machine array by comparing each to a default machine
int getSMarSize(StateMac SMar[]) {
  int counter = 0;
  for (int i = 0; i < 100; i++) {
    if (SMar[i].compare(StateMac())) {
      break;
    } else {
      counter += 1;
    }
  }
  return counter;
}

//Receives an array of state machines and makes each of them say their states,
void everyone(StateMac SMar[]) {
  for (int i; i < getSMarSize(SMar); i++) {
    cout << "SM" << i << ": " << SMar[i].talk() << endl;
  }
}

int main() {
  //Array with 4 state machines
  StateMac ar[] = {StateMac(Happy), StateMac(Sad), StateMac(Mad), StateMac()};

  //Have everyone say their states
  everyone(ar);

  //Does same as above but line-by-line for each machine
  cout << "SM0: " << ar[0].talk() << endl;
  cout << "SM1: " << ar[1].talk() << endl;
  cout << "SM2: " << ar[2].talk() << endl;

  //Other functions
  string response = ar[0].interact(&ar[2]);
  cout << "SM0 to SM1: " << response << endl;
  cout << "SM1: " << ar[1].talk() << endl;
  response = ar[0].interact(&ar[2]);
  cout << "SM0 to SM2: " << response << endl;
  cout << "SM2: " << ar[2].talk() << endl;
  response = ar[1].interact(&ar[2]);
  cout << "SM0 to SM2: " << response << endl;
  cout << "SM0: " << ar[0].talk() << endl;
  cout << "SM1: " << ar[1].talk() << endl;
  cout << "SM2: " << ar[2].talk() << endl;
}

Producing this result:

SM0: I'm happy!   //From everyone function
SM1: I'm sad...
SM2: I'm Mad!!!
SM0: I'm happy!   //From line-by-line
SM1: I'm sad...
SM2: I'm Mad!!!
SM0 to SM1: There's nothing to be mad about!   //Other functions
SM1: I'm sad...
SM0 to SM2: That guy!!!
SM2: I'm happy!
SM0 to SM2: You look happy, might as well forget about that.
SM0: I'm Mad!!!
SM1: I'm sad...
SM2: I'm happy!

Everything looks good in the result as of now. However, if I am to add, change, or delete any line in the main function, all of a sudden, the everyone function doesn't run anymore.

For example, I changed one of the responses in the main function:

everyone(ar);
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;
string response = "";                       //Changed here
cout << "SM0 to SM1: " << response << endl;
cout << "SM1: " << ar[1].talk() << endl;
response = ar[0].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM2: " << ar[2].talk() << endl;
response = ar[1].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;

Creating this result, notice the missing everyone function call:

SM0: I'm happy!    //Line-by-line
SM1: I'm sad...
SM2: I'm Mad!!!
SM0 to SM1:        //Changed response
SM1: I'm sad...
SM0 to SM2: There's nothing to be mad about!
SM2: I'm happy!
SM0 to SM2: You look happy, might as well forget about that.
SM0: I'm happy!
SM1: I'm sad...
SM2: I'm happy!

Body:
The problem is in your function

void everyone(StateMac SMar[]) {
  for (int i; i < getSMarSize(SMar); i++) {
    cout << "SM" << i << ": " << SMar[i].talk() << endl;
  }
}

This code does not initialize the variable i, and so it has undefined behavior. Changing this to int i = 0 should solve your problem.

BTW, I am also puzzled by your use of the function int getSMarSize(StateMac SMar[]) to determine the size of the array of state machines. Your strategy seems to be to leave a "blank" state machine at the end of the array and counts the array length by iterating until it finds this blank state machine, much like the terminating character in a C string. Since you cannot automatically enforce that the array should end in StateMac(), unlike C/C++ can do with a C string, this is error-prone. There is no good reason to use this technique for an array in C++ -- you should either pass the length of the array as a parameter to the function, or better yet use the std::vector container.


问:
Bootstrap nav-tabs active color Change to a Different Colour For Each Bootstrap Active Tab
I can successfully change the color of the active tab and non active tabs as a group, but is it possible remain same when i go next tab.

here i tried  : http://jsfiddle.net/pThn6/2031/

When 2nd tab active the 1st color will be red. same way when 3rd active 1st and 2nd color will be red.

is it possible?

Thanks in advance.

答:
Yes, anything is possible lol

try this:

$('ul li a').live('click', function() {
  let numClicked = $(this).parent('li').index();
  $("a").each(function(index) {
    if (index <= numClicked) {
      $(this).addClass('active-red');
    } else {
      $(this).removeClass('active-red');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css');
.container {
  margin-top: 10px;
}

.active-red {
  color: red;
}</code>```

1st

2nd

3rd

4th

...Content...

...Content...

...Content...

```

Body:
Yes, anything is possible lol

try this:

$('ul li a').live('click', function() {
  let numClicked = $(this).parent('li').index();
  $("a").each(function(index) {
    if (index <= numClicked) {
      $(this).addClass('active-red');
    } else {
      $(this).removeClass('active-red');
    }
  });
});

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css');
.container {
  margin-top: 10px;
}

.active-red {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>

<ul class="nav nav-tabs">
  <li><a href="#aaa" data-toggle="tab">1st</a></li>
  <li><a href="#bbb" data-toggle="tab">2nd</a></li>
  <li><a href="#ccc" data-toggle="tab">3rd</a></li>
  <li><a href="#ccc" data-toggle="tab">4th</a></li>
</ul>
<div class="tab-content" id="tabs">
  <div class="tab-pane" id="aaa">...Content...</div>
  <div class="tab-pane" id="bbb">...Content...</div>
  <div class="tab-pane" id="ccc">...Content...</div>
</div>


问:
Kill attached screen session with numbers as session name
I have this session for example 7540.27535      (Detached)
and the 27535 is the session name, so it's not the id but the session name.

What I want is to kill the sessions with the name 27535, How can I do that ?

I have multiple sessions with the same name but I also have another ones and I don't want to kill them all with killall screen.
The command I am using screen -S 27535 -X quit and the answer I get from the server is

```<code>No screen session found.
</code>```

答:
I found the answer.</p>

```<code>screen -ls | grep 27535  | cut -d. -f1 | awk '{print $1}' | xargs kill
</code>```

Body:
I have this session for example 7540.27535      (Detached)
and the 27535 is the session name, so it's not the id but the session name.

What I want is to kill the sessions with the name 27535, How can I do that ?

I have multiple sessions with the same name but I also have another ones and I don't want to kill them all with killall screen.
The command I am using screen -S 27535 -X quit and the answer I get from the server is

No screen session found.

Body:
I found the answer.

screen -ls | grep 27535  | cut -d. -f1 | awk '{print $1}' | xargs kill


问:
Notifications with AKKA and OSGi
I've a OSGi based web application. The next feature I'd like to add is notifications. A simple box that appears in the browser. I've looked into this and it seems a combination of Akka and Websockets is the best way to go. Now, I'm looking for a simple example for my problem. Or is there another - easier - way to go? </p>

答:
You can find an example Server Sent Events example in OSGi enRoute EASSE example. This example is based on Server Sent Events.

The application sends an event to OSGi Event Admin the Server Sent Event Bundle contains a servlet that handles the requests from Javascript. It dispatches matching Event Admin events to any Javascript requests. The Javascript code is in the web folder.

You should be able to checkout the workspace and run it all in Bndtools. If you're unfamiliar with OSGi enRoute, follow the Quick Start Tutorial

Title: Notifications with AKKA and OSGi


问:
Distinct values in Android ExpandableListView
I'm having trouble with an ExpandableListView. What I want is for each group to be from column "bond", which is non-unique, but I want the groups to be unique (i.e. each value of "bond" should only have one group). Each value in the group has data in other columns which should be displayed. The problem is that it seems I can either use the SQL DISTINCT operator with one column (and then getChildrenCursor() throws an IllegalStateException), or not use the DISTINCT operator and have each group duplicated.

Can anyone suggest a fix for this?

```<code>public void onCreate(Bundle saved) {

    super.onCreate(saved);

    DatabaseHelper dh = new DatabaseHelper(this);
    dh.openDataBase();
    db = dh.getReadableDatabase();

    String query = "SELECT DISTINCT bond FROM spectro";

    Cursor c = db.rawQuery(query, null); //throws exception when group opened
    //Cursor c = db.query("spectro", new String[] { "_id", "name", "bond", ir },
        //null, null, null, null, null) - gives duplicate groups

    ExpandableListAdapter a = new IRCursorAdapter (this,
            c, android.R.layout.simple_expandable_list_item_1, new String[] { "bond" },
            new int[] { android.R.id.text1 }, R.layout.row_doubleend,
            new String[] { "name", "ir" }, new int[] { R.id.double_item1, R.id.double_item2 });

    this.setListAdapter(a);

}

protected class IRCursorAdapter extends SimpleCursorTreeAdapter {

    public IRCursorAdapter(Context context, Cursor cursor, int groupLayout,
            String[] groupFrom, int[] groupTo, int childLayout,
            String[] childFrom, int[] childTo) {
        super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom,
                childTo);
    }

    @Override
    protected Cursor getChildrenCursor(Cursor groupCursor) {

        Cursor c = db.query("spectro", new String[] {"_id", "name", "bond", "ir"},
                "bond=?", new String[] { groupCursor.getString(0) }, null, null, null);

        startManagingCursor(c);
        return c;
    }

};
</code>```

here's what my table looks like- the bond is what I want to be unique:

_id | name | bond | ir

1 | name 1 | bond 1 | ir 1

2 | name 2 | bond 1 | ir 2

3 | name 3 | bond 2 | ir 3

4 | name 4 | bond 3 | ir 4

sorry if this isn't particularly clear, but thanks for your help!

答:
I think you are mis-using the distinct operator.  IT will return only Bond1, Bond2, Bond3 and that's it.  You need to create a compound join statement to produce the correct cursor. What you have there will always throw an error because you haven't specified children correctly.  Secondly, I would use the query (instead of raw query) and specify parameters there.

E.g.  db.query(true, "spectro", new String[]{"bond"}, null,null,...)

You will also need to make sure you have your Group From -->To parameters and Children From --> to parameters correct!

ContentLicense: CC BY-SA 2.5

Body:
I'm having trouble with an ExpandableListView. What I want is for each group to be from column "bond", which is non-unique, but I want the groups to be unique (i.e. each value of "bond" should only have one group). Each value in the group has data in other columns which should be displayed. The problem is that it seems I can either use the SQL DISTINCT operator with one column (and then getChildrenCursor() throws an IllegalStateException), or not use the DISTINCT operator and have each group duplicated.

Can anyone suggest a fix for this?

public void onCreate(Bundle saved) {

    super.onCreate(saved);

    DatabaseHelper dh = new DatabaseHelper(this);
    dh.openDataBase();
    db = dh.getReadableDatabase();

    String query = "SELECT DISTINCT bond FROM spectro";

    Cursor c = db.rawQuery(query, null); //throws exception when group opened
    //Cursor c = db.query("spectro", new String[] { "_id", "name", "bond", ir },
        //null, null, null, null, null) - gives duplicate groups

    ExpandableListAdapter a = new IRCursorAdapter (this,
            c, android.R.layout.simple_expandable_list_item_1, new String[] { "bond" },
            new int[] { android.R.id.text1 }, R.layout.row_doubleend,
            new String[] { "name", "ir" }, new int[] { R.id.double_item1, R.id.double_item2 });

    this.setListAdapter(a);

}

protected class IRCursorAdapter extends SimpleCursorTreeAdapter {

    public IRCursorAdapter(Context context, Cursor cursor, int groupLayout,
            String[] groupFrom, int[] groupTo, int childLayout,
            String[] childFrom, int[] childTo) {
        super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom,
                childTo);
    }

    @Override
    protected Cursor getChildrenCursor(Cursor groupCursor) {

        Cursor c = db.query("spectro", new String[] {"_id", "name", "bond", "ir"},
                "bond=?", new String[] { groupCursor.getString(0) }, null, null, null);

        startManagingCursor(c);
        return c;
    }

};

here's what my table looks like- the bond is what I want to be unique:

_id | name | bond | ir

1 | name 1 | bond 1 | ir 1

2 | name 2 | bond 1 | ir 2

3 | name 3 | bond 2 | ir 3

4 | name 4 | bond 3 | ir 4

sorry if this isn't particularly clear, but thanks for your help!


问:
how to understand postgres EXPLAIN output
```<code>EXPLAIN SELECT a.name, m.name FROM Casting c JOIN Movie m ON c.m_id = m.m_id JOIN Actor a ON a.a_id = c.a_id AND c.a_id < 50;
</code>```

Output

```<code>                                                                  QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=26.20..18354.49 rows=1090 width=27) (actual time=0.240..5.603 rows=1011 loops=1)
   ->  Nested Loop  (cost=25.78..12465.01 rows=1090 width=15) (actual time=0.236..4.046 rows=1011 loops=1)
         ->  Bitmap Heap Scan on casting c  (cost=25.35..3660.19 rows=1151 width=8) (actual time=0.229..1.059 rows=1011 loops=1)
               Recheck Cond: (a_id < 50)
               Heap Blocks: exact=989
               ->  Bitmap Index Scan on casting_a_id_index  (cost=0.00..25.06 rows=1151 width=0) (actual time=0.114..0.114 rows=1011 loops=1)
                     Index Cond: (a_id < 50)
         ->  Index Scan using movie_pkey on movie m  (cost=0.42..7.64 rows=1 width=15) (actual time=0.003..0.003 rows=1 loops=1011)
               Index Cond: (m_id = c.m_id)
   ->  Index Scan using actor_pkey on actor a  (cost=0.42..5.39 rows=1 width=20) (actual time=0.001..0.001 rows=1 loops=1011)
         Index Cond: (a_id = c.a_id)
 Planning time: 0.334 ms
 Execution time: 5.672 ms
(13 rows)
</code>```

I am trying to understand how query planner works? I am able to understand the process it choose, but I am not getting why ?
Can someone explain query optimizer choices (choice of query processing algorithms, join order) in these queries based on parameters like query selectivity and cost models or anything that effects choice?
Also why there is use of Recheck Cond, after index scan ?

答:
There are two reasons why there has to be a Bitmap Heap Scan:

PostgreSQL has to check whether the rows found are visible for the current transaction or not. Remember that PostgreSQL keeps old row versions in the table until VACUUM removes them. This visibility information is not stored in the index.

If work_mem is not large enough to contain a bitmap with one bit per table row, PostgreSQL uses one bit per table page, which loses some information. The PostgreSQL needs to check the lossy blocks to see which of the rows in the block really satisfy the condition.

You can see this when you use EXPLAIN (ANALYZE, BUFFERS), then PostgreSQL will show if there were lossy matches, see this example on rextester:

```<code>->  Bitmap Heap Scan on t  (cost=177.14..4719.43 rows=9383 width=0)
                           (actual time=2.130..144.729 rows=10001 loops=1)
      Recheck Cond: (val = 10)
      Rows Removed by Index Recheck: 738586
      Heap Blocks: exact=646 lossy=3305
      Buffers: shared hit=1891 read=2090
      ->  Bitmap Index Scan on t_val_idx  (cost=0.00..174.80 rows=9383 width=0)
                                          (actual time=1.978..1.978 rows=10001 loops=1)
            Index Cond: (val = 10)
            Buffers: shared read=30
</code>```

I cannot explain the whole of the PostgreSQL optimizer in this answer, but what it does is to try all possible ways to compute the result, estimate how much each one will cost and choose the cheapest plan.

To estimate how big the result set will be, it uses the object definitions and the table statistics, which contain detailed data about how the column values are distributed.

It then calculates how many disk blocks it will have to read sequentially and by random access (I/O cost), and how many tables and index rows and function calls it will have to process (CPU cost) to come up with a grand total. The weights for each of these components in the total can be configured.

Usually the best plan is one that reduces the number of result rows as quickly as possible by applying the most selective condition first. In your case this seems to be casting.a_id < 50.

Nested loop joins are often preferred if the number of rows in the outer (upper in EXPLAIN output) table is small.

Body:
EXPLAIN SELECT a.name, m.name FROM Casting c JOIN Movie m ON c.m_id = m.m_id JOIN Actor a ON a.a_id = c.a_id AND c.a_id < 50;

Output

                                                                  QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=26.20..18354.49 rows=1090 width=27) (actual time=0.240..5.603 rows=1011 loops=1)
   ->  Nested Loop  (cost=25.78..12465.01 rows=1090 width=15) (actual time=0.236..4.046 rows=1011 loops=1)
         ->  Bitmap Heap Scan on casting c  (cost=25.35..3660.19 rows=1151 width=8) (actual time=0.229..1.059 rows=1011 loops=1)
               Recheck Cond: (a_id < 50)
               Heap Blocks: exact=989
               ->  Bitmap Index Scan on casting_a_id_index  (cost=0.00..25.06 rows=1151 width=0) (actual time=0.114..0.114 rows=1011 loops=1)
                     Index Cond: (a_id < 50)
         ->  Index Scan using movie_pkey on movie m  (cost=0.42..7.64 rows=1 width=15) (actual time=0.003..0.003 rows=1 loops=1011)
               Index Cond: (m_id = c.m_id)
   ->  Index Scan using actor_pkey on actor a  (cost=0.42..5.39 rows=1 width=20) (actual time=0.001..0.001 rows=1 loops=1011)
         Index Cond: (a_id = c.a_id)
 Planning time: 0.334 ms
 Execution time: 5.672 ms
(13 rows)

I am trying to understand how query planner works? I am able to understand the process it choose, but I am not getting why ?
Can someone explain query optimizer choices (choice of query processing algorithms, join order) in these queries based on parameters like query selectivity and cost models or anything that effects choice?
Also why there is use of Recheck Cond, after index scan ?

Body:
There are two reasons why there has to be a Bitmap Heap Scan:

PostgreSQL has to check whether the rows found are visible for the current transaction or not. Remember that PostgreSQL keeps old row versions in the table until VACUUM removes them. This visibility information is not stored in the index.

If work_mem is not large enough to contain a bitmap with one bit per table row, PostgreSQL uses one bit per table page, which loses some information. The PostgreSQL needs to check the lossy blocks to see which of the rows in the block really satisfy the condition.

You can see this when you use EXPLAIN (ANALYZE, BUFFERS), then PostgreSQL will show if there were lossy matches, see this example on rextester:

->  Bitmap Heap Scan on t  (cost=177.14..4719.43 rows=9383 width=0)
                           (actual time=2.130..144.729 rows=10001 loops=1)
      Recheck Cond: (val = 10)
      Rows Removed by Index Recheck: 738586
      Heap Blocks: exact=646 lossy=3305
      Buffers: shared hit=1891 read=2090
      ->  Bitmap Index Scan on t_val_idx  (cost=0.00..174.80 rows=9383 width=0)
                                          (actual time=1.978..1.978 rows=10001 loops=1)
            Index Cond: (val = 10)
            Buffers: shared read=30

I cannot explain the whole of the PostgreSQL optimizer in this answer, but what it does is to try all possible ways to compute the result, estimate how much each one will cost and choose the cheapest plan.

To estimate how big the result set will be, it uses the object definitions and the table statistics, which contain detailed data about how the column values are distributed.

It then calculates how many disk blocks it will have to read sequentially and by random access (I/O cost), and how many tables and index rows and function calls it will have to process (CPU cost) to come up with a grand total. The weights for each of these components in the total can be configured.

Usually the best plan is one that reduces the number of result rows as quickly as possible by applying the most selective condition first. In your case this seems to be casting.a_id < 50.

Nested loop joins are often preferred if the number of rows in the outer (upper in EXPLAIN output) table is small.


问:
Solving linear regression equation for a sparse matrix
I'd like to solve a multivariate linear regression equation for vector X with m elements while I have n observations, Y. If I assume the measurements have Gaussian random errors. How can I solve this problem using python? My problem looks like this:

A simple example of W when m=5, is given as follows:

P.S. I would like to consider the effect of errors and precisely I want to measure the standard deviation of errors.

答:
You can do it like this

```<code>def myreg(W, Y):
    from numpy.linalg import pinv
    m, n = Y.shape
    k = W.shape[1]
    X = pinv(W.T.dot(W)).dot(W.T).dot(Y)
    Y_hat = W.dot(X)
    Residuals = Y_hat - Y
    MSE = np.square(Residuals).sum(axis=0) / (m - 2)
    X_var = (MSE[:, None] * pinv(W.T.dot(W)).flatten()).reshape(n, k, k)
    Tstat = X / np.sqrt(X_var.diagonal(axis1=1, axis2=2)).T
    return X, Tstat
</code>```

demo

```<code>W = np.array([
        [ 1, -1,  0,  0,  1],
        [ 0, -1,  1,  0,  0],
        [ 1,  0,  0,  1,  0],
        [ 0,  1, -1,  0,  1],
        [ 1, -1,  0,  0, -1],
    ])

Y = np.array([2, 4, 1, 5, 3])[:, None]

X, V = myreg(W, Y)
</code>```

Body:
You can do it like this

def myreg(W, Y):
    from numpy.linalg import pinv
    m, n = Y.shape
    k = W.shape[1]
    X = pinv(W.T.dot(W)).dot(W.T).dot(Y)
    Y_hat = W.dot(X)
    Residuals = Y_hat - Y
    MSE = np.square(Residuals).sum(axis=0) / (m - 2)
    X_var = (MSE[:, None] * pinv(W.T.dot(W)).flatten()).reshape(n, k, k)
    Tstat = X / np.sqrt(X_var.diagonal(axis1=1, axis2=2)).T
    return X, Tstat

demo

W = np.array([
        [ 1, -1,  0,  0,  1],
        [ 0, -1,  1,  0,  0],
        [ 1,  0,  0,  1,  0],
        [ 0,  1, -1,  0,  1],
        [ 1, -1,  0,  0, -1],
    ])

Y = np.array([2, 4, 1, 5, 3])[:, None]

X, V = myreg(W, Y)


问:
How to adjust the divs?
I need to move the paragraph div over to the left with it expanding all the way to the image. The top-div should display on two lines and break after the word festival. Both paragraphs should be to the left of the image. How do I get the div's to display correctly?

body {
  width: 8.5in;
}

.container {
  display: flex;
  background: red;
}

.top-div {
  display: table;
  background: rgb(204, 255, 102);
  text-align: center;
  font-size: 1.75em;
  font-weight: bold;
  color: rgb(35, 66, 113);
}

.top-div>p {
  margin: 10px;
}

.paragraph {
  align-self: flex-end;
  background: blue;
}

.flower-img {
  display: table;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="top-div">
    <p lang="zh">Qingming Festival<br>qīng míng jié</p>
  </div>
  <div class="paragraph">
    <p>The Qingming or Ching Ming Festival, also known as Tomb-Sweeping Day in English, is a traditional Chinese festival on the first day of the fifth solar term of the traditional Chinese lunisolar calendar. This makes it the 15th day after the Spring
      Equinox, either 4 or 5 April in a given year. Other common translations include Chinese Memorial Day and Ancestors' Day.</p>
    <p>It is also a time for people to go outside to enjoy the spring such as having a picnic or flying a kite. In 2017 Qingming Festival falls on April 4. The three-day public holiday in China is April 3–5, 2017.</p>
  </div>
  <div>
    <img src="//dummyimage.com/300x450" alt="flower" width="300" class="flower-img">
  </div>
</div></code>```

This what I would like it to look like

答:
Place your paragprah elements in a parent container with class content, then place this container in your div with class container.
Afterwards apply  css styling as follows

body {
  width: 10.5in;
}

.container {
  background: red;
}

.content {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  margin: 0;
}

.top-div {
  background: rgb(204, 255, 102);
  text-align: center;
  font-size: 1.75em;
  font-weight: bold;
  color: rgb(35, 66, 113);
}

.top-div>p {
  margin: 0;
}

.paragraph {
  background: blue;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="content">

    <div class="paragraph">
      <div class="top-div">
        <p lang="zh">Qingming Festival
          <br>qīng míng jié</p>
      </div>
      <p>The Qingming or Ching Ming Festival, also known as Tomb-Sweeping Day in English, is a traditional Chinese festival on the first day of the fifth solar term of the traditional Chinese lunisolar calendar. This makes it the 15th day after the Spring
        Equinox, either 4 or 5 April in a given year. Other common translations include Chinese Memorial Day and Ancestors' Day.</p>
      <p>It is also a time for people to go outside to enjoy the spring such as having a picnic or flying a kite. In 2017 Qingming Festival falls on April 4. The three-day public holiday in China is April 3–5, 2017.</p>
    </div>
    <div>
      <img src="//dummyimage.com/300x450" alt="flower" width="300" class="flower-img">
    </div>
  </div>

</div></code>```

Title: How to adjust the divs?

Body:
I need to move the paragraph div over to the left with it expanding all the way to the image. The top-div should display on two lines and break after the word festival. Both paragraphs should be to the left of the image. How do I get the div's to display correctly?

body {
  width: 8.5in;
}

.container {
  display: flex;
  background: red;
}

.top-div {
  display: table;
  background: rgb(204, 255, 102);
  text-align: center;
  font-size: 1.75em;
  font-weight: bold;
  color: rgb(35, 66, 113);
}

.top-div>p {
  margin: 10px;
}

.paragraph {
  align-self: flex-end;
  background: blue;
}

.flower-img {
  display: table;
  float: left;
}

Qingming Festival
qīng míng jié

The Qingming or Ching Ming Festival, also known as Tomb-Sweeping Day in English, is a traditional Chinese festival on the first day of the fifth solar term of the traditional Chinese lunisolar calendar. This makes it the 15th day after the Spring
      Equinox, either 4 or 5 April in a given year. Other common translations include Chinese Memorial Day and Ancestors' Day.

It is also a time for people to go outside to enjoy the spring such as having a picnic or flying a kite. In 2017 Qingming Festival falls on April 4. The three-day public holiday in China is April 3–5, 2017.

This what I would like it to look like

Body:
Place your paragprah elements in a parent container with class content, then place this container in your div with class container.
Afterwards apply  css styling as follows

body {
  width: 10.5in;
}

.container {
  background: red;
}

.content {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  margin: 0;
}

.top-div {
  background: rgb(204, 255, 102);
  text-align: center;
  font-size: 1.75em;
  font-weight: bold;
  color: rgb(35, 66, 113);
}

.top-div>p {
  margin: 0;
}

.paragraph {
  background: blue;
  height: 100%;
}

<div class="container">

  <div class="content">

    <div class="paragraph">
      <div class="top-div">
        <p lang="zh">Qingming Festival
          <br>qīng míng jié</p>
      </div>
      <p>The Qingming or Ching Ming Festival, also known as Tomb-Sweeping Day in English, is a traditional Chinese festival on the first day of the fifth solar term of the traditional Chinese lunisolar calendar. This makes it the 15th day after the Spring
        Equinox, either 4 or 5 April in a given year. Other common translations include Chinese Memorial Day and Ancestors&#39; Day.</p>
      <p>It is also a time for people to go outside to enjoy the spring such as having a picnic or flying a kite. In 2017 Qingming Festival falls on April 4. The three-day public holiday in China is April 3–5, 2017.</p>
    </div>
    <div>
      <img src="//dummyimage.com/300x450" alt="flower" width="300" class="flower-img">
    </div>
  </div>

</div>


问:
Python: Building a Bar Chart in Tkinter with Data From an SQlite3 Database
Before I start I am new to stack overflow so I apologize if my question is poorly formatted. Also this is for an A-level school project for my school library and aims to help with the management of the library. I have created a table containing data about students previous loans named 'pastLoans'(see here ), I need a way of finding out which books are most popular among library users and represent the findings on a bar chart. To do this I created an SQL command that counts the number of times a book title appears from the 'book' column of the 'pastLoans' table, currently I have 2 books in there (see here).

Due to the nature of Tk.canvas bar charts only except integers as data respectively, so I need to find a way of splitting up the name of the book and the amount of times it occurs in the table, using the amount of times it has occurred as the data to be displayed on the barchart, and the name of the book as the labels on the X Axis.

Currently I have coded the SQL command to pull the data I need from the table containing data about the past loans using the 'COUNT' function in SQLite3, additionally I have coded the frame for the bar chart and have tested it works with sample data from a list e.g [1,2,3,4,5,..]

Please note the bar chart successfully displays on Tkinter with the correct data values, unfortunately I cannot add a picture of the result since I do not have enough rep.

My code looks like this:

```<code>    command = ("SELECT book,COUNT(book) AS cnt FROM pastLoans GROUP BY
    book ORDER BY cnt DESC;")

    c.execute(command)
    result = c.fetchall()
    print (result)
    """This is the code for pulling the book name and amount of books
    from the "pastLoans" as well as the book name, the result is this:

    >>> [('Book', 1), ('Harry Potter', 1)]

    This is my bar chart frame:"""

    data = [1, 2, 3, 4, 5] #The data used here is sample data.

    g_width = 900  # Define it's width
    g_height = 400  # Define it's height
    g = tk.Canvas(self, width=g_width, height=g_height)
    g.grid()

    # The variables below size the bar graph
    y_stretch = 15  # The highest y = max_data_value * y_stretch
    y_gap = 20  # The gap between lower canvas edge and x axis
    x_stretch = 10  # Stretch x wide enough to fit the variables
    x_width = 20  # The width of the x-axis
    x_gap = 20  # The gap between left canvas edge and y axis

    for x, y in enumerate(data):

        # coordinates of each bar

        # Bottom left coordinate
        x0 = x * x_stretch + x * x_width + x_gap

        # Top left coordinates
        y0 = g_height - (y * y_stretch + y_gap)

        # Bottom right coordinates
        x1 = x * x_stretch + x * x_width + x_width + x_gap

        # Top right coordinates
        y1 = g_height - y_gap

        # Draw the bar
        g.create_rectangle(x0, y0, x1, y1, fill="red")

        # Put the y value above the bar
        g.create_text(x0 + 2, y0, anchor=tk.SW, text=str(y))
</code>```

答:
As you have already done all of the work to get tkinter display the bars and some text above it you just have to iterate over result instead of data:

```<code># Sort so that the most popular book is on the left
result.sort(key=lambda e: e[1], reverse=True)

for x, (name, y) in enumerate(result):
   ...

   # Put the name above the bar
   g.create_text(x0 + 2, y0, anchor=tk.SW, text=name)
</code>```

You may have to vary the x_stretch variable, so that the text does not overlap.

Body:
Before I start I am new to stack overflow so I apologize if my question is poorly formatted. Also this is for an A-level school project for my school library and aims to help with the management of the library. I have created a table containing data about students previous loans named 'pastLoans'(see here ), I need a way of finding out which books are most popular among library users and represent the findings on a bar chart. To do this I created an SQL command that counts the number of times a book title appears from the 'book' column of the 'pastLoans' table, currently I have 2 books in there (see here).

Due to the nature of Tk.canvas bar charts only except integers as data respectively, so I need to find a way of splitting up the name of the book and the amount of times it occurs in the table, using the amount of times it has occurred as the data to be displayed on the barchart, and the name of the book as the labels on the X Axis.

Currently I have coded the SQL command to pull the data I need from the table containing data about the past loans using the 'COUNT' function in SQLite3, additionally I have coded the frame for the bar chart and have tested it works with sample data from a list e.g [1,2,3,4,5,..]

Please note the bar chart successfully displays on Tkinter with the correct data values, unfortunately I cannot add a picture of the result since I do not have enough rep.

My code looks like this:

    command = ("SELECT book,COUNT(book) AS cnt FROM pastLoans GROUP BY
    book ORDER BY cnt DESC;")

    c.execute(command)
    result = c.fetchall()
    print (result)
    """This is the code for pulling the book name and amount of books
    from the "pastLoans" as well as the book name, the result is this:

    >>> [('Book', 1), ('Harry Potter', 1)]

    This is my bar chart frame:"""

    data = [1, 2, 3, 4, 5] #The data used here is sample data.

    g_width = 900  # Define it's width
    g_height = 400  # Define it's height
    g = tk.Canvas(self, width=g_width, height=g_height)
    g.grid()

    # The variables below size the bar graph
    y_stretch = 15  # The highest y = max_data_value * y_stretch
    y_gap = 20  # The gap between lower canvas edge and x axis
    x_stretch = 10  # Stretch x wide enough to fit the variables
    x_width = 20  # The width of the x-axis
    x_gap = 20  # The gap between left canvas edge and y axis

    for x, y in enumerate(data):

        # coordinates of each bar

        # Bottom left coordinate
        x0 = x * x_stretch + x * x_width + x_gap

        # Top left coordinates
        y0 = g_height - (y * y_stretch + y_gap)

        # Bottom right coordinates
        x1 = x * x_stretch + x * x_width + x_width + x_gap

        # Top right coordinates
        y1 = g_height - y_gap

        # Draw the bar
        g.create_rectangle(x0, y0, x1, y1, fill="red")

        # Put the y value above the bar
        g.create_text(x0 + 2, y0, anchor=tk.SW, text=str(y))

Body:
As you have already done all of the work to get tkinter display the bars and some text above it you just have to iterate over result instead of data:

# Sort so that the most popular book is on the left
result.sort(key=lambda e: e[1], reverse=True)

for x, (name, y) in enumerate(result):
   ...

   # Put the name above the bar
   g.create_text(x0 + 2, y0, anchor=tk.SW, text=name)

You may have to vary the x_stretch variable, so that the text does not overlap.


问:
Can anyone send me a link for best boilerplate in react redux?
I want the perfect boilerplate for react redux. Can any one send me a github link?</p>

答:
There is an open source library with a number of complete examples:
https://github.com/reactjs/redux/tree/master/examples

It's an excellent resource while learning.


问:
SQL query, join on a manipulated column
I have database table with the following column structure and data (1 column example only)

```<code>[ProductRaw] [nvarchar](255) NULL
One Kind of Product (CatA)
Another Product (CatB)
Yet Another Product (CatC)
</code>```

I cannot change this column due to other requirements but I also need to do a 'join' on a clean version of this column. The clean version would look like this

```<code>[ProductClean] [nvarchar](255) NULL
One Kind of Product
Another Product
Yet Another Product
</code>```

What would the best way to do this in SQL server be? I know it can be done using  the following

```<code>DECLARE @Sql varchar(50) = 'One Kind of Product (CatA)'

SELECT
    PARSENAME(REPLACE(@sql,' (','.'),2)
</code>```

Is there a better way to do this (eg such as calculated column)?

答:
You can use like:

```<code>on ProductRaw like ProductClean + '%'
</code>```

However, my recommendation is to alter the table with a computed column:

```<code>alter table t
    add ProductClean as (left(ProductRaw, charindex(' (', ProductRaw + ' (') - 1)));
</code>```

Then you can add an index on ProductClean and do a more sensible join:

```<code>on t.ProductClean = ?.ProductClean
</code>```

Title: SQL query, join on a manipulated column

Body:
I have database table with the following column structure and data (1 column example only)

[ProductRaw] [nvarchar](255) NULL
One Kind of Product (CatA)
Another Product (CatB)
Yet Another Product (CatC)

I cannot change this column due to other requirements but I also need to do a 'join' on a clean version of this column. The clean version would look like this

[ProductClean] [nvarchar](255) NULL
One Kind of Product
Another Product
Yet Another Product

What would the best way to do this in SQL server be? I know it can be done using  the following

DECLARE @Sql varchar(50) = 'One Kind of Product (CatA)'

SELECT
    PARSENAME(REPLACE(@sql,' (','.'),2)

Is there a better way to do this (eg such as calculated column)?

Body:
You can use like:

on ProductRaw like ProductClean + '%'

However, my recommendation is to alter the table with a computed column:

alter table t
    add ProductClean as (left(ProductRaw, charindex(' (', ProductRaw + ' (') - 1)));

Then you can add an index on ProductClean and do a more sensible join:

on t.ProductClean = ?.ProductClean


问:
Create an enclave in an linux kernel module
Is it possible to write a linux kernel module and create an enclave in the module.
And how to do this.</p>

答:
No, all enclave operations (those executed by the enclaves not by the kernel creating the enclave) have to be executed in user mode. They will fail if executed in kernel mode.

However, there is a scientific paper where they use a kernel module that communicates with a user space SGX enclave via a Netlink connection.


问:
C++, char* string modification
I am new to C++.
I have a program:

```<code>#include <iostream>

int main()
{
   char* str = "Test";
   *str = 'S';
}
</code>```

The question is, why *str = 'S' crashes the program?
As far as I know str must be pointing to the first character of the string (well, char array), so in theory I should be able to modify it.
Is it because the memory is read-only for defined constant values?
I am using gcc 5.3.0.

答:
why *str = 'S' crashes the program?

Because you're not allowed to modify string literals. The C++ standard allows them to be stored in read-only memory.

In fact, if you enable compiler warnings, you get:

```<code>prog.cc:5:16: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    char* str = "Test";
                ^~~~~~
</code>```

Always use const char* when pointing to string literals:

Title: C++, char* string modification

Body:
I am new to C++.
I have a program:

#include <iostream>

int main()
{
   char* str = "Test";
   *str = 'S';
}

The question is, why *str = 'S' crashes the program?
As far as I know str must be pointing to the first character of the string (well, char array), so in theory I should be able to modify it.
Is it because the memory is read-only for defined constant values?
I am using gcc 5.3.0.

Body:
why *str = 'S' crashes the program?

Because you're not allowed to modify string literals. The C++ standard allows them to be stored in read-only memory.

In fact, if you enable compiler warnings, you get:

prog.cc:5:16: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    char* str = "Test";
                ^~~~~~

Always use const char* when pointing to string literals:


问:
Java script to close doesn't work
I build a toggle bar in html/css and I want to use JS to close. I think I did all the code right, yet the script does not work.

Code:

```<code>$(document).ready(function(){
$(".fa-times").click(function(){$(".sidebar_menu").addClass("hide_menu");
$(".toggle_menu").addClass("opacity_one");});
</code>```

jsfiddle link

The point is that I created a button "x shaped" that closes the side bar but you won't be able to see it cuz is a custom font and I have no clue how to upload it onto jsfiddle. The button is placed in the top-right corner of the purple bar.

I hope its enough information and the code is easy to understand. I`m just at the start with html/css/js but I have to do this for a microsoft project since noone in my team can't even set a default html page.

P.S. Ignore the white element with that random text.

答:
Check width with element inspector in you browser

```<code><i class="fa fa-times">you need same place holder here, or set width</i>
</code>```

EDITED

Title: Java script to close doesn't work

Body:
I build a toggle bar in html/css and I want to use JS to close. I think I did all the code right, yet the script does not work.

Code:

$(document).ready(function(){
$(".fa-times").click(function(){$(".sidebar_menu").addClass("hide_menu");
$(".toggle_menu").addClass("opacity_one");});

jsfiddle link

The point is that I created a button "x shaped" that closes the side bar but you won't be able to see it cuz is a custom font and I have no clue how to upload it onto jsfiddle. The button is placed in the top-right corner of the purple bar.

I hope its enough information and the code is easy to understand. I`m just at the start with html/css/js but I have to do this for a microsoft project since noone in my team can't even set a default html page.

P.S. Ignore the white element with that random text.

Body:
Check width with element inspector in you browser

<i class="fa fa-times">you need same place holder here, or set width</i>

EDITED


问:
Using 'goto' to move from if to else
I know that there's no goto in java, but I ask on general if there are a method to goto from if to else
example :

```<code>public void decToAsci(String decimal) {
    String nb = "";
    int number;
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                //here i want to jump to else
                // i can do it like this :
                // System.out.print( (char) Integer.parseInt(nb) + " ");
                // but i repeat code in else here ..i just want to jump to else
        } else {
            number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
            number = 0;
        }
    }
}
</code>```

I try this :

```<code>if (!c.equals(' ')) {
    nb += decimal.charAt(i);
    if (i == decimal.length() - 1) continue label;
} else {
    label: the code in else
}
</code>```

But not worked, not worked with break label also. I understand that continue, break. Are used between son and parent like that? :

```<code>label:
for(int i=0 ; i<n ; i++)
    if (cond) break label;
</code>```

I ask about a method that can jump from if to else (2 sons)

(not a son and a parent but jumping between 2 sons )

I think even with goto on c and c++ 4 example we can't do it

答:
I think you did not think this through correctly. An if-else statement is designed in such a way that you can't jump from the if branch to the else branch. The whole point of an if statement is to make it clear that "if this is true, do this, otherwise do that." Trying to violate this by using dirty tricks will only lead to maintenance problems. Your code will become very difficult to understand.

Instead of thinking about how to break the if statement, why not find a workaround? What you seem to be doing here is just reading integers separated by white space. If that's what you are doing, why not append a ' ' character to the end of the string before the loop? This will achieve the same thing as the condition i == decimal.length() - 1

```<code>decimal += " ";
String nb = "";
int number;
for (int i = 0; i < decimal.length(); i++) {
    ...
</code>```

Or you can use a Scanner:

```<code>Scanner s = new Scanner(decimal);
while (s.hasNextInt())
    System.out.print(((char)s.nextInt()) + " ");
</code>```

Title: Using 'goto' to move from if to else

Body:
I know that there's no goto in java, but I ask on general if there are a method to goto from if to else
example :

public void decToAsci(String decimal) {
    String nb = "";
    int number;
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                //here i want to jump to else
                // i can do it like this :
                // System.out.print( (char) Integer.parseInt(nb) + " ");
                // but i repeat code in else here ..i just want to jump to else
        } else {
            number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
            number = 0;
        }
    }
}

I try this :

if (!c.equals(' ')) {
    nb += decimal.charAt(i);
    if (i == decimal.length() - 1) continue label;
} else {
    label: the code in else
}

But not worked, not worked with break label also. I understand that continue, break. Are used between son and parent like that? :

label:
for(int i=0 ; i<n ; i++)
    if (cond) break label;

I ask about a method that can jump from if to else (2 sons)

(not a son and a parent but jumping between 2 sons )

I think even with goto on c and c++ 4 example we can't do it

Body:
I think you did not think this through correctly. An if-else statement is designed in such a way that you can't jump from the if branch to the else branch. The whole point of an if statement is to make it clear that "if this is true, do this, otherwise do that." Trying to violate this by using dirty tricks will only lead to maintenance problems. Your code will become very difficult to understand.

Instead of thinking about how to break the if statement, why not find a workaround? What you seem to be doing here is just reading integers separated by white space. If that's what you are doing, why not append a ' ' character to the end of the string before the loop? This will achieve the same thing as the condition i == decimal.length() - 1

decimal += " ";
String nb = "";
int number;
for (int i = 0; i < decimal.length(); i++) {
    ...

Or you can use a Scanner:

Scanner s = new Scanner(decimal);
while (s.hasNextInt())
    System.out.print(((char)s.nextInt()) + " ");


问:
How do I count how many times a string occur in a file using javascript?
How to count no. of occurrences of a regex string or a html tag in the entire file using javascript?
Say for example, I want to find how many href="graphic[0-9]+"> tags are present in a file and store that value in a variable. How do I achieve that?

答:
```<code>var len = document.querySelectorAll("a[href='graphic[0-9]+']").length;
</code>```

Body:
How to count no. of occurrences of a regex string or a html tag in the entire file using javascript?
Say for example, I want to find how many  tags are present in a file and store that value in a variable. How do I achieve that?


问:
Issue with passing property through function
First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner. </p>

```<code> var student={FirstName:"", LastName:""};
var studentlist=[];

var i=0;

function generatePassword() {
    var length = 4,
        charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}

  function Register() {
    var next="Yes";
    while (next="Yes"){
        student.FirstName=prompt("Please enter the name");
        student.LastName=prompt("Please enter the last name");

        studentlist.push(student);

        document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
        "<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
        next = prompt ("Do you want to add more data?", "Yes")
         i++;
      }
    }
</code>```

答:
Two mistakes:

```<code>var student={FirstName:""; LastName:""};

Should be -> var student={FirstName:"", LastName:""};

var i==0; -> var i = 0;
</code>```

Try after changes and tell me if it works ;d

Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.

Body:
First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.

 var student={FirstName:"", LastName:""};
var studentlist=[];

var i=0;

function generatePassword() {
    var length = 4,
        charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}

  function Register() {
    var next="Yes";
    while (next="Yes"){
        student.FirstName=prompt("Please enter the name");
        student.LastName=prompt("Please enter the last name");

        studentlist.push(student);

        document.getElementById("demo").innerHTML += "
 First Name: "+ studentlist[i].FirstName + "," +
        "Last Name: "+ studentlist[i].LastName + "," + "
";
        next = prompt ("Do you want to add more data?", "Yes")
         i++;
      }
    }

Body:
Two mistakes:

var student={FirstName:""; LastName:""};

Should be -> var student={FirstName:"", LastName:""};

var i==0; -> var i = 0;

Try after changes and tell me if it works ;d

Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.


问:
to MSMQ or not to MSMQ? (or SQL Table as the Queue)
I've got a distributed system where there will be 1 SQL Server, 1-n processing servers, and 1-n data suppliers (hardware devices across the network).  The data being supplied will require processing prior to going into the relational DB structure - performed by the processing servers (as windows services - .net code to parse the data, process it, and insert it into the relational structure.)

To handle the potential load and not slow down the data suppliers, I want to implement a queue, but I'm not sure I want to add the complexity of an MSMQ server to the mix.  Is there a good alternative to MSMQ, such as using the DB (a flat table) as the queue?  Does .NET provide any out-of-the-box support for DB queues, or is there another option for reliable queueing?

Thanks

EDIT: (29 Nov, 11:30pm)

sounds like SQL Service Broker (SSB) might do the trick.

http://www.netframeworkdev.com/windows-communication-foundation/service-broker-vs-msmq-as-reliable-queueing-mechanism-63981.shtml

EDIT: (30 Nov, 7:45am)

Found another very useful link on this subject:

http://social.msdn.microsoft.com/Forums/en-US/sqlservicebroker/thread/52687510-0852-44f3-bfcd-83610d1c1b9a

I'm also looking into the max/min size of the data that will be supplied.  Of the top of their head, does anyone know the max size accommodated by MSMQ and/or SSB?

MSMQ: 4MB message size

SSB: 2GB message size

EDIT: (30 nov, 8;15am)

Great comparison between MSMQ & SSB here:

Good Strategy for Message Queuing?

答: Out of the two options, MSMQ is actually the more simplistic. If you need the ability to re-prioritize work, or have processing agents only pick certain types of queued jobs, then you cant use MSMQ. If you dont need any of those bells and whistles, then MSMQ is cake to use with .NET.</p>


问:
remove specific string in python2.7
I have a list as follows:

```<code>>>> header
['Id', ["['GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']"]]
>>> type(header)
list
</code>```

And, how can I change it to a string as follows;

```<code>['Id','GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']
</code>```

I'm try used re.split('\[|\]|\"',str(header)) . But the resulted is not I want to get.

```<code>['',
 "'Id', ",
 '',
 '',
 "'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt'",
 '',
 '',
 '',
 '']
</code>```

So, any suggestion is hope.

答:
```<code>parsed = header[:1] + eval(header[1][0])
</code>```

<p>This will work if you always have the exact format you have in the example and the second string has a proper Python syntax. </p>

Title: remove specific string in python2.7

Body:
I have a list as follows:

>>> header
['Id', ["['GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']"]]
>>> type(header)
list

And, how can I change it to a string as follows;

['Id','GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']

I'm try used re.split('\[|\]|\"',str(header)) . But the resulted is not I want to get.

['',
 "'Id', ",
 '',
 '',
 "'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt'",
 '',
 '',
 '',
 '']

So, any suggestion is hope.

Body:
parsed = header[:1] + eval(header[1][0])

This will work if you always have the exact format you have in the example and the second string has a proper Python syntax.