问:
VBA program getting slow
I am running this program to convert 1.5 million '.tab' format files into excel. Initially this program working fine but subsequently its speed slowing down. I tried this on several system, all behaving similarly. Also I tried to clear temp files, drive cleanup but worthless. What should I do to make it efficient?</p>

```<code>Sub runFiles()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim fso As New FileSystemObject
Dim fldr As Object

Dim fldrPath As String
Dim i As Double
Dim wb As Workbook

fldrPath = "C:\Users\skumar150\Desktop\upwork data\RAW\ACS"
Set fldr = fso.GetFolder(fldrPath)

i = 551

For Each fl In fldr.Files
    i = i + 1
    Set wb = Workbooks.Open(fldr.Path & "\" & fl.Name)
    createFile "C:\Users\skumar150\Desktop\upwork data\Excel Data1\ACS3",   wb, i
    Set wb = Nothing
    fl.Delete

 Next fl
 Application.EnableEvents = True
 Application.DisplayAlerts = True
 Application.ScreenUpdating = True

End Sub

Function createFile(fldrPath As String, ByRef wb1 As Workbook, vr As Double)
Dim wb As Workbook
Dim flName As String, fldrName As String
Dim ws As Worksheet
Dim delrow As Integer
Set wb = Workbooks.Add
Set ws = Worksheets(wb.Sheets(1).Name)

wb1.Sheets(1).Range("a1").CurrentRegion.Copy wb.Sheets(1).Range("a1")
fname = wb1.Name
wb1.Close False

With wb
    With ws
        .Names.Add "countyID", ws.Range("b2").Value
        .Names.Add "Title", ws.Range("b3").Value
        .Names.Add "rate_per", ws.Range("b4").Value
        .Names.Add "topic", ws.Range("b5").Value
        .Names.Add "yLabel", ws.Range("b6").Value
        delrow = Application.WorksheetFunction.Match("METADATA END", .Range("a:a"), 0)
        .Rows("1:" & delrow).Delete
    End With
    .Close True, fldrPath & "\__sk" & vr & "_" & fname & ".xlsx"

End With
End Function
</code>```

答:
It probably requires in depth investigation with access to the environment.
However few points:

1) Is the number of files (1.5 mln) is constant? Just to ensure, that decrease in performance is not caused by number of iterations. (Why i = 551?)

2) Can you avoid using: ".Rows("1:" & delrow).Delete"? Such range operations have impact on overall performance.

3) Try to put some timers in the code to measure how long it takes to ie. save the Excel file. If 90% of runtime is caused by file save it may be network issue (if you are running on corporate network).

Title: VBA program getting slow

Body:
I am running this program to convert 1.5 million '.tab' format files into excel. Initially this program working fine but subsequently its speed slowing down. I tried this on several system, all behaving similarly. Also I tried to clear temp files, drive cleanup but worthless. What should I do to make it efficient?

Sub runFiles()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim fso As New FileSystemObject
Dim fldr As Object

Dim fldrPath As String
Dim i As Double
Dim wb As Workbook

fldrPath = "C:\Users\skumar150\Desktop\upwork data\RAW\ACS"
Set fldr = fso.GetFolder(fldrPath)

i = 551

