问:
Make DbDataReader start reading again from the beginning of the result set
How to make dr.Read(); start reading again from the beginning if a condition is satisfied?

Something like:

```<code>SqlDataReader dr = command.ExecuteReader();
for(int i=0; dr.Read() ; i++){
    if(condition ){
        //let dr.Read() start reading from the beginning
    }
}
</code>```

答:
You can do that by first closing the datareader using dr.close();  then initializing it again.

```<code>If(condition)
{
    dr.close();
    dr=command.ExecuteReader();
}
</code>```

Where command is the MySqlCommand object.

Body:
How to make dr.Read(); start reading again from the beginning if a condition is satisfied?

Something like:

SqlDataReader dr = command.ExecuteReader();
for(int i=0; dr.Read() ; i++){
    if(condition ){
        //let dr.Read() start reading from the beginning
    }
}

Body:
You can do that by first closing the datareader using dr.close();  then initializing it again.

If(condition)
{
    dr.close();
    dr=command.ExecuteReader();
}

Where command is the MySqlCommand object.


来源: stackexchange

问:
Sending a button response to fb messenger via api.ai
I have started playing with diaglofFlow a.k.a api.ai with fb messenger integration.

I defined an intent which current returns 3 responses. 2 text responses and 1 custom payload.

the 2 text responses comes just fine but the custom payload which is suppose to return a button is not.

the custom payload looks like

```<code>{
  "recipient": {
    "id": "1234"
  },
  "message": {
    "attachment": {
      "type": "template",
      "payload": {
        "template_type": "button",
        "text": "What do you want to do next?",
        "buttons": [
          {
            "type": "web_url",
            "url": "https://www.messenger.com",
            "title": "Visit Messenger"
          }
        ]
      }
    }
  }
}
</code>```

Also, please note that the recipient id is something i am not sure how it should be provided. the fb documentation says it should be number of the recipient. I do not know how i am going to get that?

答:
recipient.id is the user's Page-scoped ID. You receive it in the sender.id prop of webhook events when the user initiates a conversation.

https://developers.facebook.com/docs/messenger-platform/introduction/integration-components#psid

ContentLicense: CC BY-SA 3.0

Body:
I have started playing with diaglofFlow a.k.a api.ai with fb messenger integration.

I defined an intent which current returns 3 responses. 2 text responses and 1 custom payload.

the 2 text responses comes just fine but the custom payload which is suppose to return a button is not.

the custom payload looks like

{
  "recipient": {
    "id": "1234"
  },
  "message": {
    "attachment": {
      "type": "template",
      "payload": {
        "template_type": "button",
        "text": "What do you want to do next?",
        "buttons": [
          {
            "type": "web_url",
            "url": "https://www.messenger.com",
            "title": "Visit Messenger"
          }
        ]
      }
    }
  }
}

Also, please note that the recipient id is something i am not sure how it should be provided. the fb documentation says it should be number of the recipient. I do not know how i am going to get that?


问:
PHP or C# or (X)? HTTP Request every 10 seconds and Chart image generation
Objective: HTTP Request every 10 seconds, chart image generation on server and upload back to user's browser for display

I wanted to go with LAMP + pChart but worried it might not handle > 1000 of simultaneous users and slow the server down to a crawl.

I thought about offloading the chart image generation to Google Charts but if the request is once every 10 seconds, I'd blast through the daily limit easily.

What server + lang is best for this implementation? Would I need to think about scaling at this point yet?

答: A low end dedicated server, or a mid-range VPS will handle this no matter what language and platform you choose. 1000 simultaneous users requesting a chart every 10 seconds is an average of only 100 requests per second. I generate over 1000 dynamic images per second on a standard LAMP/PHP stack and it doesn't really generate much load at all. </p>

ContentLicense: CC BY-SA 2.5


问:
How Billing works with internal IPs
If I create a custom network. lets say I have 2 subnets in the same network and If I try to communicate from VM-1 and VM-2 which are in subnet-1 and subnet-2 with the help of Internal IPs. Will be billed for egress?

Google docs says it will be billed for
between Zones
Across regions

But not mentioned about Internal or exteranl IPs

答:
The table is in general network pricing is for egress through the Internal IP.

When using the External IP all egress is charged, even if the destination VM is in the same Zone. The details are in Traffic through external IP addresses.

Title: How Billing works with internal IPs


问:
c# Switch case not working
I'm trying to check a value by using a switch:

private void btnInput1Rste_Click(object sender, EventArgs e)
{
    switch (sender == btnInput1Rste)
    {
        case "1": currentButtonPressedRste = 1;
            break;
    }
}
```

It gives the error as follows:

can't convert type 'string' to 'bool'

However, when i try to convert it to a boolean it says:

a constant value is expected.

How do I fix it?

When it works it's supposed to check 3 values. (not with just this switch)

答:
Your switch is formatted oddly as well I think you want to see if btnInput1Rste was equal to the sender? And you don't have default case either.

```<code> switch (sender)
    {
        case btnInput1Rste:
             //This button was the sender
            break;
        default:
            break;
    }
</code>```

Title: c# Switch case not working

Body:
I'm trying to check a value by using a switch:

private void btnInput1Rste_Click(object sender, EventArgs e)
{
    switch (sender == btnInput1Rste)
    {
        case "1": currentButtonPressedRste = 1;
            break;
    }
}

It gives the error as follows:

can't convert type 'string' to 'bool'

However, when i try to convert it to a boolean it says:

a constant value is expected.

How do I fix it?

When it works it's supposed to check 3 values. (not with just this switch)

Body:
Your switch is formatted oddly as well I think you want to see if btnInput1Rste was equal to the sender? And you don't have default case either.

 switch (sender)
    {
        case btnInput1Rste:
             //This button was the sender
            break;
        default:
            break;
    }


问:
How to export SQL Server data to Excel using VBA?
Currently I'm testing how to export data from SQL Server Management Studio to Excel for an upcoming project.

I looked up online and came upon a code as follows:

```<code>Function ImportSQLtoRange(ByVal conString As String, ByVal query As String, ByVal target As Range) As Integer

On Error Resume Next

' Object type and CreateObject function are used instead of ADODB.Connection,
' ADODB.Command for late binding without reference to
' Microsoft ActiveX Data Objects 2.x Library

' ADO API Reference
' http://msdn.microsoft.com/en-us/library/ms678086(v=VS.85).aspx

' Dim con As ADODB.Connection
Dim con As Object
Set con = CreateObject("ADODB.Connection")

con.ConnectionString = conString

' Dim cmd As ADODB.Command
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")

cmd.CommandText = query
cmd.CommandType = 1         ' adCmdText

' The Open method doesn't actually establish a connection to the server
' until a Recordset is opened on the Connection object
con.Open
cmd.ActiveConnection = con

' Dim rst As ADODB.Recordset
Dim rst As Object
Set rst = cmd.Execute

If rst Is Nothing Then
    con.Close
    Set con = Nothing

    ImportSQLtoRange = 1
    Exit Function
End If

Dim ws As Worksheet
Dim col As Integer

Set ws = target.Worksheet

' Column Names
For col = 0 To rst.Fields.Count - 1
    ws.Cells(target.row, target.Column + col).Value = rst.Fields(col).Name
Next
ws.Range(ws.Cells(target.row, target.Column), ws.Cells(target.row, target.Column + rst.Fields.Count)).Font.Bold = True

' Data from Recordset
ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst

rst.Close
con.Close

Set rst = Nothing
Set cmd = Nothing
Set con = Nothing

ImportSQLtoRange = 0

End Function

Sub TestImportUsingADO()

Dim conString As String
conString = "data source = server name; initial catalog = database; uid = name; password = password"

Dim query As String
query = "my query goes here"

Dim target As Range
Set target = ThisWorkbook.Sheets(2).Cells(3, 2)

target.CurrentRegion.Clear

Select Case ImportSQLtoRange(conString, query, target)
    Case 1
        MsgBox "Import database data error", vbCritical
    Case Else
End Select