For Each fl In fldr.Files
    i = i + 1
    Set wb = Workbooks.Open(fldr.Path & "\" & fl.Name)
    createFile "C:\Users\skumar150\Desktop\upwork data\Excel Data1\ACS3",   wb, i
    Set wb = Nothing
    fl.Delete

 Next fl
 Application.EnableEvents = True
 Application.DisplayAlerts = True
 Application.ScreenUpdating = True

End Sub

Function createFile(fldrPath As String, ByRef wb1 As Workbook, vr As Double)
Dim wb As Workbook
Dim flName As String, fldrName As String
Dim ws As Worksheet
Dim delrow As Integer
Set wb = Workbooks.Add
Set ws = Worksheets(wb.Sheets(1).Name)

wb1.Sheets(1).Range("a1").CurrentRegion.Copy wb.Sheets(1).Range("a1")
fname = wb1.Name
wb1.Close False

With wb
    With ws
        .Names.Add "countyID", ws.Range("b2").Value
        .Names.Add "Title", ws.Range("b3").Value
        .Names.Add "rate_per", ws.Range("b4").Value
        .Names.Add "topic", ws.Range("b5").Value
        .Names.Add "yLabel", ws.Range("b6").Value
        delrow = Application.WorksheetFunction.Match("METADATA END", .Range("a:a"), 0)
        .Rows("1:" & delrow).Delete
    End With
    .Close True, fldrPath & "\__sk" & vr & "_" & fname & ".xlsx"

End With
End Function


来源: stackexchange

问:
Delete row in Google Sheets that contains any number of defined keywords
I would like to delete rows in Google Sheets that contain any keyword that is a member of some pre-defined set.  I currently have the following code:

```<code>function removeKeywords() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var rows = sheet.getDataRange();
 var numRows = rows.getNumRows();
 var values = rows.getValues();

 var rowsDeleted = 0;
 for (var i = 0; i <= numRows - 1; i++) {

 var row = values[i];

 if (row[0].indexOf("admin","conference","department") > -1) {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
 }

 }
};
</code>```

Where the keywords 'admin', 'conference', and 'department' trigger the function to delete the row.  Yet my code doesn't work.  Help would be much appreciated.

答:
See if this works</p>

```<code> function removeKeywords() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var rowsDeleted = 0;
 sheet.getDataRange()
     .getValues()
     .forEach(function (r, i) {
         if (["admin", "conference", "department"].indexOf(r[0]) > -1) {
             sheet.deleteRow((parseInt(i) + 1) - rowsDeleted);
             rowsDeleted++;
         }
     })
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to delete rows in Google Sheets that contain any keyword that is a member of some pre-defined set.  I currently have the following code:

function removeKeywords() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var rows = sheet.getDataRange();
 var numRows = rows.getNumRows();
 var values = rows.getValues();

 var rowsDeleted = 0;
 for (var i = 0; i <= numRows - 1; i++) {

 var row = values[i];

 if (row[0].indexOf("admin","conference","department") > -1) {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
 }

 }
};

Where the keywords 'admin', 'conference', and 'department' trigger the function to delete the row.  Yet my code doesn't work.  Help would be much appreciated.

Body:
See if this works

 function removeKeywords() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var rowsDeleted = 0;
 sheet.getDataRange()
     .getValues()
     .forEach(function (r, i) {
         if (["admin", "conference", "department"].indexOf(r[0]) > -1) {
             sheet.deleteRow((parseInt(i) + 1) - rowsDeleted);
             rowsDeleted++;
         }
     })
}


问:
Scalable Flask server
Is it possible to scale a Flask server?

I have a python server which uses Flask, when it gets a request from my web app, it does something according to the endpoint. The issue is that this something can take some time.

I would like to process multiple requests in parallel. In other words, scale it up.

When I send a request one after the other, it just waits for the first one to complete before attending the other, any way to run those in parallel?

答:
I assume you are using the flask builtin 'testing' server, which is really not designed for a production workload.

What you want to do is run your application on a proper web server such as Apache or Nginx that supports execution of python, these will easily handle many simultaneous connections

I would start here:
http://flask.pocoo.org/docs/0.12/deploying/

in particular looking at these sections

uWSGI

FastCGI

Title: Scalable Flask server


问:
python xml print particular child node based on sub-element text
I have a sample XML like below:

```<code><data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
    <sessions xmlns="com:infinera:common:session">
        <session>
            <MoId>admin_12</MoId>
            <AccountName>admin</AccountName>
            <ProtocolType>SSH</ProtocolType>
            <MgmtAppType>CLI</MgmtAppType>
            <AuthenticationType>LOCAL</AuthenticationType>
        </session>
        <session>
            <MoId>admin_13</MoId>
            <AccountName>admin</AccountName>
            <ProtocolType>TELNET</ProtocolType>
            <MgmtAppType>TL1</MgmtAppType>
            <AuthenticationType>LOCAL</AuthenticationType>
        <session>
    </sessions>
</data>
</code>```

Here i want to iterate through the children to find if value of MgmtAppType is TL1 and if it is I want to print all the elements associated it i.e. MoID, AccountName, ProtocolType, MgmtAppType, AuthenticationType.
I tried with below code, but this prints only the value of MgmtAppType

```<code>import xml.etree.ElementTree as ET
root = ET.parse('C:\\session.xml')
roots = root.getroot()
for sess in roots.iter():
    if (sess.tag == "{com:infinera:common:session}MgmtAppType") and (sess.text == "TL1"):
            for chd in sess.iter():
                    print chd.text
</code>```

How would i print all the elements of particular child node based on the search?

答:
A better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions:

```<code>import xml.etree.ElementTree as ET

root = ET.parse('C:\\session.xml').getroot()
ns = {'common': 'com:infinera:common:session'}
for session in root.findall('common:sessions/common:session[common:MgmtAppType="TL1"]', ns):
    print([el.text for el in list(session)])
</code>```

The output (as a list of consecutive elements values):

```<code>['admin_13', 'admin', 'TELNET', 'TL1', 'LOCAL']
</code>```

https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces

Body:
I have a sample XML like below:

<data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
    <sessions xmlns="com:infinera:common:session">
        <session>
            <MoId>admin_12</MoId>
            <AccountName>admin</AccountName>
            <ProtocolType>SSH</ProtocolType>
            <MgmtAppType>CLI</MgmtAppType>
            <AuthenticationType>LOCAL</AuthenticationType>
        </session>
        <session>
            <MoId>admin_13</MoId>
            <AccountName>admin</AccountName>
            <ProtocolType>TELNET</ProtocolType>
            <MgmtAppType>TL1</MgmtAppType>
            <AuthenticationType>LOCAL</AuthenticationType>
        <session>
    </sessions>
</data>

Here i want to iterate through the children to find if value of MgmtAppType is TL1 and if it is I want to print all the elements associated it i.e. MoID, AccountName, ProtocolType, MgmtAppType, AuthenticationType.
I tried with below code, but this prints only the value of MgmtAppType

import xml.etree.ElementTree as ET
root = ET.parse('C:\\session.xml')
roots = root.getroot()
for sess in roots.iter():
    if (sess.tag == "{com:infinera:common:session}MgmtAppType") and (sess.text == "TL1"):
            for chd in sess.iter():
                    print chd.text

How would i print all the elements of particular child node based on the search?

Body:
A better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions:

import xml.etree.ElementTree as ET

root = ET.parse('C:\\session.xml').getroot()
ns = {'common': 'com:infinera:common:session'}
for session in root.findall('common:sessions/common:session[common:MgmtAppType="TL1"]', ns):
    print([el.text for el in list(session)])

The output (as a list of consecutive elements values):

['admin_13', 'admin', 'TELNET', 'TL1', 'LOCAL']

https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces


问:
Setting TDBGrid visible rows
I want to adjust a TDBGrid height given a VisibleRows parameter. the grid may or may not have titles.

Suppose I select 100 records from the db, but I want the grid height to adjust to show the first 10 rows (make them visible). the dataset will still hold 100 records.

i.e.

```<code>procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
begin
  ...
  DBGrid.Height := ???
end;
</code>```

I know how to get the visible rows:

```<code>type
  TCustomGridHack = class(TCustomGrid);

function GetVisibleRows(DBGrid: TCustomDBGrid): Integer;
begin
   Result := TCustomGridHack(DBGrid).VisibleRowCount;
end;
</code>```

But, is there a way to set the VisibleRowCount?

答:
This seems to work (maybe could be optimized more):

```<code>type
  TCustomDBGridHack = class(TCustomDBGrid);

procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
var
  TitleHeight, RowHeight: Integer;
begin
  with TCustomDBGridHack(DBGrid) do
  begin
    if dgTitles in Options then
    begin
      TitleHeight := RowHeights[0] + GridLineWidth;
      RowHeight := RowHeights[1] + GridLineWidth;
    end
    else
    begin
      TitleHeight := 0;
      RowHeight := RowHeights[0] + GridLineWidth;
    end;
  end;
  DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1;
end;
</code>```

Or by using TGridDrawInfo as suggested by @nil. It produces more accurate results  (I modified it a bit):

```<code>procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
var
  DrawInfo: TGridDrawInfo;
  TitleHeight, RowHeight: Integer;
begin
  with TCustomDBGridHack(DBGrid) do
  begin
    CalcDrawInfo(DrawInfo);
    TitleHeight := DrawInfo.Vert.FixedBoundary;
    RowHeight := RowHeights[DrawInfo.Vert.FirstGridCell] + DrawInfo.Vert.EffectiveLineWidth;
  end;
  DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1;
end;
</code>```

As mentioned by @nil, RowHeight could be also calculated with:

```<code>RowHeight := DrawInfo.Vert.GetExtent(DrawInfo.Vert.FirstGridCell) + DrawInfo.Vert.EffectiveLineWidth;
</code>```

I haven't noticed any difference though. (should be further investigated).

The above could be further improved to make the TDBGrid scroll-bars adjust better:

```<code>procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
var
  DrawInfo: TGridDrawInfo;
  TitleHeight, RowHeight: Integer;
  HasActiveDataSet: Boolean;
begin
  if VisibleRows < 0 then VisibleRows := 0;
  HasActiveDataSet := Assigned(DBGrid.DataSource) and
    Assigned(DBGrid.DataSource.DataSet) and
    DBGrid.DataSource.DataSet.Active;
  if HasActiveDataSet then
    DBGrid.DataSource.DataSet.DisableControls;
  try
    with TCustomDBGridHack(DBGrid) do
    begin
      CalcDrawInfo(DrawInfo);
      TitleHeight :=  DrawInfo.Vert.FixedBoundary;
      RowHeight := RowHeights[DrawInfo.Vert.FirstGridCell] + DrawInfo.Vert.EffectiveLineWidth;
    end;
    DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1;
  finally
    if HasActiveDataSet then
      DBGrid.DataSource.DataSet.EnableControls;
  end;
end;
</code>```

Title: Setting TDBGrid visible rows

Body:
I want to adjust a TDBGrid height given a VisibleRows parameter. the grid may or may not have titles.

Suppose I select 100 records from the db, but I want the grid height to adjust to show the first 10 rows (make them visible). the dataset will still hold 100 records.

i.e.

procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
begin
  ...
  DBGrid.Height := ???
end;

I know how to get the visible rows:

type
  TCustomGridHack = class(TCustomGrid);

function GetVisibleRows(DBGrid: TCustomDBGrid): Integer;
begin
   Result := TCustomGridHack(DBGrid).VisibleRowCount;
end;

But, is there a way to set the VisibleRowCount?

Body:
This seems to work (maybe could be optimized more):

type
  TCustomDBGridHack = class(TCustomDBGrid);

procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
var
  TitleHeight, RowHeight: Integer;
begin
  with TCustomDBGridHack(DBGrid) do
  begin
    if dgTitles in Options then
    begin
      TitleHeight := RowHeights[0] + GridLineWidth;
      RowHeight := RowHeights[1] + GridLineWidth;
    end
    else
    begin
      TitleHeight := 0;
      RowHeight := RowHeights[0] + GridLineWidth;
    end;
  end;
  DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1;
end;

Or by using TGridDrawInfo as suggested by @nil. It produces more accurate results  (I modified it a bit):

procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
var
  DrawInfo: TGridDrawInfo;
  TitleHeight, RowHeight: Integer;
begin
  with TCustomDBGridHack(DBGrid) do
  begin
    CalcDrawInfo(DrawInfo);
    TitleHeight := DrawInfo.Vert.FixedBoundary;
    RowHeight := RowHeights[DrawInfo.Vert.FirstGridCell] + DrawInfo.Vert.EffectiveLineWidth;
  end;
  DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1;
end;

As mentioned by @nil, RowHeight could be also calculated with:

RowHeight := DrawInfo.Vert.GetExtent(DrawInfo.Vert.FirstGridCell) + DrawInfo.Vert.EffectiveLineWidth;

I haven't noticed any difference though. (should be further investigated).

The above could be further improved to make the TDBGrid scroll-bars adjust better:

procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
var
  DrawInfo: TGridDrawInfo;
  TitleHeight, RowHeight: Integer;
  HasActiveDataSet: Boolean;
begin
  if VisibleRows < 0 then VisibleRows := 0;
  HasActiveDataSet := Assigned(DBGrid.DataSource) and
    Assigned(DBGrid.DataSource.DataSet) and
    DBGrid.DataSource.DataSet.Active;
  if HasActiveDataSet then
    DBGrid.DataSource.DataSet.DisableControls;
  try
    with TCustomDBGridHack(DBGrid) do
    begin
      CalcDrawInfo(DrawInfo);
      TitleHeight :=  DrawInfo.Vert.FixedBoundary;
      RowHeight := RowHeights[DrawInfo.Vert.FirstGridCell] + DrawInfo.Vert.EffectiveLineWidth;
    end;
    DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1;
  finally
    if HasActiveDataSet then
      DBGrid.DataSource.DataSet.EnableControls;
  end;
end;


问:
How cookies are managed by networking code
I was recently migrating over from C# and looking to create some of my old applications. As such I have needed to find a way to manage sessions within Go web requests. I found a solution in the form of this code:

```<code>// Jar is session object struct - cookie jar including mutex for syncing
type Jar struct {
    sync.Mutex
    cookies map[string][]*http.Cookie
}

// NewJar is a function for creating cookie jar for use
func NewJar() *Jar {
    jar := new(Jar)
    jar.cookies = make(map[string][]*http.Cookie)
    return jar
}

// SetCookies sets the cookies for the jar
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    jar.Lock()
    if _, ok := jar.cookies[u.Host]; ok {
        for _, c := range cookies {
            jar.cookies[u.Host] = append(jar.cookies[u.Host], c)
        }
    } else {
        jar.cookies[u.Host] = cookies
    }
    jar.Unlock()
}

// Cookies returns cookies for each host
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
    return jar.cookies[u.Host]
}