End Sub
</code>```

When I try to use the macro, I receive a message box as set in Case 1 in ImportSQLtoRange. But I'm not sure if that means that the code works and can access the query or this is an error message. If this shows that it does work how do I modify it so that it gives me the table I want based on my query?

Edit: Upon following Kazimierz Jawor suggestion, I commented on

```<code>On Error Resume Next
</code>```

Now I get an error as follows:

Clicking Debug show the error coming from

```<code>con.open
</code>```

What does that mean?

答:
How about doing it this way?

```<code>Sub GetDataFromADO()

    'Declare variables'
        Set objMyconn = New ADODB.Connection
        Set objMyCmd = New ADODB.Command
        Set objMyRecordset = New ADODB.Recordset
        Dim rc As Long

    'Open Connection'
        objMyconn.ConnectionString = "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_DB_Name; Integrated Security=SSPI;"

        objMyconn.Open

    'Set and Excecute SQL Command'
        Set objMyCmd.ActiveConnection = objMyconn
        objMyCmd.CommandText = "select * from [Person].[BusinessEntity] "
        objMyCmd.CommandType = adCmdText
        objMyCmd.Execute

    'Open Recordset'
        Set objMyRecordset.ActiveConnection = objMyconn
        objMyRecordset.Open objMyCmd

    'Copy Data to Excel'
        'ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
        Application.ActiveCell.CopyFromRecordset (objMyRecordset)
        rc = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
        ActiveSheet.Cells(rc + 1, 1).Select
        'Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Value
        objMyconn.Close

End Sub
</code>```

You can find lots of useful tips about integrating Excel and SQL Server from the link below.

https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm

Body:
Currently I'm testing how to export data from SQL Server Management Studio to Excel for an upcoming project.

I looked up online and came upon a code as follows:

Function ImportSQLtoRange(ByVal conString As String, ByVal query As String, ByVal target As Range) As Integer

On Error Resume Next

' Object type and CreateObject function are used instead of ADODB.Connection,
' ADODB.Command for late binding without reference to
' Microsoft ActiveX Data Objects 2.x Library

' ADO API Reference
' http://msdn.microsoft.com/en-us/library/ms678086(v=VS.85).aspx

' Dim con As ADODB.Connection
Dim con As Object
Set con = CreateObject("ADODB.Connection")

con.ConnectionString = conString

' Dim cmd As ADODB.Command
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")

cmd.CommandText = query
cmd.CommandType = 1         ' adCmdText

' The Open method doesn't actually establish a connection to the server
' until a Recordset is opened on the Connection object
con.Open
cmd.ActiveConnection = con

' Dim rst As ADODB.Recordset
Dim rst As Object
Set rst = cmd.Execute

If rst Is Nothing Then
    con.Close
    Set con = Nothing

    ImportSQLtoRange = 1
    Exit Function
End If

Dim ws As Worksheet
Dim col As Integer

Set ws = target.Worksheet

' Column Names
For col = 0 To rst.Fields.Count - 1
    ws.Cells(target.row, target.Column + col).Value = rst.Fields(col).Name
Next
ws.Range(ws.Cells(target.row, target.Column), ws.Cells(target.row, target.Column + rst.Fields.Count)).Font.Bold = True

' Data from Recordset
ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst

rst.Close
con.Close

Set rst = Nothing
Set cmd = Nothing
Set con = Nothing

ImportSQLtoRange = 0

End Function

Sub TestImportUsingADO()

Dim conString As String
conString = "data source = server name; initial catalog = database; uid = name; password = password"

Dim query As String
query = "my query goes here"

Dim target As Range
Set target = ThisWorkbook.Sheets(2).Cells(3, 2)

target.CurrentRegion.Clear

Select Case ImportSQLtoRange(conString, query, target)
    Case 1
        MsgBox "Import database data error", vbCritical
    Case Else
End Select

End Sub

When I try to use the macro, I receive a message box as set in Case 1 in ImportSQLtoRange. But I'm not sure if that means that the code works and can access the query or this is an error message. If this shows that it does work how do I modify it so that it gives me the table I want based on my query?

Edit: Upon following Kazimierz Jawor suggestion, I commented on

On Error Resume Next

Now I get an error as follows:

Clicking Debug show the error coming from

con.open

What does that mean?

Body:
How about doing it this way?

Sub GetDataFromADO()

    'Declare variables'
        Set objMyconn = New ADODB.Connection
        Set objMyCmd = New ADODB.Command
        Set objMyRecordset = New ADODB.Recordset
        Dim rc As Long

    'Open Connection'
        objMyconn.ConnectionString = "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_DB_Name; Integrated Security=SSPI;"

        objMyconn.Open

    'Set and Excecute SQL Command'
        Set objMyCmd.ActiveConnection = objMyconn
        objMyCmd.CommandText = "select * from [Person].[BusinessEntity] "
        objMyCmd.CommandType = adCmdText
        objMyCmd.Execute

    'Open Recordset'
        Set objMyRecordset.ActiveConnection = objMyconn
        objMyRecordset.Open objMyCmd

    'Copy Data to Excel'
        'ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
        Application.ActiveCell.CopyFromRecordset (objMyRecordset)
        rc = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
        ActiveSheet.Cells(rc + 1, 1).Select
        'Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Value
        objMyconn.Close

End Sub

You can find lots of useful tips about integrating Excel and SQL Server from the link below.

https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm


问:
Cannot Import F2PY Generated Module in __init__.py
I am Wrapping a fortran library with f2py, so far it has been successful in terms of getting the functions to work within python

I am at the point of structuring my package and am running into __init__.py issues when using these f2py generated modules. This is related to a package constructed with distutils extensions for f2py

After installing the egg, in an external script I can import the f2py generated module directly

```<code>from package.core.module1 import fortran_fn
</code>```

,but when I place

```<code>from module1 import fortran_fn
</code>```

in  package/core/__init__.py in order to refactor the namespace for users,

the package import fails

```<code>----> 1 import package.core as core
~/venv/dev/lib/python3.5/site-packages/package-py3.5-linux-x86_64.egg/package/core/__init__.py in <module>()
      1
      2
----> 3 from module1 import fortran_fn
      4
      5

ImportError: No module named 'module1'
</code>```

However, there is one exception, for whatever reason one module in particular, does wish to import itself.

Project Structure:

```<code>setup.py
package/
  __init__.py
  core/
    __init__.py
    module1.pyf
    module2.pyf
    ...
src/
  lib/
    module1.f
    module2.f
    ...
</code>```

*pyf were generated with f2py -h package/core/moduleX.pyf src/lib/moduleX.f -m moduleX

Further,

```<code>#core/__init__.py

from module1 import fortran_fn
</code>```

and,

```<code>#setup.py
from setuptools import find_packages
from numpy.distutils.core import Extension

ext1 = Extension(name='package.core.module1',
                 sources=['package/core/module1.pyf',
                 'src/lib/module1.f'])
#ext2 = ...
# and others

setup (name="package",
       packages = find_packages(),
       ext_modules = [ ext1 ]) # ..., ext2, ... ]
</code>```

Code samples simplified to illustrate the problem, the specific code is available at this github

For some context, I initially tried to have f2py place the fortran into the .core subpackage directly by compiling with -m package.core and the same for name='package.core' for extension, however f2py would complain about missing names.

In this particular structure there is an additional layer where each fortran module is just one function, and I would like to remove the extra submodule layer from the API.

答:
In Python 3 all imports are absolute. To perform relative import do it explicitly:</p>

```<code>from .module1 import fortran_fn
</code>```

Body:
I am Wrapping a fortran library with f2py, so far it has been successful in terms of getting the functions to work within python

I am at the point of structuring my package and am running into __init__.py issues when using these f2py generated modules. This is related to a package constructed with distutils extensions for f2py

After installing the egg, in an external script I can import the f2py generated module directly

from package.core.module1 import fortran_fn

,but when I place

from module1 import fortran_fn

in  package/core/__init__.py in order to refactor the namespace for users,

the package import fails

----> 1 import package.core as core
~/venv/dev/lib/python3.5/site-packages/package-py3.5-linux-x86_64.egg/package/core/__init__.py in <module>()
      1
      2
----> 3 from module1 import fortran_fn
      4
      5

ImportError: No module named 'module1'

However, there is one exception, for whatever reason one module in particular, does wish to import itself.

Project Structure:

setup.py
package/
  __init__.py
  core/
    __init__.py
    module1.pyf
    module2.pyf
    ...
src/
  lib/
    module1.f
    module2.f
    ...

*pyf were generated with f2py -h package/core/moduleX.pyf src/lib/moduleX.f -m moduleX

Further,

#core/__init__.py

from module1 import fortran_fn

and,

#setup.py
from setuptools import find_packages
from numpy.distutils.core import Extension

ext1 = Extension(name='package.core.module1',
                 sources=['package/core/module1.pyf',
                 'src/lib/module1.f'])
#ext2 = ...
# and others

setup (name="package",
       packages = find_packages(),
       ext_modules = [ ext1 ]) # ..., ext2, ... ]

Code samples simplified to illustrate the problem, the specific code is available at this github

For some context, I initially tried to have f2py place the fortran into the .core subpackage directly by compiling with -m package.core and the same for name='package.core' for extension, however f2py would complain about missing names.

In this particular structure there is an additional layer where each fortran module is just one function, and I would like to remove the extra submodule layer from the API.

Body:
In Python 3 all imports are absolute. To perform relative import do it explicitly:

from .module1 import fortran_fn


问:
How to set maximum execution time for a Promise await?
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

```<code>await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}
</code>```

This is not for a bluebird promise.

答:
The code below will give you some idea:

function doSomething(maxExecutionTime) {
    return new Promise(resolve => {
        setTimeout(() => resolve(true), 2000);  // this setTimeout simulates your async action which sould not exced maxExecutionTime
        setTimeout(() => resolve(false), maxExecutionTime);
    });
}

async function someFunc(maxExecutionTime) {
    var exced = await doSomething(maxExecutionTime);
    if (exced) {
        console.log("Doesn't exced max time");
    } else {
        console.log("Exced max time");
    }
}

someFunc(1000);
someFunc(3000);```