// NewJarClient creates new client, utilising a NewJar()
func NewJarClient() *http.Client {

    proxyURL, _ := url.Parse("http://127.0.0.1:8888")

    tr := &http.Transport{
        MaxIdleConns:       10,
        IdleConnTimeout:    30 * time.Second,
        DisableCompression: true,
        Proxy:              http.ProxyURL(proxyURL),
    }

    return &http.Client{
        Jar:       NewJar(),
        Transport: tr,
    }
}
</code>```

The problem I'm having is in understanding how this works. I create a client doing the following

```<code>client := NewJarClient()
</code>```

but then when I issue networking fuctions using it such as a get request, the cookies automatically carry on and it all works as planned. The problem is  Ihave no idea why. I see no mention of methods such as the Cookies one or the SetCookies one ever being called and it seems to just handle each one by magically running the functions. Could someone annotate or explain the given methods line by line or in a way so that they'd make better sense to me coming over from a C# background. Thanks :)

答:
Due to misinformation in the form of a few dated blog posts, I came to the impression that I was unable to maintain cookies across requests in go - for some weird reason. Having thought that, I researched and looked into creating my own implementation which ca be seen above. It's been brought to my attention that my implementation is completely broken and flawed and that the standard http library itself can perfectly handle maintaining cookies, simply by including a value for the Jar when creating a client. For example:

```<code>jar, _ := cookiejar.New(nil)

proxyURL, _ := url.Parse("http://127.0.0.1:8888")

tr := &http.Transport{
    MaxIdleConns:       10,
    IdleConnTimeout:    30 * time.Second,
    DisableCompression: true,
    Proxy:              http.ProxyURL(proxyURL),
}

c := &http.Client{
    Jar:       jar,
    Transport: tr,
}
</code>```

Body:
I was recently migrating over from C# and looking to create some of my old applications. As such I have needed to find a way to manage sessions within Go web requests. I found a solution in the form of this code:

// Jar is session object struct - cookie jar including mutex for syncing
type Jar struct {
    sync.Mutex
    cookies map[string][]*http.Cookie
}

// NewJar is a function for creating cookie jar for use
func NewJar() *Jar {
    jar := new(Jar)
    jar.cookies = make(map[string][]*http.Cookie)
    return jar
}

// SetCookies sets the cookies for the jar
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    jar.Lock()
    if _, ok := jar.cookies[u.Host]; ok {
        for _, c := range cookies {
            jar.cookies[u.Host] = append(jar.cookies[u.Host], c)
        }
    } else {
        jar.cookies[u.Host] = cookies
    }
    jar.Unlock()
}

// Cookies returns cookies for each host
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
    return jar.cookies[u.Host]
}

// NewJarClient creates new client, utilising a NewJar()
func NewJarClient() *http.Client {

    proxyURL, _ := url.Parse("http://127.0.0.1:8888")

    tr := &http.Transport{
        MaxIdleConns:       10,
        IdleConnTimeout:    30 * time.Second,
        DisableCompression: true,
        Proxy:              http.ProxyURL(proxyURL),
    }

    return &http.Client{
        Jar:       NewJar(),
        Transport: tr,
    }
}

The problem I'm having is in understanding how this works. I create a client doing the following

client := NewJarClient()

but then when I issue networking fuctions using it such as a get request, the cookies automatically carry on and it all works as planned. The problem is  Ihave no idea why. I see no mention of methods such as the Cookies one or the SetCookies one ever being called and it seems to just handle each one by magically running the functions. Could someone annotate or explain the given methods line by line or in a way so that they'd make better sense to me coming over from a C# background. Thanks :)

Body:
Due to misinformation in the form of a few dated blog posts, I came to the impression that I was unable to maintain cookies across requests in go - for some weird reason. Having thought that, I researched and looked into creating my own implementation which ca be seen above. It's been brought to my attention that my implementation is completely broken and flawed and that the standard http library itself can perfectly handle maintaining cookies, simply by including a value for the Jar when creating a client. For example:

jar, _ := cookiejar.New(nil)

proxyURL, _ := url.Parse("http://127.0.0.1:8888")

tr := &http.Transport{
    MaxIdleConns:       10,
    IdleConnTimeout:    30 * time.Second,
    DisableCompression: true,
    Proxy:              http.ProxyURL(proxyURL),
}

c := &http.Client{
    Jar:       jar,
    Transport: tr,
}


问:
AWS python lambda function:No module named requests
I am fairly new to AWS and I am having some issues. Here is my code:

```<code>from __future__ import print_function
from urllib2 import Request, urlopen, URLError
import requests
import boto3
import json

def lambda_handler(event, context):
    url = "https://globalcurrencies.xignite.com/xGlobalCurrencies.json/GetHistoricalRatesRange?Symbol=BTCUSD&PriceType=Mid&StartDate=01/01/2017&EndDate=10/27/2017&PeriodType=Daily&FixingTime=22:00&_token=some_token_xyz"
    response = requests.get(url).json()
    # print json.dumps(response, indent=4) # gives a syntax error
    return response
</code>```

Name of the file is lambda_function.py; I have checked similar problems on stackoverflow and some mentioned that I have to change the file naming. But it didn't help. Here is how python method was named:

                                                                             Here is the error I am getting:
START RequestId: cf24e9be-bbef-11e7-97b4-d9b586307f3e Version: $LATEST
Unable to import module 'lambda_function': No module named requests
And when try to print it gives me a syntax error. Sorry for the formatting. Any suggestions?

答:
This is because it is missing the requests library when running in the lambda - its likely that its installed globally on your local machine.  If you run:

pip install requests -t .

in the same directory as your source code it will install the requests package in that directory then you can upload it to lambda along with your lambda_function.py.  You may need to do the same for boto3 and json:

pip install boto3 -t .

    pip install json -t .

Body:
I am fairly new to AWS and I am having some issues. Here is my code:

from __future__ import print_function
from urllib2 import Request, urlopen, URLError
import requests
import boto3
import json

def lambda_handler(event, context):
    url = "https://globalcurrencies.xignite.com/xGlobalCurrencies.json/GetHistoricalRatesRange?Symbol=BTCUSD&PriceType=Mid&StartDate=01/01/2017&EndDate=10/27/2017&PeriodType=Daily&FixingTime=22:00&_token=some_token_xyz"
    response = requests.get(url).json()
    # print json.dumps(response, indent=4) # gives a syntax error
    return response

Name of the file is lambda_function.py; I have checked similar problems on stackoverflow and some mentioned that I have to change the file naming. But it didn't help. Here is how python method was named:

                                                                             Here is the error I am getting:
START RequestId: cf24e9be-bbef-11e7-97b4-d9b586307f3e Version: $LATEST
Unable to import module 'lambda_function': No module named requests
And when try to print it gives me a syntax error. Sorry for the formatting. Any suggestions?


问:
Separate optimizer for discriminator and the rest of the model in adversarial setting
I have a model with the following components.

embedding layer

encoder

generator

discriminator

feed-forward neural network

I want to define two optimizers. One for the discriminator only and one for the rest. I am doing the following.

```<code>optimizers = []
model_params = chain(model.embedding.parameters(), model.encoder.parameters(),
                            model.generator.parameters(), model.ffnn.parameters())
optimizers.append(optim.Adam(model_params, args.lr))
optimizers.append(optim.Adam(model.discriminator.parameters(), args.lr))
</code>```

Is there any better way to do the same? For example, can I take the difference between model.parameters() and model.discriminator.parameters()? If yes, how can I do that?

答: no, because model.parameters() returns a generator. If you want to modify a generator like you want it you have to convert it to a list anyway.</p>

Body:
I have a model with the following components.

embedding layer

encoder

generator

discriminator

feed-forward neural network

I want to define two optimizers. One for the discriminator only and one for the rest. I am doing the following.

optimizers = []
model_params = chain(model.embedding.parameters(), model.encoder.parameters(),
                            model.generator.parameters(), model.ffnn.parameters())
optimizers.append(optim.Adam(model_params, args.lr))
optimizers.append(optim.Adam(model.discriminator.parameters(), args.lr))

Is there any better way to do the same? For example, can I take the difference between model.parameters() and model.discriminator.parameters()? If yes, how can I do that?


问:
Android: Add two text views programmatically
I am trying  to add Views to a linear layout programmatically.

```<code>    LinearLayout layout     = (LinearLayout) findViewById(R.id.info);
    String [] informations  = topOffer.getInformations();
    TextView informationView;
    View line = new View(this);
    line.setLayoutParams(new LayoutParams(1, LayoutParams.FILL_PARENT));
    line.setBackgroundColor(R.color.solid_history_grey);
    for (int i = 0; i < informations.length; i++) {
        informationView = new TextView(this);
        informationView.setText(informations[i]);
        layout.addView(informationView, 0);
        layout.addView(line, 1);
    }