Body:
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}

This is not for a bluebird promise.


问:
Fiware Keyrock - organizations are not returned AGAIN
I'm encountering the same problem asked here.
 The list of organizations of an authenticated user https://<idm_domain>/user?access_token=xxxxxxxxxxxxx is always empty.

I tried to follow the guide reported in the previous post to solve my problem but as reported in the past question, I can't find the button Authorize, the point 7 in the guide, so it's impossible to achieve.

Someone can help me!

Thanks in advance.

答:
Did you solve the problem?

You can assign roles to users in organization directly from the dialog that appears when you press "manage" button. There you must assign some specific roles to the user, then you will see the organization in the list retrieved from the service.

If it does not work for you, just ask and we can continue working on it.


问:
How to put some array elements from the middle to last in Javascript
I have this following JS object array whose elements are just columns of a HTML table :

```<code>var my_cols = [
  {
    "id": "name",
    "header": [
      "Name",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "type",
    "header": [
      "Type",
      {
        "content": "textFilter"
      }
    ],
    "width": 180,
    "sort": "string"
  },
  {
    "id": "dob",
    "header": [
      "DOB",
      {
        "content": "textFilter"
      }
    ],
    "width": 100,
    "sort": "string"
  },
  {
    "id": "merged_a",
    "header": [
      {
        "text": "merged_a",
        "colspan": 3
      },
      {
        "text": "port"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_b",
    "header": [
      null,
      {
        "text": "merged_b"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_c",
    "header": [
      null,
      {
        "text": "merged_c"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "place",
    "header": [
      "place",
      {
        "content": "textFilter"
      }
    ],
    "width": 300,
    "sort": "string"
  },
  {
    "id": "address",
    "header": [
      "address",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "phone",
    "header": [
      "phone",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  }
];
</code>```

I want to put elements with id as 'merged_a' , 'merged_b', and 'merged_c' at the end of the entire array my_cols. I have written the below code so far, however it is not giving me the exact result:

```<code>var my_cols= [{"id":"name","header":["Name",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"type","header":["Type",{"content":"textFilter"}],"width":180,"sort":"string"},
{"id":"dob","header":["DOB",{"content":"textFilter"}],"width":100,"sort":"string"},
{"id":"merged_a","header":[{"text":"merged_a","colspan":3},{"text":"port"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_b","header":[null,{"text":"merged_b"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_c","header":[null,{"text":"merged_c"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"place","header":["place",{"content":"textFilter"}],"width":300,"sort":"string"},
{"id":"address","header":["address",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"phone","header":["phone",{"content":"textFilter"}],"width":200,"sort":"string"}];
</code>```

My effort

 var my_cols = [
   { "id": "name", "header": [ "Name", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "type", "header": [ "Type", { "content": "textFilter" } ], "width": 180, "sort": "string" },
   { "id": "dob", "header": [ "DOB", { "content": "textFilter" } ], "width": 100, "sort": "string" },
   { "id": "merged_a", "header": [{ "text": "merged_a", "colspan": 3 }, { "text": "port" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_b", "header": [ null, { "text": "merged_b" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_c", "header": [ null, { "text": "merged_c" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "place", "header": [ "place", { "content": "textFilter" } ], "width": 300, "sort": "string" },
   { "id": "address", "header": [ "address", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "phone", "header": [ "phone", { "content": "textFilter" } ], "width": 200, "sort": "string" }
 ];

for (var i in my_cols) {

  var col = my_cols[i];
  var a_col;
  var b_col;
  var c_col;
  if (col.hasOwnProperty('id')) {
    if (col['id'] == 'merged_a') {
      a_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_b') {
      b_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_c') {
      c_col = my_cols.splice(i, 1);
    }
  }

}

my_cols.push(a_col);
my_cols.push(b_col);
my_cols.push(c_col);

console.log("my_cols = " + JSON.stringify(my_cols));```

答:
You can use Array.prototype.sort() for this. It take a optional compareFunction, which can be used to add custom sort. Please see following example.

var my_cols=[{"id":"name","header":["Name",{"content":"textFilter"}],"width":200,"sort":"string"},{"id":"type","header":["Type",{"content":"textFilter"}],"width":180,"sort":"string"},{"id":"dob","header":["DOB",{"content":"textFilter"}],"width":100,"sort":"string"},{"id":"merged_a","header":[{"text":"merged_a","colspan":3},{"text":"port"},{"content":"textFilter"}],"width":200,"sort":"string"},{"id":"merged_b","header":[null,{"text":"merged_b"},{"content":"textFilter"}],"width":200,"sort":"string"},{"id":"merged_c","header":[null,{"text":"merged_c"},{"content":"textFilter"}],"width":200,"sort":"string"},{"id":"place","header":["place",{"content":"textFilter"}],"width":300,"sort":"string"},{"id":"address","header":["address",{"content":"textFilter"}],"width":200,"sort":"string"},{"id":"phone","header":["phone",{"content":"textFilter"}],"width":200,"sort":"string"}]

my_cols.sort(function(a, b) {
  var range = ['merged_a', 'merged_b', 'merged_c'];
  if (range.indexOf(a.id) > -1 && range.indexOf(b.id) <= -1) {
    return 1
  } else {
    return 0;
  }
});

console.log(my_cols);```

Body:
I have this following JS object array whose elements are just columns of a HTML table :

var my_cols = [
  {
    "id": "name",
    "header": [
      "Name",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "type",
    "header": [
      "Type",
      {
        "content": "textFilter"
      }
    ],
    "width": 180,
    "sort": "string"
  },
  {
    "id": "dob",
    "header": [
      "DOB",
      {
        "content": "textFilter"
      }
    ],
    "width": 100,
    "sort": "string"
  },
  {
    "id": "merged_a",
    "header": [
      {
        "text": "merged_a",
        "colspan": 3
      },
      {
        "text": "port"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_b",
    "header": [
      null,
      {
        "text": "merged_b"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_c",
    "header": [
      null,
      {
        "text": "merged_c"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "place",
    "header": [
      "place",
      {
        "content": "textFilter"
      }
    ],
    "width": 300,
    "sort": "string"
  },
  {
    "id": "address",
    "header": [
      "address",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "phone",
    "header": [
      "phone",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  }
];

I want to put elements with id as 'merged_a' , 'merged_b', and 'merged_c' at the end of the entire array my_cols. I have written the below code so far, however it is not giving me the exact result:

var my_cols= [{"id":"name","header":["Name",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"type","header":["Type",{"content":"textFilter"}],"width":180,"sort":"string"},
{"id":"dob","header":["DOB",{"content":"textFilter"}],"width":100,"sort":"string"},
{"id":"merged_a","header":[{"text":"merged_a","colspan":3},{"text":"port"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_b","header":[null,{"text":"merged_b"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_c","header":[null,{"text":"merged_c"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"place","header":["place",{"content":"textFilter"}],"width":300,"sort":"string"},
{"id":"address","header":["address",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"phone","header":["phone",{"content":"textFilter"}],"width":200,"sort":"string"}];

My effort

 var my_cols = [
   { "id": "name", "header": [ "Name", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "type", "header": [ "Type", { "content": "textFilter" } ], "width": 180, "sort": "string" },
   { "id": "dob", "header": [ "DOB", { "content": "textFilter" } ], "width": 100, "sort": "string" },
   { "id": "merged_a", "header": [{ "text": "merged_a", "colspan": 3 }, { "text": "port" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_b", "header": [ null, { "text": "merged_b" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_c", "header": [ null, { "text": "merged_c" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "place", "header": [ "place", { "content": "textFilter" } ], "width": 300, "sort": "string" },
   { "id": "address", "header": [ "address", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "phone", "header": [ "phone", { "content": "textFilter" } ], "width": 200, "sort": "string" }
 ];

for (var i in my_cols) {

  var col = my_cols[i];
  var a_col;
  var b_col;
  var c_col;
  if (col.hasOwnProperty('id')) {
    if (col['id'] == 'merged_a') {
      a_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_b') {
      b_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_c') {
      c_col = my_cols.splice(i, 1);
    }
  }

}

my_cols.push(a_col);
my_cols.push(b_col);
my_cols.push(c_col);

console.log("my_cols = " + JSON.stringify(my_cols));


问:
How are people handling user authentication for web services?
I'm creating a web service to expose some data via publicly accessible APIs. At a high level, what mechanisms are people using to secure their APIs to ensure that a valid, authenticated user is making the call?

The service will be C#, the consumer could be anything (Facebook or iPhone app as well as a website) so Microsoft only solutions are out.

It's not a new problem so I assume there are some standard practices in place to deal with it but my google-fu is failing me on this one. Can the collective point me to any resources? Thanks.

答: I see that ferequently in SaaS web services is used authentication by token key over SSL - we choose this simple method in our last project over OAuth and SAML protocols. Maybe this can be usefull - sometimes simple solutions make things more scalable and over control.</p>


问:
Secondary payment processor as a fallback on declines
When doing credit card processing online you see a number of declines from the issuing bank of the end user credit card. Some of these are legitimate (internet payments blocked, no money on the account), but a number of them are also automatic fraud system erroneously kicking in.

I was toying with the idea of having a secondary payment processor, and, if the credit card is declined on my primary, retry it again with the secondary one.

Does anyone have any experience from this and/or know if it's a bad idea.

Thanks!

答: Find a payment gateway company that handle multiple merchants at the same time.  They can route certain credit cards to certain issuing banks.  Full disclosure; we do have clients that need this option as a gateway: https://tripayments.com</p>


问:
C# WPF Bind a specific object of a list to a GridViewColumn
i'm working on this since a while but didn't solved my problem.

The Case:

I have list A which contains objects of Info.
Info has the properties id, name and list B which contains objects of Details.
Details has the properties id, Name and a bool.

Is it possible to bind list A to a ListView and show the property of an object from list B where the bool is true?

edit:

List B contains more than one object but only one of the objects has a true bool, the others have false. I want to show the Name of the object with the true bool in the GridViewColumn with Binding but didn't find a way till now

答:
```<code>public class Info
{
    public int Id { get; set; }
    public string Name { get; set; }
    List<Detail> Details { get; set; }

    public string GoodDetails
    {
        get { return String.Join(",", Details.Where(x => x.Good == true).Select(y => y.Name)); }
    }
}

public class Detail
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Good { get; set; }
}
</code>```

So taking from your list of Details with the bool (which I called Good) set to true, I make a separate property called GoodDetails which pulls all of the names into a comma delimited string.  So you just bind to GoodDetails

Body:
public class Info
{
    public int Id { get; set; }
    public string Name { get; set; }
    List<Detail> Details { get; set; }

    public string GoodDetails
    {
        get { return String.Join(",", Details.Where(x => x.Good == true).Select(y => y.Name)); }
    }
}

public class Detail
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Good { get; set; }
}

So taking from your list of Details with the bool (which I called Good) set to true, I make a separate property called GoodDetails which pulls all of the names into a comma delimited string.  So you just bind to GoodDetails


问:
Jenkins LTS Docker image stuck on Jenkins 2.60.3
I have a image "x/jenkins-base" using

```<code>FROM jenkins/jenkins:lts
</code>```

which is used by another one using

```<code>FROM x/jenkins-base
</code>```

Now, despite doing

```<code>docker pull jenkins/jenkins:lts
</code>```

The image seems to be stuck at Jenkins 2.60.3.

The jenkins/jenkins Dockerfile on GitHub indeed still references 2.60.3.

So how can I update to the latest LTS (today at 2.89.1)?

答:
If their lts tag is that version; then you can't do anything about that. What you can do - is build your own image!

Take that Dockerfile you just pasted, and on line 40 you'll see they have an ARG for setting the version - that you pointed out.

You can build with a different version by using the --build-arg option in order to pass this.

```<code>docker build --build-arg 2.89.1 -t custom-jenkins .
</code>```

It looks like it then uses that variable to download the .war file from their servers, so I'd double check that file is actually available for the version you want; which looks like it is.

Body:
I have a image "x/jenkins-base" using

FROM jenkins/jenkins:lts

which is used by another one using

FROM x/jenkins-base

Now, despite doing

docker pull jenkins/jenkins:lts

The image seems to be stuck at Jenkins 2.60.3.

The jenkins/jenkins Dockerfile on GitHub indeed still references 2.60.3.

So how can I update to the latest LTS (today at 2.89.1)?

Body:
If their lts tag is that version; then you can't do anything about that. What you can do - is build your own image!

Take that Dockerfile you just pasted, and on line 40 you'll see they have an ARG for setting the version - that you pointed out.

You can build with a different version by using the --build-arg option in order to pass this.

docker build --build-arg 2.89.1 -t custom-jenkins .

It looks like it then uses that variable to download the .war file from their servers, so I'd double check that file is actually available for the version you want; which looks like it is.


问:
FileSystemWatcher Changed event is raised twice
I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event. I am using the NotifyFilters.LastWriteTime but still the event is getting fired twice. Here is the code.

```<code>public void Initialize()
{
   FileSystemWatcher _fileWatcher = new FileSystemWatcher();
  _fileWatcher.Path = "C:\\Folder";
  _fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
  _fileWatcher.Filter = "Version.txt";
  _fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
  _fileWatcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
   .......
}
</code>```

In my case the OnChanged is called twice, when I change the text file version.txt and save it.

答:
Here's my approach :

```<code>// Consider having a List<String> named _changedFiles

private void OnChanged(object source, FileSystemEventArgs e)
{
    lock (_changedFiles)
    {
        if (_changedFiles.Contains(e.FullPath))
        {
            return;
        }
        _changedFiles.Add(e.FullPath);
    }

    // do your stuff

    System.Timers.Timer timer = new Timer(1000) { AutoReset = false };
    timer.Elapsed += (timerElapsedSender, timerElapsedArgs) =>
    {
        lock (_changedFiles)
        {
            _changedFiles.Remove(e.FullPath);
        }
    };
   timer.Start();
}
</code>```

This is the solution I used to solve this issue on a project where I was sending the file as attachment in a mail.
It will easily avoid the twice fired event even with a smaller timer interval but in my case 1000 was alright since I was happier with missing few changes than with flooding the mailbox with > 1 message per second.
At least it works just fine in case several files are changed at the exact same time.

Another solution I've thought of would be to replace the list with a dictionary mapping files to their respective MD5, so you wouldn't have to choose an arbitrary interval since you wouldn't have to delete the entry but update its value, and cancel your stuff if it hasn't changed.
It has the downside of having a Dictionary growing in memory as files are monitored and eating more and more memory, but I've read somewhere that the amount of files monitored depends on the FSW's internal buffer, so maybe not that critical.
Dunno how MD5 computing time would affect your code's performances either, careful =\

Body:
I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event. I am using the NotifyFilters.LastWriteTime but still the event is getting fired twice. Here is the code.

public void Initialize()
{
   FileSystemWatcher _fileWatcher = new FileSystemWatcher();
  _fileWatcher.Path = "C:\\Folder";
  _fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
  _fileWatcher.Filter = "Version.txt";
  _fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
  _fileWatcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
   .......
}

In my case the OnChanged is called twice, when I change the text file version.txt and save it.

Body:
Here's my approach :

// Consider having a List<String> named _changedFiles

private void OnChanged(object source, FileSystemEventArgs e)
{
    lock (_changedFiles)
    {
        if (_changedFiles.Contains(e.FullPath))
        {
            return;
        }
        _changedFiles.Add(e.FullPath);
    }

    // do your stuff

    System.Timers.Timer timer = new Timer(1000) { AutoReset = false };
    timer.Elapsed += (timerElapsedSender, timerElapsedArgs) =>
    {
        lock (_changedFiles)
        {
            _changedFiles.Remove(e.FullPath);
        }
    };
   timer.Start();
}

This is the solution I used to solve this issue on a project where I was sending the file as attachment in a mail.
It will easily avoid the twice fired event even with a smaller timer interval but in my case 1000 was alright since I was happier with missing few changes than with flooding the mailbox with > 1 message per second.
At least it works just fine in case several files are changed at the exact same time.

Another solution I've thought of would be to replace the list with a dictionary mapping files to their respective MD5, so you wouldn't have to choose an arbitrary interval since you wouldn't have to delete the entry but update its value, and cancel your stuff if it hasn't changed.
It has the downside of having a Dictionary growing in memory as files are monitored and eating more and more memory, but I've read somewhere that the amount of files monitored depends on the FSW's internal buffer, so maybe not that critical.
Dunno how MD5 computing time would affect your code's performances either, careful =\


问:
wrapAll unchecks checked radio button in internet explorer 11
I have a code like this:

```<code>var root="<div id=\"editorIdPrefix01e36f3a6d53541512468193877\" contenteditable=\"true\"></div>";
var kid = "<div>" +
  "<input name=\"fieldControlId2\" id=\"fieldId2_1\" type=\"radio\" checked=\"checked\" value=\"1\">" +
  "<input name=\"fieldControlId2\" id=\"fieldId2_2\" type=\"radio\" value=\"2\">" +
"</div>";
var result = $(kid).wrapAll($(root)).parent();
alert(result.find("input").first().prop("outerHTML"));
</code>```

Notice: there is input with checked="checked" inside the kid variable. In internet explorer 11 after wrapping the input is being unchecked. Any idea what's going on (works ok in chrome/ff) ?

JsFiddle link: https://jsfiddle.net/svejdo1/81dc0gg4/2/

EDIT
Thanks for the comments, but the checked="checked" is being created automatically via various jQuery manipulations (i.e. if you use jquery to append <input checked /> to some parent element, it automatically changes to checked="checked"

Also experimentally changing the root to

```<code>var root="<div id=\"editorIdPrefix01e36f3a6d53541512468193877\"></div>";
</code>```

Fixes the issue, so at this point I suspect jQuery bug.

答:
Turns out, this is a known IE 11 serialization issue. Sample here:

var root = document.getElementById('editor');
var kid1 = document.getElementById('kid1');
var kid2 = document.getElementById('kid2');
root.appendChild(kid1);
root.appendChild(kid2);
alert(root.innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="editor" contenteditable="true" data-ckeditor="true"></div>
<div>
  <input name="fieldControlId2" id="kid1" type="radio" checked="checked" value="1">
  <input name="fieldControlId2" id="kid2" type="radio" value="2">
</div></code>```

Solution is easy, before manipulating the nodes run fixup for IE11:

```<code>if (isIe11()) {
  $(kid).find('input[checked="checked"]').each(function() {
    $(this)[0].setAttribute("checked");
  });
}
</code>```

Body:
I have a code like this:

var root="

";
var kid = "
" +
  "<input name=\"fieldControlId2\" id=\"fieldId2_1\" type=\"radio\" checked=\"checked\" value=\"1\">" +
  "<input name=\"fieldControlId2\" id=\"fieldId2_2\" type=\"radio\" value=\"2\">" +
"
";
var result = $(kid).wrapAll($(root)).parent();
alert(result.find("input").first().prop("outerHTML"));

Notice: there is input with checked="checked" inside the kid variable. In internet explorer 11 after wrapping the input is being unchecked. Any idea what's going on (works ok in chrome/ff) ?

JsFiddle link: https://jsfiddle.net/svejdo1/81dc0gg4/2/

EDIT
Thanks for the comments, but the checked="checked" is being created automatically via various jQuery manipulations (i.e. if you use jquery to append <input checked /> to some parent element, it automatically changes to checked="checked"

Also experimentally changing the root to

var root="

";

Fixes the issue, so at this point I suspect jQuery bug.

Body:
Turns out, this is a known IE 11 serialization issue. Sample here:

var root = document.getElementById('editor');
var kid1 = document.getElementById('kid1');
var kid2 = document.getElementById('kid2');
root.appendChild(kid1);
root.appendChild(kid2);
alert(root.innerHTML);

<div id="editor" contenteditable="true" data-ckeditor="true"></div>
<div>
  <input name="fieldControlId2" id="kid1" type="radio" checked="checked" value="1">
  <input name="fieldControlId2" id="kid2" type="radio" value="2">
</div>

Solution is easy, before manipulating the nodes run fixup for IE11:

if (isIe11()) {
  $(kid).find('input[checked="checked"]').each(function() {
    $(this)[0].setAttribute("checked");
  });
}


问:
parallel processing write dictionary to multiple csv files
I have a large dataframe that I would like to write to different files depending on the value in a particular column.

The first function takes a dictionary where the key is the file to write out to and the value is a numpy array which is a subset of the original dataframe.

```<code>def write_in_parallel(inputDict):
    for key,value in inputDict.items():
        df = pd.DataFrame(value)
        with open(baseDir + outDir + outputFileName + key + outputFileType, 'a') as oFile:
            data.to_csv(oFile, sep = '|', index = False, header = False)
        print("Finished writing month: " + outputFileName + key)
</code>```

function 2 takes the column values for partitioning the dataframe and the dataframe itself, and returns the dataframe.

```<code>def make_slices(files, df):
    outlist = dict()
    for item in files:
        data = np.array(df[df.iloc[:,1] == item])
        outlist[item] = data
    return outlist
</code>```

the final function uses multiprocessing to call write_in_parallel and iterates over the dictionary from make_slices, hopefully in parallel.

```<code>def make_dynamic_columns():
    perfPath = baseDir + rawDir
    perfFiles = glob.glob(perfPath + "/*" + inputFileType)
    perfFrame = pd.DataFrame()
    for file_ in perfFiles:
        df = pd.read_table(file_, delimiter = '|', header = None)

        df.fillna(missingDataChar,inplace=True)
        df.iloc[:,1] = df.iloc[:,1].astype(str)

        fileList = list(df.iloc[:, 1].astype('str').unique())

        with mp.Pool(processes=10) as pool:
            pool.map(write_in_parallel, make_slices(fileList, df))
</code>```

the error I am getting is 'str object has no attribute items' which leads me to believe that pool.map and write_in_parallel is not receiving the dictionary. I am not sure how to solve this issue. Any help is greatly appreciated.

```<code>multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 44, in mapstar
    return list(map(*args))
  File "_FHLMC_LLP_dataprep.py", line 22, in write_in_parallel
    for key,value in dict.items():
AttributeError: 'str' object has no attribute 'items'
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "_FHLMC_LLP_dataprep.py", line 59, in <module>
    make_dynamic_columns_freddie()
  File "_FHLMC_LLP_dataprep.py", line 55, in make_dynamic_columns_freddie
    pool.map(write_in_parallel, dictinput)
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 260, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 608, in get
    raise self._value
AttributeError: 'str' object has no attribute 'items'
</code>```

答:
Your problem is that make_slices returns a dictionary, not a list, and pool.map() does not like that. It just passes your dictionary keys to your workers, which means they are strings (try printing what you receive as inputDict). It is not dictionary but just keys.

```<code>def make_slices(files, df):
    outlist = []
    for item in files:
        data = df + item
        outlist.append({item: data})
    return outlist
</code>```

Could you try something like this, so that you actually return a list? Members would then be dictionary items. (I had to modify your code to just create something in data to test).

This way you can receive a key and a related data item in your worker if that is what you want to do.

Body:
I have a large dataframe that I would like to write to different files depending on the value in a particular column.

The first function takes a dictionary where the key is the file to write out to and the value is a numpy array which is a subset of the original dataframe.

def write_in_parallel(inputDict):
    for key,value in inputDict.items():
        df = pd.DataFrame(value)
        with open(baseDir + outDir + outputFileName + key + outputFileType, 'a') as oFile:
            data.to_csv(oFile, sep = '|', index = False, header = False)
        print("Finished writing month: " + outputFileName + key)

function 2 takes the column values for partitioning the dataframe and the dataframe itself, and returns the dataframe.

def make_slices(files, df):
    outlist = dict()
    for item in files:
        data = np.array(df[df.iloc[:,1] == item])
        outlist[item] = data
    return outlist

the final function uses multiprocessing to call write_in_parallel and iterates over the dictionary from make_slices, hopefully in parallel.

def make_dynamic_columns():
    perfPath = baseDir + rawDir
    perfFiles = glob.glob(perfPath + "/*" + inputFileType)
    perfFrame = pd.DataFrame()
    for file_ in perfFiles:
        df = pd.read_table(file_, delimiter = '|', header = None)

        df.fillna(missingDataChar,inplace=True)
        df.iloc[:,1] = df.iloc[:,1].astype(str)

        fileList = list(df.iloc[:, 1].astype('str').unique())

        with mp.Pool(processes=10) as pool:
            pool.map(write_in_parallel, make_slices(fileList, df))

the error I am getting is 'str object has no attribute items' which leads me to believe that pool.map and write_in_parallel is not receiving the dictionary. I am not sure how to solve this issue. Any help is greatly appreciated.

multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 44, in mapstar
    return list(map(*args))
  File "_FHLMC_LLP_dataprep.py", line 22, in write_in_parallel
    for key,value in dict.items():
AttributeError: 'str' object has no attribute 'items'
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "_FHLMC_LLP_dataprep.py", line 59, in <module>
    make_dynamic_columns_freddie()
  File "_FHLMC_LLP_dataprep.py", line 55, in make_dynamic_columns_freddie
    pool.map(write_in_parallel, dictinput)
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 260, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "/home/ssun/library/python/Python-3.5.2/build/lib/python3.5/multiprocessing/pool.py", line 608, in get
    raise self._value
AttributeError: 'str' object has no attribute 'items'

Body:
Your problem is that make_slices returns a dictionary, not a list, and pool.map() does not like that. It just passes your dictionary keys to your workers, which means they are strings (try printing what you receive as inputDict). It is not dictionary but just keys.

def make_slices(files, df):
    outlist = []
    for item in files:
        data = df + item
        outlist.append({item: data})
    return outlist

Could you try something like this, so that you actually return a list? Members would then be dictionary items. (I had to modify your code to just create something in data to test).

This way you can receive a key and a related data item in your worker if that is what you want to do.


问:
If statement syntax error in JS
I am trying to use an if/else and I can't figure out where I'm going wrong with the syntax. I want the payload to only submit school_ids if the role isn't p_admin. Thank you for your help!

```<code>const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        if (role !== 'p_admin'){
        school_ids: payload.schoolIds
        }
    })
);
</code>```

答:
You can't write if statement at the object declaration. Also you need to explicitly defined body for your arrow function. So you can do something like

```<code>const createUser = (payload) => {
   const obj = {
      username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId
   };

   if(obj.role !== 'p_admin') {
      obj.school_ids = payload.schoolIds
   }

   return request.postJSON('/register', excludeObjNullValue(obj));

}
</code>```

Title: If statement syntax error in JS

Body:
I am trying to use an if/else and I can't figure out where I'm going wrong with the syntax. I want the payload to only submit school_ids if the role isn't p_admin. Thank you for your help!

const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        if (role !== 'p_admin'){
        school_ids: payload.schoolIds
        }
    })
);

Body:
You can't write if statement at the object declaration. Also you need to explicitly defined body for your arrow function. So you can do something like

const createUser = (payload) => {
   const obj = {
      username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId
   };

   if(obj.role !== 'p_admin') {
      obj.school_ids = payload.schoolIds
   }

   return request.postJSON('/register', excludeObjNullValue(obj));

}


问:
Python coding flaw for making acronyms
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.

Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.

Code is as follows:

```<code>#ask for Input
name = input('Input words to make acroname :')

#make all in caps
name = name.upper()

#turn them in list
listname = name.split()

#cycle through
for namee in listname:
    #Get the first letter & type in same line
    print(name[0],end="")
print()

input (' press a key to move out' )
</code>```

答:
You could use str.join with a generator-expression for a one-line solution to the problem:

```<code>>>> name = "Lion head and Snake tail"
>>> ''.join(i[0].upper() for i in name.split())
'LHAST'
</code>```

why?

Well if we start from inside the generator, we are iterating through name.split(). The .split method of a str returns a list of all the different strings which have been found by splitting on what is passed into the method. The default character is a space and since we want the words, this is fine for us.

We then say that for each word i in this list, take the first character from the string with: i[0]. We then convert this to upper case with str.upper().

Then, the final step is to join all these characters together and that is done with the str.join method.

Title: Python coding flaw for making acronyms

Body:
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.

Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.

Code is as follows:

#ask for Input
name = input('Input words to make acroname :')

#make all in caps
name = name.upper()

#turn them in list
listname = name.split()

#cycle through
for namee in listname:
    #Get the first letter & type in same line
    print(name[0],end="")
print()

input (' press a key to move out' )

Body:
You could use str.join with a generator-expression for a one-line solution to the problem:

>>> name = "Lion head and Snake tail"
>>> ''.join(i[0].upper() for i in name.split())
'LHAST'

why?

Well if we start from inside the generator, we are iterating through name.split(). The .split method of a str returns a list of all the different strings which have been found by splitting on what is passed into the method. The default character is a space and since we want the words, this is fine for us.

We then say that for each word i in this list, take the first character from the string with: i[0]. We then convert this to upper case with str.upper().

Then, the final step is to join all these characters together and that is done with the str.join method.


问:
Unity - Spawn a sprite as a child of a sprite (on top of sprite)
I'm having real issues doing something I think should be quite easy so I am probably doing something very wrong!
I have a sprite on top of a space background image which is sitting within a canvas which the camera is fixed over and can be moved around. This is the main scene.

I am at the point where I want the player to be able to add a room to the station. This basically consists of another sprite which can slot into a space on top of the station sprite. I can add the sprite to the image and see it on top of the station in the sprite view but I cannot see it in the game view while the game is running. I have tried:

Having a canvas which a gameoject can be Instantiated on and then setting the image to the new room image.

Adding the sprite to the base station sprite, making sure they are on the same layer and then changing the sorting layer and order in layer and I don't think I have done this properly.

The room sprite is a child of the station and I just cannot get it to show in game. Can anyone offer any suggestions as to things I may have missed?

答:
You should not be rendering your entire game in a UI Canvas; they're designed for UI.  In order to manage rendering orders within a Canvas object, you'll have to reorder your heirarchy (which is both slow and unnecessary).

From Unity's Canvas docs:

UI elements in the Canvas are drawn in the same order they appear in
  the Hierarchy. The first child is drawn first, the second child next,
  and so on. If two UI elements overlap, the later one will appear on
  top of the earlier one.

To change which element appear on top of other elements, simply
  reorder the elements in the Hierarchy by dragging them. The order can
  also be controlled from scripting by using these methods on the
  Transform component: SetAsFirstSibling, SetAsLastSibling, and
  SetSiblingIndex.

Instead, I'd recommend going through Unity's Rogue-Like Tutorial and, if you don't feel like going through the entire tutorial, at least take a peek at the Sorting Layers portion for an understand of how the game should properly utilize SpriteRenderer.  They'll be far easier to manage.


问:
How to use enzyme for react-native with jest
I have followed –or tried to– several posts on how to do it, including the airbnb enzyme's guide for (separatedly) react-native and jest. (E.g: https://medium.com/@childsmaidment/testing-react-native-components-with-enzyme-d46bf735540#.6sxq10kgt, https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.4iqylmqh5 or How to use Jest with React Native)

But I keep getting lots of warnings (I have multiple set of concurrent tests) whenever I try to render (not mount, it crashes) any native component. Warnings are always about a native prop not being recognised.

```<code>Warning: Unknown props `focus`, `secureTextEntry` on <TextInput> tag. Remove these props from the element.
          in TextInput (created by TextInput)
          in TextInput (created by PasswordInput)
</code>```

Anyone who has a set up working, recognises how to remove the warning or how to solve it?

Thanks

答:
So I know this is a bit old but I was having issues with Jest, Enzyme, and React Native and I found this post - hopefully this solution will help.

To start with - Enzyme doesn't support mounting React Native and only supports shallow rendering. This wasn't good enough for me as I needed end-to-end tests from the component to the api which lead me to react-native-mock-render. What this does is allow us to run react native inside a browser environment which let's us test using Enzyme - all the calls for React Native and the components work as you would expect.

To set this up you'll need to install JSDOM, react-native-mock-render, Enzyme 3.0+, and Jest 20.0.0+. And then inside your jest setup file (which is specified in your package.json) include the following code:

```<code>const { JSDOM } = require('jsdom');

const jsdom = new JSDOM();
const { window } = jsdom;

function copyProps(src, target) {
  const props = Object.getOwnPropertyNames(src)
    .filter(prop => typeof target[prop] === 'undefined')
    .map(prop => Object.getOwnPropertyDescriptor(src, prop));
  Object.defineProperties(target, props);
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
copyProps(window, global);

// Setup adapter to work with enzyme 3.2.0
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

Enzyme.configure({ adapter: new Adapter() });

// Ignore React Web errors when using React Native
console.error = (message) => {
  return message;
};

require('react-native-mock-render/mock');
</code>```

And that's it - you're all setup to mount components in Enzyme and test them.

If you want to see a full sample check out react-native-mock-render-example. This is working with React 16, React Native 0.51, and Enzyme 3.2.

Body:
I have followed –or tried to– several posts on how to do it, including the airbnb enzyme's guide for (separatedly) react-native and jest. (E.g: https://medium.com/@childsmaidment/testing-react-native-components-with-enzyme-d46bf735540#.6sxq10kgt, https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.4iqylmqh5 or How to use Jest with React Native)

But I keep getting lots of warnings (I have multiple set of concurrent tests) whenever I try to render (not mount, it crashes) any native component. Warnings are always about a native prop not being recognised.

Warning: Unknown props `focus`, `secureTextEntry` on <TextInput> tag. Remove these props from the element.
          in TextInput (created by TextInput)
          in TextInput (created by PasswordInput)

Anyone who has a set up working, recognises how to remove the warning or how to solve it?

Thanks

Body:
So I know this is a bit old but I was having issues with Jest, Enzyme, and React Native and I found this post - hopefully this solution will help.

To start with - Enzyme doesn't support mounting React Native and only supports shallow rendering. This wasn't good enough for me as I needed end-to-end tests from the component to the api which lead me to react-native-mock-render. What this does is allow us to run react native inside a browser environment which let's us test using Enzyme - all the calls for React Native and the components work as you would expect.

To set this up you'll need to install JSDOM, react-native-mock-render, Enzyme 3.0+, and Jest 20.0.0+. And then inside your jest setup file (which is specified in your package.json) include the following code:

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM();
const { window } = jsdom;

function copyProps(src, target) {
  const props = Object.getOwnPropertyNames(src)
    .filter(prop => typeof target[prop] === 'undefined')
    .map(prop => Object.getOwnPropertyDescriptor(src, prop));
  Object.defineProperties(target, props);
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
copyProps(window, global);

// Setup adapter to work with enzyme 3.2.0
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

Enzyme.configure({ adapter: new Adapter() });

// Ignore React Web errors when using React Native
console.error = (message) => {
  return message;
};

require('react-native-mock-render/mock');

And that's it - you're all setup to mount components in Enzyme and test them.

If you want to see a full sample check out react-native-mock-render-example. This is working with React 16, React Native 0.51, and Enzyme 3.2.


问:
How to find x,y location of a text in pdf
Is there any tool to find the X-Y location on a text content in a pdf file ?</p>

答:
TET, the Text Extraction Toolkit from the pdflib family of products can do that. TET has a commandline interface, and it's the most powerful of all text extraction tools I'm aware of. (It can even handle ligatures...)

Geometry

  TET provides precise metrics for the text, such as the position on the page, glyph widths, and text direction. Specific areas on the page can be excluded or included in the text extraction, e.g. to ignore headers and footers or margins.


问:
Time complexity for comparing two numbers
I'm trying to establish the time complexity of an algorithm that involves comparison of numbers.

Say I have two numbers A and B, where both numbers have N number of digits individually. Assume it also holds that A<=K and B<=K.

Now I want to compare if A<=B (if A is less than or equal to B).

I suspect that the time complexity is either O(N) or O(K).

What is the correct time complexity?

答:
Knowing that A, B <= K doesn't really help.

You can conclude by comparing all digits left-to-right, until you find a difference, and this takes at worst O(N) comparisons. This is optimal as you have to look at that many digits (at worst).

You can also observe that N = O(Log K).


问:
Upload image via ModelForm in django
When I try to submit my form it says "This field is required."
for an image even though I provide the image and other details to it.

forms.py file

```<code>from django.forms import ModelForm
from .models import Status

class CreatePost(ModelForm):

    class Meta:
        model=Status
        fields = ["username","text","privacy","image"]
</code>```

models.py file

```<code>class Status(models.Model):
    title=models.CharField(max_length=20,default="updated status")
    username = models.ForeignKey('User',on_delete=models.CASCADE)
    #username = models.CharField(max_length=20)
    text = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to="media/image",null=True)
    time = models.DateTimeField(auto_now=True)
    privacy = models.CharField(max_length=5, blank=True, null=True)
    gid = models.IntegerField(blank=True, null=True)
    dp = models.SmallIntegerField(blank=True, null=True)

    class Meta:
        #unique_together = (('username', 'dp'),)
        #managed = False
        db_table = 'status'
</code>```

view.py

```<code>def create_post(request):
    form=CreatePost(request.POST or None)
    if request.method=="POST":
        if form.is_valid():
            instance=form.save(commit=False)
            instance.time=time.time()
            instance.save()
            return redirect('post',)

    return render(request,"uposts/createpost.html",{'form':form})
</code>```

createpost.html

```<code>{% extends "friendsbook/structure.html" %}
{% block content %}
<form action="" method="post">
    {%csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>

{% endblock %}
</code>```

What it said after clicking on save button

I am only taking 4 fields in form because all other fields can be null. For time field I took care of that in views.py by giving the time there.

答:
You have to modify the template like this adding multipart/form-data:

```<code><form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
</code>```

and in views.py, you can access the uploaded file using request.FILES.

Title: Upload image via ModelForm in django

Body:
When I try to submit my form it says "This field is required."
for an image even though I provide the image and other details to it.

forms.py file

from django.forms import ModelForm
from .models import Status

class CreatePost(ModelForm):

    class Meta:
        model=Status
        fields = ["username","text","privacy","image"]

models.py file

class Status(models.Model):
    title=models.CharField(max_length=20,default="updated status")
    username = models.ForeignKey('User',on_delete=models.CASCADE)
    #username = models.CharField(max_length=20)
    text = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to="media/image",null=True)
    time = models.DateTimeField(auto_now=True)
    privacy = models.CharField(max_length=5, blank=True, null=True)
    gid = models.IntegerField(blank=True, null=True)
    dp = models.SmallIntegerField(blank=True, null=True)

    class Meta:
        #unique_together = (('username', 'dp'),)
        #managed = False
        db_table = 'status'

view.py

def create_post(request):
    form=CreatePost(request.POST or None)
    if request.method=="POST":
        if form.is_valid():
            instance=form.save(commit=False)
            instance.time=time.time()
            instance.save()
            return redirect('post',)

    return render(request,"uposts/createpost.html",{'form':form})

createpost.html

{% extends "friendsbook/structure.html" %}
{% block content %}
<form action="" method="post">
    {%csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>

{% endblock %}

What it said after clicking on save button

I am only taking 4 fields in form because all other fields can be null. For time field I took care of that in views.py by giving the time there.

Body:
You have to modify the template like this adding multipart/form-data:

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>

and in views.py, you can access the uploaded file using request.FILES.


问:
Java EOF file exception
Do you have you any idea why this error is generated?

Error :-

(org.eclipse.jetty.io.EofException: Closed) org.eclipse.jetty.io.EofException: Closed at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:325) at java.io.OutputStream.write(OutputStream.java:75).

The code that cause the error is below :-

```<code>try {
    chain.doFilter(request, wrappedResponse);
    wrappedResponse.flushBuffer();
} finally {
    byte[] bytes = wrappedResponse.getCopy();
    if (wrappedResponse.getContentType() != null && wrappedResponse.getContentType().contains("text/html")) {
        if (bytes.length > 0) {
            String out = new String(bytes);
            out = out.replace(
                "</head>", "Hello</head>");

            response.getOutputStream().write(out.getBytes());
        }
    } else {
        //line
        response.getOutputStream().write(bytes);
    }
}
</code>```

答:
This is common.

The client closed the connection before the entire response was received.

Some examples: long connections, mobile connections, flaky connections, or even browsers that close the tab or navigate away before the response is received fully.).

The servlet saw this as a EOF Exception during OutputStream.write() because there's nothing to write to anymore on that connection.

Title: Java EOF file exception

Body:
Do you have you any idea why this error is generated?

Error :-

(org.eclipse.jetty.io.EofException: Closed) org.eclipse.jetty.io.EofException: Closed at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:325) at java.io.OutputStream.write(OutputStream.java:75).

The code that cause the error is below :-

try {
    chain.doFilter(request, wrappedResponse);
    wrappedResponse.flushBuffer();
} finally {
    byte[] bytes = wrappedResponse.getCopy();
    if (wrappedResponse.getContentType() != null && wrappedResponse.getContentType().contains("text/html")) {
        if (bytes.length > 0) {
            String out = new String(bytes);
            out = out.replace(
                "", "Hello");

            response.getOutputStream().write(out.getBytes());
        }
    } else {
        //line
        response.getOutputStream().write(bytes);
    }
}


问:
Looking for good bonus quiz to test efficiency (specifically efficiency related to time)
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

```<code>public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}
</code>```

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.

答: Those are good ideas.  What about having a sorting question?</p>

Body:
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.


问:
results of jquery $.get assignment to variable not usable in event listener
Can anyone identify the problem with this code and/or help to fix it?

I'm trying to preload html files, assign their html to variables, then inject them into a div after the user clicks a button.

I have it working successfully where the html files are loaded into the div on click, but I want to preload the html so the user doesn't have to wait for the external resource of the html file to load or not load if there is internet failure/ external resource fetching issues.

In the code, the alert successfully shows the html so I know at least that part works.

```<code>//IIFE
(function() {

// ^other stuff omitted

// start navButton behavior

var hatContent;
function doSomethingWithData(data) {
  hatContent = data;
  alert(data);
}

$.get('helpAndTips.html', doSomethingWithData);

function replaceNotebookContentWithVariable(content){
    $("#usersNotebook").innerHTML = content;
  }

document.getElementById('helpAndTipsButton').addEventListener("click", function(){
  replaceNotebookContentWithVariable(hatContent);
 }, false);

// end navButton behavior ____________________X

// other stuff omitted

})(); // end IIFE
</code>```

答:
Try this and see if it works better for you.

(function() {
  //save the ajax deferred
  var helpAndTips = $.get('helpAndTips.html');

  function replaceNotebookContentWithVariable(content) {
    $("#usersNotebook").innerHTML = content;
  }

  $('#helpAndTipsButton').on("click", function() {
    //call the replace with the result of the deferred whenever it gets it
    //if the deferred has already resolved this will happen immediately
    helpAndTips.then(function(hatContent) {
      replaceNotebookContentWithVariable(hatContent);
    });
  }, false);
})();```

Body:
Can anyone identify the problem with this code and/or help to fix it?

I'm trying to preload html files, assign their html to variables, then inject them into a div after the user clicks a button.

I have it working successfully where the html files are loaded into the div on click, but I want to preload the html so the user doesn't have to wait for the external resource of the html file to load or not load if there is internet failure/ external resource fetching issues.

In the code, the alert successfully shows the html so I know at least that part works.

//IIFE
(function() {

// ^other stuff omitted

// start navButton behavior

var hatContent;
function doSomethingWithData(data) {
  hatContent = data;
  alert(data);
}

$.get('helpAndTips.html', doSomethingWithData);

function replaceNotebookContentWithVariable(content){
    $("#usersNotebook").innerHTML = content;
  }

document.getElementById('helpAndTipsButton').addEventListener("click", function(){
  replaceNotebookContentWithVariable(hatContent);
 }, false);

// end navButton behavior ____________________X

// other stuff omitted

})(); // end IIFE


问:
How to sum column values from two tables and preserve another column which is only in one table
i have created tables item and item2, I know maybe it's data redundancy but i want to know how can select it, and create a view?

```<code>create table item(
id  number(10) primary key,
name varchar2(20),
mark number(10));
insert into item values(10,'Apple1',23);
insert into item values(11,'Apple2',0);
insert into item values(12,'Apple3',0);
insert into item values(13,'Apple4',0);
insert into item values(14,'Apple4',0);
insert into item values(15,'Apple4',0);
insert into item values(16,'Apple4',0);

create table  item2(
id number(10),
mark number(10));
alter table item2 add(constraint id_fk FOREIGN KEY (id) references  item(id));
Insert into  item2 values(10,1);
Insert into  item2 values(10,1);
Insert into  item2 values(11,7);
Insert into  item2 values(12,14);
</code>```

I can query both:

```<code>select * from item;

ID  Name    Mark
10  Apple1    23
11  Apple2     0
12  Apple3     0
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

select * from item2;

ID  Mark
10     1
10     1
11     7
12    14
</code>```

I want to get the result set below using the select statement sum from the item and item2 tables:

```<code>ID  Name    Mark
10  Apple1    25
11  Apple2     7
12  Apple3    14
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0
</code>```

How can I combine my queries to produce that output?

答:
You can union the two tables together on the id and mark. The name you can either add a null name column into the union and do a max/min on that field to get one value from that table. Otherwise you can union the id and marks, and then join back to the original table with the name to grab it from there and include it in the group by.</p>

```<code>select item_table.id, item_table.name, sum(mark_data_set.mark) as mark_score
from
(select
    id, mark
from item
union all
select id, mark
from item2
) mark_data_set
inner join item item_table on (mark_data_set.id = item_table.id)
group by item_table.id, item_table.name
</code>```

Body:
i have created tables item and item2, I know maybe it's data redundancy but i want to know how can select it, and create a view?

create table item(
id  number(10) primary key,
name varchar2(20),
mark number(10));
insert into item values(10,'Apple1',23);
insert into item values(11,'Apple2',0);
insert into item values(12,'Apple3',0);
insert into item values(13,'Apple4',0);
insert into item values(14,'Apple4',0);
insert into item values(15,'Apple4',0);
insert into item values(16,'Apple4',0);

create table  item2(
id number(10),
mark number(10));
alter table item2 add(constraint id_fk FOREIGN KEY (id) references  item(id));
Insert into  item2 values(10,1);
Insert into  item2 values(10,1);
Insert into  item2 values(11,7);
Insert into  item2 values(12,14);

I can query both:

select * from item;

ID  Name    Mark
10  Apple1    23
11  Apple2     0
12  Apple3     0
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

select * from item2;

ID  Mark
10     1
10     1
11     7
12    14

I want to get the result set below using the select statement sum from the item and item2 tables:

ID  Name    Mark
10  Apple1    25
11  Apple2     7
12  Apple3    14
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

How can I combine my queries to produce that output?

Body:
You can union the two tables together on the id and mark. The name you can either add a null name column into the union and do a max/min on that field to get one value from that table. Otherwise you can union the id and marks, and then join back to the original table with the name to grab it from there and include it in the group by.

select item_table.id, item_table.name, sum(mark_data_set.mark) as mark_score
from
(select
    id, mark
from item
union all
select id, mark
from item2
) mark_data_set
inner join item item_table on (mark_data_set.id = item_table.id)
group by item_table.id, item_table.name


问:
Best solution for deleting elements from a list array
So, i have an array, of a custom type, used in Angular :

```<code>List {
    task: string;
    id?: number;
    status?: boolean;
}
</code>```

Here, I want to delete elements that have List.status == true I tried 2 methods for this, the first one is very simple, it requires .filter() :

```<code>return listArray.filter(item => !item.status);
</code>```

The problem of this method, is that even though it returns the list with need elements deleted, after modifying the array, it reverts to it's sate before editing + added element, so I came to second method, it is quite longer, and requires both .filter() and .forEach() :

```<code>listArray1.filter(item => !item.status).forEach(item => {
listArray2.filter((element, index) => {
    if (element === item) {
        listArray2.splice(index, 1);
    }
});
</code>```

Is there a possible way to make this method shorter, or is there another method that will also work in angular?

答:
For those who wants to use Lodash can use: myArray = _.without(myArray, itemToRemove)

for use in angular use like bellow:

```<code>import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...
</code>```

Body:
So, i have an array, of a custom type, used in Angular :

List {
    task: string;
    id?: number;
    status?: boolean;
}

Here, I want to delete elements that have List.status == true I tried 2 methods for this, the first one is very simple, it requires .filter() :

return listArray.filter(item => !item.status);

The problem of this method, is that even though it returns the list with need elements deleted, after modifying the array, it reverts to it's sate before editing + added element, so I came to second method, it is quite longer, and requires both .filter() and .forEach() :

listArray1.filter(item => !item.status).forEach(item => {
listArray2.filter((element, index) => {
    if (element === item) {
        listArray2.splice(index, 1);
    }
});

Is there a possible way to make this method shorter, or is there another method that will also work in angular?

Body:
For those who wants to use Lodash can use: myArray = _.without(myArray, itemToRemove)

for use in angular use like bellow:

import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...