</code>```

First, I have only added the informationsView, and everything worked fine. Butt after adding also the line-View, it crashed with the following error:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

So I tried addView(View v, int index), but it crashed with the same message...

Has somebody a solution?

Thanks,
Martin

答:
You can't add the same child view multiple times in the same parent view.
You need to create a new view or inflate a new view every time.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying  to add Views to a linear layout programmatically.

    LinearLayout layout     = (LinearLayout) findViewById(R.id.info);
    String [] informations  = topOffer.getInformations();
    TextView informationView;
    View line = new View(this);
    line.setLayoutParams(new LayoutParams(1, LayoutParams.FILL_PARENT));
    line.setBackgroundColor(R.color.solid_history_grey);
    for (int i = 0; i < informations.length; i++) {
        informationView = new TextView(this);
        informationView.setText(informations[i]);
        layout.addView(informationView, 0);
        layout.addView(line, 1);
    }

First, I have only added the informationsView, and everything worked fine. Butt after adding also the line-View, it crashed with the following error:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

So I tried addView(View v, int index), but it crashed with the same message...

Has somebody a solution?

Thanks,
Martin


问:
MarkdownDeep AutoHeadingIDs are not working
I'm working with MarkdownDeep in my WebSite:

```<code>public static MvcHtmlString FromMarkdown(this HtmlHelper helper, string value)
{
    var md = new Markdown
    {
        ExtraMode = true,
        SafeMode = true,
        NewWindowForExternalLinks = true,
        MarkdownInHtml = true,
        AutoHeadingIDs = true
    };

    text = md.Transform(value);

    return MvcHtmlString.Create(text);
}
</code>```

My problem here is, that headings still not get IDs since I want to work with anchors.
Anyone an idea?

答:
The problem was that you can't use property SafeMode together with AutoHeadingIDs. It's not documented but it solved my problem. Initialization now looks:

```<code>var md = new Markdown
{
    ExtraMode = true,
    NewWindowForExternalLinks = true,
    MarkdownInHtml = true,
    AutoHeadingIDs = true
};
</code>```

Body:
I'm working with MarkdownDeep in my WebSite:

public static MvcHtmlString FromMarkdown(this HtmlHelper helper, string value)
{
    var md = new Markdown
    {
        ExtraMode = true,
        SafeMode = true,
        NewWindowForExternalLinks = true,
        MarkdownInHtml = true,
        AutoHeadingIDs = true
    };

    text = md.Transform(value);

    return MvcHtmlString.Create(text);
}

My problem here is, that headings still not get IDs since I want to work with anchors.
Anyone an idea?

Body:
The problem was that you can't use property SafeMode together with AutoHeadingIDs. It's not documented but it solved my problem. Initialization now looks:

var md = new Markdown
{
    ExtraMode = true,
    NewWindowForExternalLinks = true,
    MarkdownInHtml = true,
    AutoHeadingIDs = true
};


问:
how i can place 50% control over the tool bar in xamarin forms?
how i can place 50% of control just like 50 % image view over the menu bar and rest 50% of control over the page just as in screenshot ?

I tried to achieve this using relative layout but could not able to do that..
please anyone know help me to design such UI.

```<code>        <Button  HeightRequest="50" WidthRequest="50" BorderRadius="35" BackgroundColor="Aqua"
            RelativeLayout.XConstraint= "{ConstraintExpression Type=RelativeToParent, Property=Width, Factor = .5}"
            RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor = -.05}" />
</code>```

答:
You can do this using absolute layout

```<code>          <AbsoluteLayout BackgroundColor="white">
                <BoxView BackgroundColor="Aqua" AbsoluteLayout.LayoutBounds="0
                    0,1,100" AbsoluteLayout.LayoutFlags="XProportional,YProportional,WidthProportional" />
                <Button BackgroundColor="White"
                    AbsoluteLayout.LayoutBounds=".5,75,70,70" AbsoluteLayout.LayoutFlags="XProportional" BorderRadius="35" />
                <Button BackgroundColor="Red" AbsoluteLayout.LayoutBounds=".5
                    80,60,60" AbsoluteLayout.LayoutFlags="XProportional" BorderRadius="30" />
            </AbsoluteLayout>
</code>```

Reference

Body:
how i can place 50% of control just like 50 % image view over the menu bar and rest 50% of control over the page just as in screenshot ?

I tried to achieve this using relative layout but could not able to do that..
please anyone know help me to design such UI.

        <Button  HeightRequest="50" WidthRequest="50" BorderRadius="35" BackgroundColor="Aqua"
            RelativeLayout.XConstraint= "{ConstraintExpression Type=RelativeToParent, Property=Width, Factor = .5}"
            RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor = -.05}" />

Body:
You can do this using absolute layout

          <AbsoluteLayout BackgroundColor="white">
                <BoxView BackgroundColor="Aqua" AbsoluteLayout.LayoutBounds="0
                    0,1,100" AbsoluteLayout.LayoutFlags="XProportional,YProportional,WidthProportional" />
                <Button BackgroundColor="White"
                    AbsoluteLayout.LayoutBounds=".5,75,70,70" AbsoluteLayout.LayoutFlags="XProportional" BorderRadius="35" />
                <Button BackgroundColor="Red" AbsoluteLayout.LayoutBounds=".5
                    80,60,60" AbsoluteLayout.LayoutFlags="XProportional" BorderRadius="30" />
            </AbsoluteLayout>

Reference


问:
Allow chart overflow over plot area
Is there anyway to allow highcharts overflow over plotarea?

Fiddle Bubbles clipped

```<code> Highcharts.chart('container', {

"chart":{"type":"bubble"},
"plotOptions":{"bubble":{"minSize":9,"maxSize":30}},

"xAxis":{"min":0},

"series":[
   {"name":"Acero", "data":[[604807,9091,19235608]],"color":"#ff0000"},
   {"name":"Xleado","data":[[189725,281,2006799]],"color":"#33A1DE"},
     {"name":"Aleado","data":[[40261840,85391,156180]],"color":"#104E8B"}
         ]
});
</code>```

答:
SVG clip-path attribute is responsible for hiding some parts of the bubbles.

It can be easily disabled via CSS:

```<code>.highcharts-series {
  clip-path: none;
}
</code>```

Live demo: http://jsfiddle.net/kkulig/h5yymapp/

Title: Allow chart overflow over plot area

Body:
Is there anyway to allow highcharts overflow over plotarea?

Fiddle Bubbles clipped

 Highcharts.chart('container', {

"chart":{"type":"bubble"},
"plotOptions":{"bubble":{"minSize":9,"maxSize":30}},

"xAxis":{"min":0},

"series":[
   {"name":"Acero", "data":[[604807,9091,19235608]],"color":"#ff0000"},
   {"name":"Xleado","data":[[189725,281,2006799]],"color":"#33A1DE"},
     {"name":"Aleado","data":[[40261840,85391,156180]],"color":"#104E8B"}
         ]
});

Body:
SVG clip-path attribute is responsible for hiding some parts of the bubbles.

It can be easily disabled via CSS:

.highcharts-series {
  clip-path: none;
}

Live demo: http://jsfiddle.net/kkulig/h5yymapp/


问:
Disable compiling including lint or linter
Im having issues building my website (built from vue-cli scaffolding) which is meant to also be homework for students.

Linter rules such as tabulation and extra spaces are causing the app to display them as a fatal error.

Code and syntax violations sure why not but spaces and tabs?

This will be impossible for the students.

How can I decide what linter rules get included in the webpack/babel compilation and which ones are ignored?

答:
Take a look at the eslint config page. You'll be able to configure the rules using .eslintrc.js. You can also define paths that won't be linted using a .eslintignore file.

As an example, this is the one I'm using in my current project:

```<code>module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    sourceType: 'module'
  },
  env: {
    browser: true
  },
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  extends: [
    'standard'
  ],
  // required to lint *.vue files
  plugins: [
    'html',
    'import'
  ],
  globals: {
    'cordova': true,
    'DEV': true,
    'PROD': true,
    '__THEME': true
  },
  // add your custom rules here
  'rules': {
    // allow paren-less arrow functions
    'arrow-parens': 0,
    'one-var': 0,
    'import/first': 0,
    'import/named': 2,
    'import/namespace': 2,
    'import/default': 2,
    'import/export': 2,
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
    'brace-style': [2, '1tbs', { 'allowSingleLine': true }],
    'no-return-assign': 0
  }
}
</code>```

And my ignore file:

```<code>build/*.js
config/*.js
dist/*.js
</code>```

Body:
Take a look at the eslint config page. You'll be able to configure the rules using .eslintrc.js. You can also define paths that won't be linted using a .eslintignore file.

As an example, this is the one I'm using in my current project:

module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    sourceType: 'module'
  },
  env: {
    browser: true
  },
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  extends: [
    'standard'
  ],
  // required to lint *.vue files
  plugins: [
    'html',
    'import'
  ],
  globals: {
    'cordova': true,
    'DEV': true,
    'PROD': true,
    '__THEME': true
  },
  // add your custom rules here
  'rules': {
    // allow paren-less arrow functions
    'arrow-parens': 0,
    'one-var': 0,
    'import/first': 0,
    'import/named': 2,
    'import/namespace': 2,
    'import/default': 2,
    'import/export': 2,
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
    'brace-style': [2, '1tbs', { 'allowSingleLine': true }],
    'no-return-assign': 0
  }
}

And my ignore file:

build/*.js
config/*.js
dist/*.js


问:
Kubernetes service with clustered PODs in active/standby
Apologies for not keeping this short, as any such attempt would make me miss-out on some important details of my problem.

I have a legacy Java application which works in a active/standby mode in a clustered environment to expose certain RESTful WebServices via a predefined port.

If there are two nodes in my app cluster, at any point in time only one would be in Active mode, and the other in Passive mode, and the requests are always served by the node with app running in Active mode. 'Active' and 'Passive' are just roles, the app as such would be running on both nodes. The Active and Passive instances communicate with each other through this same predetermined port.

Suppose I have a two node cluster with one instance of my application running on each node, then one of the instance would initially be active and the other will be passive. If for some reason the active node goes for a toss for some reason, the app instance in other node identifies this using some heartbeat mechanism, takes over the control and becomes the new active. When the old active comes back up it detects the other guy has owned up the new Active role, hence it goes into Passive mode.

The application manages to provide RESTful webservices on the same endpoint IP irrespective of which node is running the app in 'Active' mode by using a cluster IP, which piggy-backs on the active instance, so the cluster IP switches over to whichever node is running the app in Active mode.

I am trying to containerize this app and run this in a Kubernetes cluster for scale and ease of deployment. I am able to containerize and able to deploy it as a POD in a Kubernetes cluster.

In order to bring in the Active/Passive role here, I am running two instances of this POD, each pinned to a separate K8S nodes using node affinity (each node is labeled as either active or passive, and POD definitions pin on these labels), and clustering them up using my app's clustering mechanism whereas only one will be active and the other will be passive.

I am exposing the REST service externally using K8S Service semantics by making use of the NodePort, and exposing the REST WebService via a NodePort on the master node.

Here's my yaml file content:

```<code>apiVersion: v1
kind: Service
metadata:
  name: myapp-service
  labels:
    app: myapp-service
spec:
  type: NodePort
  ports:
    - port: 8443
      nodePort: 30403
  selector:
    app: myapp

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: active
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - active
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: active
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: passive
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - passive
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: passive
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage
</code>```

Everything seems working fine, except that since both PODs are exposing the web service via same port, the K8S Service is routing the incoming requests to one of these PODS in a random fashion. Since my REST WebService endpoints work only on Active node, the service requests work via K8S Service resource only when the request is getting routed to the POD with app in Active role. If at any point in time the K8S Service happens to route the incoming request to POD with app in passive role, the service is inaccessible/not served.

How do I make this work in such a way that the K8S service always routes the requests to POD with app in Active role? Is this something doable in Kubernetes or I'm aiming for too much?

Thank you for your time!

答: You can use a readiness probe in conjunction with election container. Election will always elect one master from the election pool, and if you make sure only that pod is marked as ready... only that pod will recieve traffic.</p>

Body:
Apologies for not keeping this short, as any such attempt would make me miss-out on some important details of my problem.

I have a legacy Java application which works in a active/standby mode in a clustered environment to expose certain RESTful WebServices via a predefined port.

If there are two nodes in my app cluster, at any point in time only one would be in Active mode, and the other in Passive mode, and the requests are always served by the node with app running in Active mode. 'Active' and 'Passive' are just roles, the app as such would be running on both nodes. The Active and Passive instances communicate with each other through this same predetermined port.

Suppose I have a two node cluster with one instance of my application running on each node, then one of the instance would initially be active and the other will be passive. If for some reason the active node goes for a toss for some reason, the app instance in other node identifies this using some heartbeat mechanism, takes over the control and becomes the new active. When the old active comes back up it detects the other guy has owned up the new Active role, hence it goes into Passive mode.

The application manages to provide RESTful webservices on the same endpoint IP irrespective of which node is running the app in 'Active' mode by using a cluster IP, which piggy-backs on the active instance, so the cluster IP switches over to whichever node is running the app in Active mode.

I am trying to containerize this app and run this in a Kubernetes cluster for scale and ease of deployment. I am able to containerize and able to deploy it as a POD in a Kubernetes cluster.

In order to bring in the Active/Passive role here, I am running two instances of this POD, each pinned to a separate K8S nodes using node affinity (each node is labeled as either active or passive, and POD definitions pin on these labels), and clustering them up using my app's clustering mechanism whereas only one will be active and the other will be passive.

I am exposing the REST service externally using K8S Service semantics by making use of the NodePort, and exposing the REST WebService via a NodePort on the master node.

Here's my yaml file content:

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
  labels:
    app: myapp-service
spec:
  type: NodePort
  ports:
    - port: 8443
      nodePort: 30403
  selector:
    app: myapp

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: active
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - active
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: active
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: passive
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - passive
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: passive
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage

Everything seems working fine, except that since both PODs are exposing the web service via same port, the K8S Service is routing the incoming requests to one of these PODS in a random fashion. Since my REST WebService endpoints work only on Active node, the service requests work via K8S Service resource only when the request is getting routed to the POD with app in Active role. If at any point in time the K8S Service happens to route the incoming request to POD with app in passive role, the service is inaccessible/not served.

How do I make this work in such a way that the K8S service always routes the requests to POD with app in Active role? Is this something doable in Kubernetes or I'm aiming for too much?

Thank you for your time!


问:
While adding data from URL to SQLite Database in android the records are repeating after 10
I was trying to add some fields from URL to SQLite Database.Here I am facing a problem like after adding 10 records the records are adding from the beginning. I am doing in getView() method of the CustomAdapter. Suggest me any solution or guide me if the way I am doing is wrong.

Here is my DatabaseHandler class

```<code>public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}
</code>```

and the getView() method of my Adapter class is.

```<code>public View getView(int i, View view, ViewGroup viewGroup) {
    view = inflater.inflate(R.layout.single_item,null);
    TextView tvName = (TextView)view.findViewById(R.id.txtName);
    TextView tvMobile = (TextView)view.findViewById(R.id.txtPhone);
    DatabaseHandler db = new DatabaseHandler(activity);
    db.addContact(new Contact(dataList.get(i).getName(),dataList.get(i).getPhoneNumber()));
    List<Contact> contacts = db.getAllContacts();
    Log.d("contacts",contacts.get(i).getName()+"");
    tvName.setText(contacts.get(i).getName());
    tvMobile.setText(contacts.get(i).getPhoneNumber());
    return view;
}
</code>```

the logcat response is like

The actual data contains 14 records but last 4 are not coming

答:
The getView method is a method that is called when the screen needs to be rendered. So getView method can be called more than once. For this reason, you should do database operations outside of this method.

For example in your activity class:

```<code>    ...
    contactListView (ListView)findViewById(R.id.lv_contacts_container);<-- your xml
    contactList = db.getAllContacts();
    adapter = new ContactListViewAdapter(this, contactList);
    contactListView.setAdapter(adapter);

    contactListView.setOnItemClickListener(new
    AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            //Selected contact entity
            ContactEntity entity = adapter.getData().get(position);
            ...
        }

    });
</code>```

and simply your adapter class might be like:

```<code>public class ContactListViewAdapter extends BaseAdapter {

Context context;
LayoutInflater inflater;
private List<ContactEntity> contactList;

public ContactListViewAdapter(Context context, List<ContactEntity> contactList) {
    this.context = context;
    this.contactList = new ArrayList<>();
    this.contactList.addAll(contactList);
}

@Override
public int getCount() {
    return contactList.size();
}

public List<ContactEntity> getData() {
    return this.contactList;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ContactRowViewHolder holder;
    if (convertView == null) {
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.contact_list_row, parent, false); <--your row xml
        holder = new ContactRowViewHolder();
        holder.contactNameTextView = (TextView) convertView.findViewById(R.id.contact_text); <-- your text view in row
        convertView.setTag(holder);
    } else {
        holder = (ContactRowViewHolder) convertView.getTag();
    }

    ContactEntity contact = contactList.get(position);
    if (contact == null || contact.getContactName() == null) {
        // error log
    }
    holder.contactNameTextView.setText(contact.getContactName());
    return convertView;
}

static class ContactRowViewHolder {
    private TextView contactNameTextView;
}
}
</code>```

Note: The holder pattern is good for long lists

Body:
I was trying to add some fields from URL to SQLite Database.Here I am facing a problem like after adding 10 records the records are adding from the beginning. I am doing in getView() method of the CustomAdapter. Suggest me any solution or guide me if the way I am doing is wrong.

Here is my DatabaseHandler class

public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

and the getView() method of my Adapter class is.

public View getView(int i, View view, ViewGroup viewGroup) {
    view = inflater.inflate(R.layout.single_item,null);
    TextView tvName = (TextView)view.findViewById(R.id.txtName);
    TextView tvMobile = (TextView)view.findViewById(R.id.txtPhone);
    DatabaseHandler db = new DatabaseHandler(activity);
    db.addContact(new Contact(dataList.get(i).getName(),dataList.get(i).getPhoneNumber()));
    List<Contact> contacts = db.getAllContacts();
    Log.d("contacts",contacts.get(i).getName()+"");
    tvName.setText(contacts.get(i).getName());
    tvMobile.setText(contacts.get(i).getPhoneNumber());
    return view;
}

the logcat response is like

The actual data contains 14 records but last 4 are not coming

Body:
The getView method is a method that is called when the screen needs to be rendered. So getView method can be called more than once. For this reason, you should do database operations outside of this method.

For example in your activity class:

    ...
    contactListView (ListView)findViewById(R.id.lv_contacts_container);<-- your xml
    contactList = db.getAllContacts();
    adapter = new ContactListViewAdapter(this, contactList);
    contactListView.setAdapter(adapter);

    contactListView.setOnItemClickListener(new
    AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            //Selected contact entity
            ContactEntity entity = adapter.getData().get(position);
            ...
        }

    });

and simply your adapter class might be like:

public class ContactListViewAdapter extends BaseAdapter {

Context context;
LayoutInflater inflater;
private List<ContactEntity> contactList;

public ContactListViewAdapter(Context context, List<ContactEntity> contactList) {
    this.context = context;
    this.contactList = new ArrayList<>();
    this.contactList.addAll(contactList);
}

@Override
public int getCount() {
    return contactList.size();
}

public List<ContactEntity> getData() {
    return this.contactList;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ContactRowViewHolder holder;
    if (convertView == null) {
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.contact_list_row, parent, false); <--your row xml
        holder = new ContactRowViewHolder();
        holder.contactNameTextView = (TextView) convertView.findViewById(R.id.contact_text); <-- your text view in row
        convertView.setTag(holder);
    } else {
        holder = (ContactRowViewHolder) convertView.getTag();
    }

    ContactEntity contact = contactList.get(position);
    if (contact == null || contact.getContactName() == null) {
        // error log
    }
    holder.contactNameTextView.setText(contact.getContactName());
    return convertView;
}

static class ContactRowViewHolder {
    private TextView contactNameTextView;
}
}

Note: The holder pattern is good for long lists


问:
How to access named url arguments in permissions with Django REST Framework?
I have an url config like

url(r'^user/(?P<id>[0-9]+)/$', UserView.as_view())

And a view class like

```<code>class UserView(GenericAPIView):
    serializer_class = UserSerializer
    permission_classes = [MyCustomPermission]

    def get(self, request, id):
        # code...
</code>```

The permission is like

```<code>class MyCustomPermission(BasePermission):
    def has_permission(self, request, view, *args, **kwargs):
    # code
</code>```

How do I access id in MyCustomPermission? I can't find it from the request or from *args or *kwargs. Documentation doesn't say anything about this. I've tried to look the source code but can't find how to access those named url arguments. Is it even possible?

答: This is the wrong approach. Rather than trying to access keyword arguments there, you should be using object-level permissions and checking has_object_permission in your permission class.

Body:
I have an url config like

url(r'^user/(?P<id>[0-9]+)/$', UserView.as_view())

And a view class like

class UserView(GenericAPIView):
    serializer_class = UserSerializer
    permission_classes = [MyCustomPermission]

    def get(self, request, id):
        # code...

The permission is like

class MyCustomPermission(BasePermission):
    def has_permission(self, request, view, *args, **kwargs):
    # code

How do I access id in MyCustomPermission? I can't find it from the request or from *args or *kwargs. Documentation doesn't say anything about this. I've tried to look the source code but can't find how to access those named url arguments. Is it even possible?


问:
Script required
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

```<code>Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)
</code>```

I tried as below, where its incrementing the values rows by rows.

```<code>select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1
</code>```

Output should be:

```<code>ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40
</code>```

Can anyone here me, how to do that.

答:
It's simply Series - 10:

```<code>SELECT ID, Name, Series, Series - 10 AS ABC
FROM #Temp1;
</code>```

Title: Script required

Body:
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)

I tried as below, where its incrementing the values rows by rows.

select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1

Output should be:

ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40

Can anyone here me, how to do that.

Body:
It's simply Series - 10:

SELECT ID, Name, Series, Series - 10 AS ABC
FROM #Temp1;


问:
scanning an array and assign it into other place in C
help me. I've been assign to make an application for some test result. but why can't I print out what user have inputted at case 2. I've tried other approach but it's not working. this is the closest I could get there. Any help would be appreciated. super thanks +_+

this is my code :

```<code>int main(){
    int option;
    char namamurid[30][15];
    int i=0,j=0;
    int listening[15];
    int reading[15];
    int essay[15];
    int score[15];

    do{ printf("\"Smart English\" Course Center\n********************************\n");
        printf("1.Add new data\n2.View data\n3.View summary\n4.Exit\n\n");
        printf("your option[1..4]: ");
        scanf("%d",&option);
        fflush(stdin);

        switch(option){
            case 1:
                do{
                    printf("Input student's name[1..25 char]: ");
                    scanf("%[^\n]s",namamurid[i]);
                    fflush(stdin);
                }while(strlen(namamurid[i])<1 || strlen(namamurid[i])>25);

                do{
                    printf("Correct answer for listening section[0..20]: ");
                    scanf("%d",&listening[i]);
                    fflush(stdin);
                }while(listening[i]<0 || listening[i]>20);

                do{
                    printf("Correct answer for reading section[0..30]: ");
                    scanf("%d",&reading[i]);
                    fflush(stdin);

                }while(reading[i]<0 || reading[i]>30);

                do{
                    printf("Correct answer for essay section[0..25]: ");
                    scanf("%d",&essay[i]);
                    fflush(stdin);

                }while(essay[i]<0 || essay[i]>25);
                break;

            case 2:
                printf("Name\t\tListening\tReading\tEssay\tScore\tGrade\n");
                for(j=0;j<i;j++)
                {
                    printf("%-1s\t\t%d\t%d\t%d\t%d\n",namamurid[j],listening[j],reading[j],essay[j],score[j]);
                }

                break;
        }
    } while(option<1 || option>4 || option !=4);

    getchar();
    return 0;
}
</code>```

答: There is no change to value of variable i which is set to 0 during initialization.Hence it will never enter the for loop in case 2.</p>

Body:
help me. I've been assign to make an application for some test result. but why can't I print out what user have inputted at case 2. I've tried other approach but it's not working. this is the closest I could get there. Any help would be appreciated. super thanks +_+

this is my code :

int main(){
    int option;
    char namamurid[30][15];
    int i=0,j=0;
    int listening[15];
    int reading[15];
    int essay[15];
    int score[15];

    do{ printf("\"Smart English\" Course Center\n********************************\n");
        printf("1.Add new data\n2.View data\n3.View summary\n4.Exit\n\n");
        printf("your option[1..4]: ");
        scanf("%d",&option);
        fflush(stdin);

        switch(option){
            case 1:
                do{
                    printf("Input student's name[1..25 char]: ");
                    scanf("%[^\n]s",namamurid[i]);
                    fflush(stdin);
                }while(strlen(namamurid[i])<1 || strlen(namamurid[i])>25);

                do{
                    printf("Correct answer for listening section[0..20]: ");
                    scanf("%d",&listening[i]);
                    fflush(stdin);
                }while(listening[i]<0 || listening[i]>20);

                do{
                    printf("Correct answer for reading section[0..30]: ");
                    scanf("%d",&reading[i]);
                    fflush(stdin);

                }while(reading[i]<0 || reading[i]>30);

                do{
                    printf("Correct answer for essay section[0..25]: ");
                    scanf("%d",&essay[i]);
                    fflush(stdin);

                }while(essay[i]<0 || essay[i]>25);
                break;

            case 2:
                printf("Name\t\tListening\tReading\tEssay\tScore\tGrade\n");
                for(j=0;j<i;j++)
                {
                    printf("%-1s\t\t%d\t%d\t%d\t%d\n",namamurid[j],listening[j],reading[j],essay[j],score[j]);
                }

                break;
        }
    } while(option<1 || option>4 || option !=4);

    getchar();
    return 0;
}


问:
What is the use of pom.xml in Maven?
I have just started working with Maven in Eclipse.

I tried running a sample program in it, and I encountered some problems. The errors were in my pom.xml file. What is the significance of the pom.xml file in Maven?

答:
When there is no Maven, it needs to add all the library JAR files one by one to the project. But when there is Pom.xml there is no need to add library JAR files one by one.

Simply add the dependency to the Pom.xml, and it will automatically add the library JAR files to the project.

ContentLicense: CC BY-SA 4.0

Title: What is the use of pom.xml in Maven?


问:
How to correctly format measured time (in minutes and seconds with optional hours) in Excel?
All I want is to enter time in an Excel sheet in the format [hh]:mm:ss without Excel going batsh*t crazy on me.

I just want to enter 30:25 as 30 minutes 25 seconds without it turning into 30:25:00 in the cell and somehow "1/1/1900  6:25:00 AM" in the formula bar.

If it's one colon it's just minutes and seconds, if there's two colons it also includes hours. Is this not possible at all?

答:
```<code>Public Sub TestMe()
    Application.StatusBar = Minute(Now) & " minutes " & Second(Now) & " seconds."
End Sub
</code>```

If you have some kind of OCD and you like to have minutes and minute, depending on whether it is 1 minute or not, this is a way to achieve it:

```<code>Public Sub TestMe()

    Dim currentTime     As Date
    Dim displayValue    As String

    currentTime = Now

    If Minute(currentTime) = 1 Then
        displayValue = Minute(currentTime ) & " minute "
    Else
        displayValue = Minute(currentTime ) & " minutes "
    End If

    If Second(currentTime) = 1 Then
        displayValue = displayValue & Second(currentTime) & " second."
    Else
        displayValue = displayValue & Second(currentTime) & " seconds."
    End If

    Application.StatusBar = displayValue

End Sub
</code>```

This is a reference for the Minute Function for VB.

Body:
Public Sub TestMe()
    Application.StatusBar = Minute(Now) & " minutes " & Second(Now) & " seconds."
End Sub

If you have some kind of OCD and you like to have minutes and minute, depending on whether it is 1 minute or not, this is a way to achieve it:

Public Sub TestMe()

    Dim currentTime     As Date
    Dim displayValue    As String

    currentTime = Now

    If Minute(currentTime) = 1 Then
        displayValue = Minute(currentTime ) & " minute "
    Else
        displayValue = Minute(currentTime ) & " minutes "
    End If

    If Second(currentTime) = 1 Then
        displayValue = displayValue & Second(currentTime) & " second."
    Else
        displayValue = displayValue & Second(currentTime) & " seconds."
    End If

    Application.StatusBar = displayValue

End Sub

This is a reference for the Minute Function for VB.


问:
What is the difference between an expression and a statement in Python?
In Python, what is the difference between expressions and statements?</p>

答:
Expression -- from the New Oxford American Dictionary:

expression: Mathematics a collection
  of symbols that jointly express a
  quantity : the expression for the
  circumference of a circle is 2πr.

In gross general terms: Expressions produce at least one value.

In Python, expressions are covered extensively in the Python Language Reference In general, expressions in Python are composed of a syntactically legal combination of Atoms, Primaries and Operators.

Python expressions from Wikipedia

Examples of expressions:

Literals and syntactically correct combinations with Operators and built-in functions or the call of a user-written functions:

```<code>>>> 23
23
>>> 23l
23L
>>> range(4)
[0, 1, 2, 3]
>>> 2L*bin(2)
'0b100b10'
>>> def func(a):      # Statement, just part of the example...
...    return a*a     # Statement...
...
>>> func(3)*4
36
>>> func(5) is func(a=5)
True
</code>```

Statement from Wikipedia:

In computer programming a statement
  can be thought of as the smallest
  standalone element of an imperative
  programming language. A program is
  formed by a sequence of one or more
  statements. A statement will have
  internal components (e.g.,
  expressions).

Python statements from Wikipedia

In gross general terms: Statements Do Something and are often composed of expressions (or other statements)

The Python Language Reference covers Simple Statements and Compound Statements extensively.

The distinction of "Statements do something" and "expressions produce a value" distinction can become blurry however:

List Comprehensions are considered "Expressions" but they have looping constructs and therfore also Do Something.

The if is usually a statement, such as if x<0: x=0 but you can also have a conditional expression like x=0 if x<0 else 1 that are expressions. In other languages, like C, this form is called an operator like this x=x<0?0:1;

You can write you own Expressions by writing a function. def func(a): return a*a is an expression when used but made up of statements when defined.

An expression that returns None is a procedure in Python: def proc(): pass Syntactically, you can use proc() as an expression, but that is probably a bug...

Python is a bit more strict than say C is on the differences between an Expression and Statement. In C, any expression is a legal statement. You can have func(x=2); Is that an Expression or Statement? (Answer: Expression used as a Statement with a side-effect.) The assignment statement of x=2 inside of the function call of func(x=2) in Python sets the named argument a to 2 only in the call to func and is more limited than the C example.

Body:
Expression -- from the New Oxford American Dictionary:

expression: Mathematics a collection
  of symbols that jointly express a
  quantity : the expression for the
  circumference of a circle is 2πr.

In gross general terms: Expressions produce at least one value.

In Python, expressions are covered extensively in the Python Language Reference In general, expressions in Python are composed of a syntactically legal combination of Atoms, Primaries and Operators.

Python expressions from Wikipedia

Examples of expressions:

Literals and syntactically correct combinations with Operators and built-in functions or the call of a user-written functions:

>>> 23
23
>>> 23l
23L
>>> range(4)
[0, 1, 2, 3]
>>> 2L*bin(2)
'0b100b10'
>>> def func(a):      # Statement, just part of the example...
...    return a*a     # Statement...
...
>>> func(3)*4
36
>>> func(5) is func(a=5)
True

Statement from Wikipedia:

In computer programming a statement
  can be thought of as the smallest
  standalone element of an imperative
  programming language. A program is
  formed by a sequence of one or more
  statements. A statement will have
  internal components (e.g.,
  expressions).

Python statements from Wikipedia

In gross general terms: Statements Do Something and are often composed of expressions (or other statements)

The Python Language Reference covers Simple Statements and Compound Statements extensively.

The distinction of "Statements do something" and "expressions produce a value" distinction can become blurry however:

List Comprehensions are considered "Expressions" but they have looping constructs and therfore also Do Something.

The if is usually a statement, such as if x<0: x=0 but you can also have a conditional expression like x=0 if x<0 else 1 that are expressions. In other languages, like C, this form is called an operator like this x=x<0?0:1;

You can write you own Expressions by writing a function. def func(a): return a*a is an expression when used but made up of statements when defined.

An expression that returns None is a procedure in Python: def proc(): pass Syntactically, you can use proc() as an expression, but that is probably a bug...

Python is a bit more strict than say C is on the differences between an Expression and Statement. In C, any expression is a legal statement. You can have func(x=2); Is that an Expression or Statement? (Answer: Expression used as a Statement with a side-effect.) The assignment statement of x=2 inside of the function call of func(x=2) in Python sets the named argument a to 2 only in the call to func and is more limited than the C example.


问:
How to count distinct values that all satisfy a condition in MySQL?
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

```<code>RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111
</code>```

Desired Result:

```<code>Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1
</code>```

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

答:
I just modified @thorsten-kettner's solution as you were facing problem while joining table. I have assumed you 2 tables, table1 - which has at least 2 rows (RowID and MemberIdentifier ) and table2 - which has at least 2 rows ( RowID and Status)</p>

```<code>select Status, count(*)
from(
  select
    case when sum(newTable.Status = 'In Progress') > 0 then 'In Progress'
         when sum(newTable.Status = 'Not Started') > 0 then 'Not Started'
         else 'Complete'
    end as status
  from (
    select table1.RowId as RowId, table1.MemberIdentifier as MemberIdentifier, table2.Status as Status from table1 INNER JOIN table2 ON table1.RowId = table2.RowId
  )newTable
  group by newTable.MemberIdentifier
) statuses
group by Status;
</code>```

Body:
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111

Desired Result:

Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

Body:
I just modified @thorsten-kettner's solution as you were facing problem while joining table. I have assumed you 2 tables, table1 - which has at least 2 rows (RowID and MemberIdentifier ) and table2 - which has at least 2 rows ( RowID and Status)

select Status, count(*)
from(
  select
    case when sum(newTable.Status = 'In Progress') > 0 then 'In Progress'
         when sum(newTable.Status = 'Not Started') > 0 then 'Not Started'
         else 'Complete'
    end as status
  from (
    select table1.RowId as RowId, table1.MemberIdentifier as MemberIdentifier, table2.Status as Status from table1 INNER JOIN table2 ON table1.RowId = table2.RowId
  )newTable
  group by newTable.MemberIdentifier
) statuses
group by Status;


问:
How do you allow time entry in 2 formats in Django?
I want users to be able to entry time as decimals:

8.25

and as time:

8:15

What Django FormField should I use?

My thoughts are to make is a forms.CharField() as that would remove HTML restrictions and forms.TimeField() creates the same input.

What Validators should be applied to that formfield?

I'm not sure if I need to create a custom validator.

答:
I would use CharField with custom validation in clean_fieldname method:

```<code>class TimeForm(forms.Form):
    user_time = forms.CharField()

    def clean_time_field(self):
        user_time = self.cleaned_data['user_time']
        if '.' in user_time:
            hours, minutes = user_time.split('.')
        elif ':' in user_time:
            hours, minutes = user_time.split(':')
        else:
            raise ValidationError('Provide correct time')
        return datetime.time(hour=hours, minute=minutes)
</code>```

Body:
I would use CharField with custom validation in clean_fieldname method:

class TimeForm(forms.Form):
    user_time = forms.CharField()

    def clean_time_field(self):
        user_time = self.cleaned_data['user_time']
        if '.' in user_time:
            hours, minutes = user_time.split('.')
        elif ':' in user_time:
            hours, minutes = user_time.split(':')
        else:
            raise ValidationError('Provide correct time')
        return datetime.time(hour=hours, minute=minutes)


问:
POST versus Ajax call
Now that most modern browsers support AJAX and client-side requests without performing a POST, what is the role of POST (form post)?

Are there situations or general rules when a POST will always be preferred to a XmlHttpRequest?

All that POST is doing is placing variable key value pairs inside the server head. The advantages of POST I can think of are large amounts of data and mobile browsers. Are there many others I'm missing?

N.B. I know you can perform POSTs with AJAX calls, I'm talking primarily about with a <form> tag

答: Some actions can't be carried out using AJAX requests due to security restrictions. For example, uploading files can't be done with AJAX.</p>

OwnerDisplayName: Chris

Title: POST versus Ajax call

OwnerDisplayName: Welbog


问:
Google Chrome Cannary: Icons isn't appearing
I'm working using the Google Chrome Cannary for some time. With the last update (Version 64.0.3268.0 (Official Build) canary (64-bit)) I loosed every icon on the browser:

Can anyone tell me how to solve this?

Thank you in advance

答: The update Google Chrome Version 64.0.3269.0 (Official Build) canary (64-bit) solved the problem.


问:
How to list all assets in a catalog in watson data science experience?
I have created a Watson data science experience (DSX) account, created a catalog into it and added data assets to it.
I am trying to use the REST APIs as documented at: https://developer.ibm.com/api/view/id-1084:title-Watson_Data_Platform_Core_Services#id36962
...  to retrieve the assets using curl.

```<code>curl -H "Authorization: Bearer <---stripped the auth token --->" -X GET 'https://api.dataplatform.ibm.com/v2/assets?catalog_id=bd2b56c3-091f-4ff5-beab-b3a1da85488d'

I get the following response:
{
    "errors": [
        {
            "code": "invalid_parameter",
            "message": "COMSV3006E: Missing or Invalid 'asset' id",
            "target": {
                "name": "asset",
                "type": "parameter"
            }
        }
    ],
    "trace": "e7b07khusvkj7s0ymgrggm6si"
}
</code>```

How do I specify the asset id to retrieve the same?
Also, I am looking to upload assets, assign metadata/tags to existing assets using REST APIs. Is there any documentation/tutorial available, which can help explain me that?

答:
One option is the search api, although it is listed as deprecated:

```<code>curl -X POST -d '{"query":"asset.asset_state:available"}' -H "Content-Type: application/json" https://api.dataplatform.ibm.com/v2/catalogs/<catalog_guid>/types/<type>/search -H "Authorization: Bearer ...."
</code>```

https://developer.ibm.com/api/view/id-1084:title-Watson_Data_Platform_Core_Services#id37001

For <type>, you probably want data_asset, but you can also look up all existing types:

```<code>curl -X GET https://api.dataplatform.ibm.com/v2/catalogs/<catalog_guid>/types -H "Authorization: Bearer ...."
</code>```

https://developer.ibm.com/api/view/id-1084:title-Watson_Data_Platform_Core_Services#id36916

Body:
I have created a Watson data science experience (DSX) account, created a catalog into it and added data assets to it.
I am trying to use the REST APIs as documented at: https://developer.ibm.com/api/view/id-1084:title-Watson_Data_Platform_Core_Services#id36962
...  to retrieve the assets using curl.

curl -H "Authorization: Bearer <---stripped the auth token --->" -X GET 'https://api.dataplatform.ibm.com/v2/assets?catalog_id=bd2b56c3-091f-4ff5-beab-b3a1da85488d'

I get the following response:
{
    "errors": [
        {
            "code": "invalid_parameter",
            "message": "COMSV3006E: Missing or Invalid 'asset' id",
            "target": {
                "name": "asset",
                "type": "parameter"
            }
        }
    ],
    "trace": "e7b07khusvkj7s0ymgrggm6si"
}

How do I specify the asset id to retrieve the same?
Also, I am looking to upload assets, assign metadata/tags to existing assets using REST APIs. Is there any documentation/tutorial available, which can help explain me that?

Body:
One option is the search api, although it is listed as deprecated:

curl -X POST -d '{"query":"asset.asset_state:available"}' -H "Content-Type: application/json" https://api.dataplatform.ibm.com/v2/catalogs/<catalog_guid>/types/<type>/search -H "Authorization: Bearer ...."

https://developer.ibm.com/api/view/id-1084:title-Watson_Data_Platform_Core_Services#id37001

For <type>, you probably want data_asset, but you can also look up all existing types:

curl -X GET https://api.dataplatform.ibm.com/v2/catalogs/<catalog_guid>/types -H "Authorization: Bearer ...."

https://developer.ibm.com/api/view/id-1084:title-Watson_Data_Platform_Core_Services#id36916


问:
Jquery validate required based on another field's input and target field's input
How can I make an input field required IF another field is not filled out OR if the target field IS filled out?

I have two fields for height...inches and feet.  I would like to make the fields required based on each other.  I was able to get the Require to work with a function

```<code>"user[height][inches]":{
    required: function(element) {
       return (!$("input[name='user[height][feet]']").hasClass('valid'));
    },
</code>```

I did the same for feet and that worked well.  The next step I needed was a range validation but only if the field is required or if it is not required but is filled in anyway.  I was able to get that to work with the Depends

```<code>range: {
   param: [1, 120],
   depends: function(element) {
   // if feet is not filled out then require inches range
   if (!$("input[name='user[height][feet]']").hasClass('valid')){
      return true;
   // else if feet is filled out and inches is not blank or 0 then require range
   } else if ( $("input[name='user[height][inches]']").val() != "" && $("input[name='user[height][inches]']").val() != "0" ) {
      return true;
   // else feet is filled out and inches is blank or 0 so do not require range
   }  else {
      return false;
   }
</code>```

I can't seem to get the Number requirement to work with this though.  It only works one the FIRST validation but when the user tries again with a non-number it accepts it.

```<code>        number: function(element){
            // if feet is not filled out then require number input
            if (!$("input[name='user[height][feet]']").hasClass('valid')){
              return true;
              // else if feet is filled out and inches is not blank
            } else if ( $("input[name='user[height][inches]']").val() != "" ) {
              return true;
              // else feet is filled out and inches is blank so do not require
            }  else {
              return false;
            }
        }
</code>```

I also tried...

```<code>        number: {
            depends: function(event){
               // if feet is not filled out then require number input
               if (!$("input[name='user[height][feet]']").hasClass('valid')){
                 return true;
              // else if feet is filled out and inches is not blank
               } else if ( $("input[name='user[height][inches]']").val() != "" ) {
                 return true;
              // else feet is filled out and inches is blank so do not require
               }  else {
                 return false;
               }
             }
           }
</code>```

My field forms are

```<code><input type="number" name="user[height][inches]" placeholder="11"/>
<input type="number" name="user[height][feet]" placeholder="4"/>
</code>```

I noticed that if I debug during the validation that when I am calling $("input[name='user[height][inches]']").val() that it returns "" even if the input value is "string", I believe this is because it does not pass validation but I also think it ruins my logic.

Another problem might be that initially it is checking if the feet field hasClass "valid" and it returns false but then it seems like after initially being false, it is then set to validated once the the inches field is filled out and then ruins the validation logic on the 2nd attempt.

Here is my JFiddle but I had trouble duplicating since it is validating for a number correctly without even including that validation requirement... http://jsfiddle.net/sza51q6s/1/

I might have to reevaluate my logic entirely.  How can I make the target field required only if the other field is NOT filled out OR if the current field IS filled out?

答:
Jquery One Field Validation Depend on another Field Input

```<code>   'document': {
                required: function(element){
                    return $("#document_title").val()!="";
                }
            }
</code>```

Body:
How can I make an input field required IF another field is not filled out OR if the target field IS filled out?

I have two fields for height...inches and feet.  I would like to make the fields required based on each other.  I was able to get the Require to work with a function

"user[height][inches]":{
    required: function(element) {
       return (!$("input[name='user[height][feet]']").hasClass('valid'));
    },

I did the same for feet and that worked well.  The next step I needed was a range validation but only if the field is required or if it is not required but is filled in anyway.  I was able to get that to work with the Depends

range: {
   param: [1, 120],
   depends: function(element) {
   // if feet is not filled out then require inches range
   if (!$("input[name='user[height][feet]']").hasClass('valid')){
      return true;
   // else if feet is filled out and inches is not blank or 0 then require range
   } else if ( $("input[name='user[height][inches]']").val() != "" && $("input[name='user[height][inches]']").val() != "0" ) {
      return true;
   // else feet is filled out and inches is blank or 0 so do not require range
   }  else {
      return false;
   }

I can't seem to get the Number requirement to work with this though.  It only works one the FIRST validation but when the user tries again with a non-number it accepts it.

        number: function(element){
            // if feet is not filled out then require number input
            if (!$("input[name='user[height][feet]']").hasClass('valid')){
              return true;
              // else if feet is filled out and inches is not blank
            } else if ( $("input[name='user[height][inches]']").val() != "" ) {
              return true;
              // else feet is filled out and inches is blank so do not require
            }  else {
              return false;
            }
        }

I also tried...

        number: {
            depends: function(event){
               // if feet is not filled out then require number input
               if (!$("input[name='user[height][feet]']").hasClass('valid')){
                 return true;
              // else if feet is filled out and inches is not blank
               } else if ( $("input[name='user[height][inches]']").val() != "" ) {
                 return true;
              // else feet is filled out and inches is blank so do not require
               }  else {
                 return false;
               }
             }
           }

My field forms are

<input type="number" name="user[height][inches]" placeholder="11"/>
<input type="number" name="user[height][feet]" placeholder="4"/>

I noticed that if I debug during the validation that when I am calling $("input[name='user[height][inches]']").val() that it returns "" even if the input value is "string", I believe this is because it does not pass validation but I also think it ruins my logic.

Another problem might be that initially it is checking if the feet field hasClass "valid" and it returns false but then it seems like after initially being false, it is then set to validated once the the inches field is filled out and then ruins the validation logic on the 2nd attempt.

Here is my JFiddle but I had trouble duplicating since it is validating for a number correctly without even including that validation requirement... http://jsfiddle.net/sza51q6s/1/

I might have to reevaluate my logic entirely.  How can I make the target field required only if the other field is NOT filled out OR if the current field IS filled out?

Body:
Jquery One Field Validation Depend on another Field Input

   'document': {
                required: function(element){
                    return $("#document_title").val()!="";
                }
            }


问:
How to read a number above 999 that is separated by a comma (eg. 10,000)?
I'm new to C (and programming) and it's possible that my question can be answered with some basic searching and reading; please point me to an answer to the question if it exists.

Let's say that I want to read a number that can possibly be above 999 from the user. From my experience, if I enter the value 10,000 (including the comma), the program would read the number until the comma and then stop taking input. Thus, the input would be 10 instead of 10000.

How can I make it read '10,000' as if it is 10000?

答:
Most implementation of scanf and printf on Linux support ' to tell that the number may have a thousands separator:

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

int main(int argc, char const *argv[])
{
    setlocale(LC_NUMERIC, ""); // set the locale so that "," is a thousands separator

    const char* string = "10,000";

    float num = 0;
    sscanf(string, "%'f", &num);
    printf("%f\n", num);

    return 0;
}
</code>```

returns

```<code>10000.000000
</code>```

https://www.systutorials.com/docs/linux/man/3-printf/

Body:
Most implementation of scanf and printf on Linux support ' to tell that the number may have a thousands separator:

#include <stdio.h>
#include <locale.h>

int main(int argc, char const *argv[])
{
    setlocale(LC_NUMERIC, ""); // set the locale so that "," is a thousands separator

    const char* string = "10,000";

    float num = 0;
    sscanf(string, "%'f", &num);
    printf("%f\n", num);

    return 0;
}

returns

10000.000000

https://www.systutorials.com/docs/linux/man/3-printf/