问:
Updating a table based on a findfirst criteria
I have a recordset TBLSOURCETARGETLINK that I want to update on an after update event.

I also need to ensure that no duplicates are present before I add the new record.
If the record exists, I just want to update the record and add new.

I am struggling with the VBA and the sequencing of how to do it.

Please could someone assist.

VBA currently looks like this:

```<code>Private Sub IsSource_AfterUpdate()

Dim VbaTableID As Integer
Dim VbaSystemID As Integer
Dim VbaFieldID As Integer
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim tabledef As String
Dim strcriteria As String

Dim rstSourceTarget As Recordset
Set rstSourceTarget = CurrentDb.OpenRecordset(Name:="tblsouretargetlink",      Type:=RecordsetTypeEnum.dbOpenDynaset)

If IsNull(Me!TableID) Then
   Else
        VbaTableID = Me!TableID
End If

If IsNull(Me!SystemID) Then
   Else
        VbaSystemID = Me!SystemID
  End If

If IsNull(Me!FieldID) Then
   Else
        Vbafield = Me!FieldID
End If
strcriteria = "[systemid] = '" & Me.SystemID & "' And [tableid] = " &    Me.TableID And [FieldID] = " & Me.fieldid"

rs.FindFirst strcriteria

   If .NoMatch Then
        With rstSourceTarget
            .AddNew
            ![SystemID] = VbaSystemID
            ![SourceTable] = VbaTableID
            ![SourceField] = VbaFieldID
            .Update
        End With
   Else
        With rstSourceTarget
            .Edit
            ![IsSource] = -1
            .Update
   End If

End Sub
</code>```

Thank you

答:
Try this code:

```<code>Private Sub IsSource_AfterUpdate()

    Dim VbaTableID As Integer
    Dim VbaSystemID As Integer
    Dim VbaFieldID As Integer
    Dim db As DAO.Database
    Dim strCriteria As String
    Dim rstSourceTarget As Recordset

    Set db = CurrentDb
    ' don't use CurrentDb for opening recordsets, it's dynamic, you can lose reference to database.
    Set rstSourceTarget = db.OpenRecordset(Name:="tblsouretargetlink", Type:=RecordsetTypeEnum.dbOpenDynaset)

    If Not IsNull(Me!TableID) Then
        VbaTableID = Me!TableID
    End If

    If Not IsNull(Me!SystemID) Then
        VbaSystemID = Me!SystemID
    End If

    If Not IsNull(Me!fieldid) Then
        VbaFieldID = Me!fieldid
    End If

    strCriteria = "[systemid] = '" & Me.SystemID & "' And [tableid] = " & Me.TableID & " And [FieldID] = " & Me.fieldid

    With rstSourceTarget
        .FindFirst strCriteria
        If .NoMatch Then
            .AddNew
            ![SystemID] = VbaSystemID
            ![SourceTable] = VbaTableID
            ![SourceField] = VbaFieldID
            .Update
        Else
            .Edit
            ![IsSource] = -1
            .Update
        End If
    End With
End Sub
</code>```

There are a lot of errors, so first of all add

```<code>Option Explicit
</code>```

at the beginning of each module and recompile the project (Debug->Compile)

Body:
I have a recordset TBLSOURCETARGETLINK that I want to update on an after update event.

I also need to ensure that no duplicates are present before I add the new record.
If the record exists, I just want to update the record and add new.

I am struggling with the VBA and the sequencing of how to do it.

Please could someone assist.

VBA currently looks like this:

Private Sub IsSource_AfterUpdate()

Dim VbaTableID As Integer
Dim VbaSystemID As Integer
Dim VbaFieldID As Integer
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim tabledef As String
Dim strcriteria As String

Dim rstSourceTarget As Recordset
Set rstSourceTarget = CurrentDb.OpenRecordset(Name:="tblsouretargetlink",      Type:=RecordsetTypeEnum.dbOpenDynaset)

If IsNull(Me!TableID) Then
   Else
        VbaTableID = Me!TableID
End If

If IsNull(Me!SystemID) Then
   Else
        VbaSystemID = Me!SystemID
  End If

If IsNull(Me!FieldID) Then
   Else
        Vbafield = Me!FieldID
End If
strcriteria = "[systemid] = '" & Me.SystemID & "' And [tableid] = " &    Me.TableID And [FieldID] = " & Me.fieldid"

rs.FindFirst strcriteria

   If .NoMatch Then
        With rstSourceTarget
            .AddNew
            ![SystemID] = VbaSystemID
            ![SourceTable] = VbaTableID
            ![SourceField] = VbaFieldID
            .Update
        End With
   Else
        With rstSourceTarget
            .Edit
            ![IsSource] = -1
            .Update
   End If

End Sub

Thank you

Body:
Try this code:

Private Sub IsSource_AfterUpdate()

    Dim VbaTableID As Integer
    Dim VbaSystemID As Integer
    Dim VbaFieldID As Integer
    Dim db As DAO.Database
    Dim strCriteria As String
    Dim rstSourceTarget As Recordset

    Set db = CurrentDb
    ' don't use CurrentDb for opening recordsets, it's dynamic, you can lose reference to database.
    Set rstSourceTarget = db.OpenRecordset(Name:="tblsouretargetlink", Type:=RecordsetTypeEnum.dbOpenDynaset)

    If Not IsNull(Me!TableID) Then
        VbaTableID = Me!TableID
    End If

    If Not IsNull(Me!SystemID) Then
        VbaSystemID = Me!SystemID
    End If

    If Not IsNull(Me!fieldid) Then
        VbaFieldID = Me!fieldid
    End If

    strCriteria = "[systemid] = '" & Me.SystemID & "' And [tableid] = " & Me.TableID & " And [FieldID] = " & Me.fieldid

    With rstSourceTarget
        .FindFirst strCriteria
        If .NoMatch Then
            .AddNew
            ![SystemID] = VbaSystemID
            ![SourceTable] = VbaTableID
            ![SourceField] = VbaFieldID
            .Update
        Else
            .Edit
            ![IsSource] = -1
            .Update
        End If
    End With
End Sub

There are a lot of errors, so first of all add

Option Explicit

at the beginning of each module and recompile the project (Debug->Compile)


来源: stackexchange

问:
dm-script function to detect digiScan overhead time
Is there an equivalent/similar function to DSisAcquisitionActive()?

In my GMS 1.93, DM complains "No match for dsisacquisitionactive()".

Wondering if there is alternative function for old systems. I need to wait the DigiScan overhead time is over before acquiring another STEM to avoid system crashing.

答:
Unfortunately, I'm not aware of an 'earlier' command which would do that.

Hardware scripting has only been introduced with GMS 2.3. All commands before that time were Gatan-intern R&D only. But as they are the "basis" for the later suppored commands, some of them exist in older versions.

The F1 help documenation lists the supported commands and it also states the version history. Most often it is "introduced in ...." and those are usually working in earlier versions. The command you've mentioned, however, reads "Added as new command" so it has been created with that version

However, you should be able to "estimate" that time pretty accurately when you know pixel-dwell-time and flyback time. There is a certain "overhead" for loading the hardware, but that should be constant and independent of the actual acquisition paramters to a large extend.
Maybe plot several acquistions times as function of the pixel-dwelltime and/or image size (at constant fly-back) and do a linear regression to get an idea of that value.

Another idea I would try would be to put the acqusitions start code into a Try{}Catch{} loop and use the exception thrown by the Digiscan still being active to wait. That's pretty ugly and I'm not sure it would work, but it's worth a  shot when you're forced to remain with old software...

ContentLicense: CC BY-SA 3.0


问:
What is the best way to transform spaces between words into + sign?
The function should transform input value to query:

```<code>1. "   bald   valves  " to "bald+valves"
2. " buffers some  " to "buffers+some"
</code>```

that is my current solution:

```<code>query.trim().replace(/\s\s+/g, ' ').replace(/[\s.;,?%]/, '+')
</code>```

could you please help me to improve it?

答:
How about </p>

```<code>s.trim().replace(/\s+/g,'+')

"   bald   valves  ".trim().replace(/\s+/g,'+')
"bald+valves"
" buffers some  ".trim().replace(/\s+/g,'+')
"buffers+some"
</code>```

Body:
The function should transform input value to query:

1. "   bald   valves  " to "bald+valves"
2. " buffers some  " to "buffers+some"

that is my current solution:

query.trim().replace(/\s\s+/g, ' ').replace(/[\s.;,?%]/, '+')

could you please help me to improve it?

Body:
How about

s.trim().replace(/\s+/g,'+')

"   bald   valves  ".trim().replace(/\s+/g,'+')
"bald+valves"
" buffers some  ".trim().replace(/\s+/g,'+')
"buffers+some"


问:
spring mvc properties - java.io.FileNotFoundException: config.properties (The system cannot find the file specified)
I have created a properties file and trying to access this in my spring DAO class file, but am getting "java.io.FileNotFoundException: config.properties (The system cannot find the file specified)". I have tried different scenarios to put the file in different folder/locations but getting same issue. Can anybody please help me on this. Below is the code and structure details,

In DAO class,

```<code>FileReader reader = new FileReader("config.properties");
Properties properties = new Properties();
properties.load(reader);
</code>```

I tried to put the "config.properties" file under src/main/resources and also under WEB-INF/. My DAO class is in src/main/java/com/test/dao
Thanks in Advance.

答:
You can keep the file in src/main/resources where its most appropriate and change the way you retrieve it into:

```<code>ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config.properties").getFile());
FileReader reader = new FileReader(file);
</code>```

Body:
I have created a properties file and trying to access this in my spring DAO class file, but am getting "java.io.FileNotFoundException: config.properties (The system cannot find the file specified)". I have tried different scenarios to put the file in different folder/locations but getting same issue. Can anybody please help me on this. Below is the code and structure details,

In DAO class,

FileReader reader = new FileReader("config.properties");
Properties properties = new Properties();
properties.load(reader);

I tried to put the "config.properties" file under src/main/resources and also under WEB-INF/. My DAO class is in src/main/java/com/test/dao
Thanks in Advance.

Body:
You can keep the file in src/main/resources where its most appropriate and change the way you retrieve it into:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config.properties").getFile());
FileReader reader = new FileReader(file);


问:
Generic parameter 'Value' could not be inferred creating block based KVO in swift
Entering this (contrived example) code

```<code>import Foundation

protocol ValueProviderProtocol {
    var amount: Int { get }
}

class ValueProvider: NSObject, ValueProviderProtocol {
    @objc dynamic var amount = 0
}

let _provider = ValueProvider()

var provider: ValueProviderProtocol { return _provider }

let subject = provider as! NSObject

let observer = subject.observe(\ValueProviderProtocol.amount, options: [.old, .new]) { (provider, changes) in

}
</code>```

into an Xcode 9 playground, results in this error for the call to subject.observe:

Generic parameter 'Value' could not be inferred

It is not clear what is causing the error. What can be done to fix this kind of problem?

答:
The following line:

```<code>let observer = subject.observe(\ValueProviderProtocol.amount,
                               options: [.old, .new])
                               { (provider, changes) in
}
</code>```

needs to change in to:

```<code>let observer = _provider.observe(\.amount,
                                 options: [.old, .new],
                                 changeHandler: { (provider, changes) in

})
</code>```

You can not try to observe on subject since is downcasted to an NSObject that does not have the property amount. And second \ValueProviderProtocol.amount is a partial key path that does not infere value type \.amount is a KeyPath that inferes keypath

Body:
Entering this (contrived example) code

import Foundation

protocol ValueProviderProtocol {
    var amount: Int { get }
}

class ValueProvider: NSObject, ValueProviderProtocol {
    @objc dynamic var amount = 0
}

let _provider = ValueProvider()

var provider: ValueProviderProtocol { return _provider }

let subject = provider as! NSObject

let observer = subject.observe(\ValueProviderProtocol.amount, options: [.old, .new]) { (provider, changes) in

}

into an Xcode 9 playground, results in this error for the call to subject.observe:

Generic parameter 'Value' could not be inferred

It is not clear what is causing the error. What can be done to fix this kind of problem?

Body:
The following line:

let observer = subject.observe(\ValueProviderProtocol.amount,
                               options: [.old, .new])
                               { (provider, changes) in
}

needs to change in to:

let observer = _provider.observe(\.amount,
                                 options: [.old, .new],
                                 changeHandler: { (provider, changes) in

})

You can not try to observe on subject since is downcasted to an NSObject that does not have the property amount. And second \ValueProviderProtocol.amount is a partial key path that does not infere value type \.amount is a KeyPath that inferes keypath

ContentLicense: CC BY-SA 4.0


问:
How to pass parameter to vue.js router in a method function?
I'm trying to send 'joke.id' as parameter to the router:

```<code>edit: function(joke) {
    this.$router.push({ '/edit/' + joke.id });
}
</code>```

The relevant route is:

```<code>{path: '/edit/:id', component: editJoke, name: 'editJoke'},
</code>```

However I get this in the console:

Module build failed: SyntaxError: Unexpected token

```<code>this.$router.push({ '/edit/' + joke.id });
  |                          ^
</code>```

How can I fix this?

答:
There's no need for curly braces inside the push function. Your code should be like this:

```<code>this.$router.push('/edit/' + joke.id);
</code>```

Body:
I'm trying to send 'joke.id' as parameter to the router:

edit: function(joke) {
    this.$router.push({ '/edit/' + joke.id });
}

The relevant route is:

{path: '/edit/:id', component: editJoke, name: 'editJoke'},

However I get this in the console:

Module build failed: SyntaxError: Unexpected token

this.$router.push({ '/edit/' + joke.id });
  |                          ^

How can I fix this?

Body:
There's no need for curly braces inside the push function. Your code should be like this:

this.$router.push('/edit/' + joke.id);


问:
Hibernate behavior with mysql strict mode
My code was committing a bean using hibernate, in table 'mast' on UAT DB with

```<code>session.save(userWalletConfigBean);
transaction.commit()
</code>```

It was working fine,
however, in my production environment, it was throwing an error

```<code>Hibernate: insert into mast (wId, no, emailid, password,
name, usertype, userstatus, creationDate, aggreatorid, distributerid,
agentid, subagentid, createdby, loginStatus, lastlogintime, address1,
address2, city, state, pin, pan, adhar, kycstatus, approvalrequired,
agent, loginipiemi, loginagent, oldpassword, id)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2017-11-10/23:00:11.340
WARN: util.JDBCExceptionReporter - SQL Error: 1292, SQLState: 22001
2017-11-10/23:00:11.341
ERROR: util.JDBCExceptionReporter - Data truncation: Truncated incorrect DOUBLE value: 'DIST001001'
2017-11-10/23:00:11.342
ERROR: def.AbstractFlushingEventListener - Could not synchronize database state with session
</code>```

Upon further inspection, I found out that this was due to Strict mode of SQL

I took an insert query from UAT table and tried to directly run it on the Production database, this leads me to face the same Truncated incorrect DOUBLE value issue on production DB's logs.

After which I disabled the strict mode of the production DB, and was able to directly run the insert query successfully.

However, even after this, I am facing the same issue from my code when running on production.

I have already double checked my tables on both UAT and production are same with no change.

What I wish to know is how to solve this issue.

Please let me know if anything else is required.

Any help is appreciated.

Below is my entity mapped bean

```<code>    @Entity
    @Table(name="mast")
    public class Mast implements Serializable{

        @Id
        @Column(name="id",length =30)
        private String id;

        @Column(name="wid",length =50,nullable = false,updatable=false)
        private String wId;

        @Column(name = "mobileno", unique = true, nullable = false, length = 12)
        private String mobileno;

        @Column(name = "emailid", unique = true, nullable = false, length = 100)
        private String emailid;

        @Column(name = "password", nullable = false, length = 100)
        private String password;

        @Column(name = "name", nullable = false, length = 100)
        private String name;

        @Column(name = "usertype", nullable = false, length = 2 ,columnDefinition = "int default 0")
        private int usertype;

        @Column(name = "userstatus", nullable = false, length = 2)
        private String userstatus;

        @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
        private Date creationDate;

        @Column(name = "aggreatorid", nullable = true, length = 100)
        private String aggreatorid;

        @Column(name = "distributerid", nullable = true, length = 100)
        private String distributerid;

        @Column(name = "agentid", nullable = true, length = 100)
        private String agentid;

        @Column(name = "subagentid", nullable = true, length = 100)
        private String subAgentId;

        @Column(name = "createdby", nullable = true, length = 100)
        private String createdby;

        @Column(name = "loginStatus", nullable = false, length = 2 ,columnDefinition = "int default 0")
        private int loginStatus;

        @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
        private Date lastlogintime;

        @Column(name="address1",length =50,nullable = true)
        private String address1;

        @Column(name="address2",length =50,nullable = true)
        private String address2;

        @Column(name="city",length =50,nullable = true)
        private String city;

        @Column(name="state",length =50,nullable = true)
        private String state;

        @Column(name="pin",length =50,nullable = true)
        private String pin;

        @Column(name="pan",length =20,nullable = true)
        private String pan;

        @Column(name="adhar",length =20,nullable = true)
        private String adhar;

        @Column(name="kycstatus",length =20,nullable = true)
        private String kycstatus;

        @Column(name = "approvalrequired", nullable = true, length = 2)
        private String approvalRequired;

        @Column(name = "agent",  length = 300 )
        private String agent;

        @Column(name = "loginipiemi",  length = 20 )
        private String loginipiemi;

        @Column(name = "loginagent",  length = 300 )
        private String loginagent;

        @Column(name = "oldpassword",  length = 1000 )
        private String oldPassword;

    }
</code>```

Below is my DB schema

```<code>    CREATE TABLE mast (
        id VARCHAR(30) NOT NULL,
        wid VARCHAR(50) NOT NULL,
        mobileno VARCHAR(12) NOT NULL,
        emailid VARCHAR(100) NOT NULL,
        password VARCHAR(100) NOT NULL,
        name VARCHAR(100) NOT NULL,
        usertype INT(11) NOT NULL DEFAULT '0',
        userstatus VARCHAR(2) NOT NULL,
        creationDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        aggreatorid VARCHAR(100) NULL DEFAULT NULL,
        distributerid VARCHAR(100) NULL DEFAULT NULL,
        agentid VARCHAR(100) NULL DEFAULT NULL,
        subagentid VARCHAR(30) NULL DEFAULT NULL,
        createdby VARCHAR(100) NULL DEFAULT NULL,
        loginStatus INT(11) NOT NULL DEFAULT '0',
        lastlogintime TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
        address1 VARCHAR(50) NULL DEFAULT NULL,
        address2 VARCHAR(50) NULL DEFAULT NULL,
        city VARCHAR(50) NULL DEFAULT NULL,
        state VARCHAR(50) NULL DEFAULT NULL,
        pin VARCHAR(50) NULL DEFAULT NULL,
        pan VARCHAR(20) NULL DEFAULT NULL,
        adhar VARCHAR(20) NULL DEFAULT NULL,
        kycstatus VARCHAR(20) NULL DEFAULT NULL,
        approvalrequired VARCHAR(2) NULL DEFAULT NULL,
        prepaidcardnumber VARCHAR(20) NULL DEFAULT NULL,
        agent TEXT NULL,
        loginipiemi VARCHAR(20) NULL DEFAULT NULL,
        loginagent TEXT NULL,
        oldpassword TEXT NULL,
        PRIMARY KEY (id)
    )COLLATE='utf8_general_ci'
ENGINE=InnoDB;
</code>```

答:
Turns out this was not the issue of the code but the whole database itself.
In the database, many tables were created with different 'COLLATE' and 'ENGINE'.

A senior developer suggested taking a backup script and re-deploying the whole database but this time with same 'COLLATE' and 'ENGINE'in all tables. Which evidently did the trick.

I do not know if this was the proper way to solve this issue but it worked for me.

Thank you @tadman @Antoniossss and @JBNizet for your support

Body:
My code was committing a bean using hibernate, in table 'mast' on UAT DB with

session.save(userWalletConfigBean);
transaction.commit()

It was working fine,
however, in my production environment, it was throwing an error

Hibernate: insert into mast (wId, no, emailid, password,
name, usertype, userstatus, creationDate, aggreatorid, distributerid,
agentid, subagentid, createdby, loginStatus, lastlogintime, address1,
address2, city, state, pin, pan, adhar, kycstatus, approvalrequired,
agent, loginipiemi, loginagent, oldpassword, id)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2017-11-10/23:00:11.340
WARN: util.JDBCExceptionReporter - SQL Error: 1292, SQLState: 22001
2017-11-10/23:00:11.341
ERROR: util.JDBCExceptionReporter - Data truncation: Truncated incorrect DOUBLE value: 'DIST001001'
2017-11-10/23:00:11.342
ERROR: def.AbstractFlushingEventListener - Could not synchronize database state with session

Upon further inspection, I found out that this was due to Strict mode of SQL

I took an insert query from UAT table and tried to directly run it on the Production database, this leads me to face the same Truncated incorrect DOUBLE value issue on production DB's logs.

After which I disabled the strict mode of the production DB, and was able to directly run the insert query successfully.

However, even after this, I am facing the same issue from my code when running on production.

I have already double checked my tables on both UAT and production are same with no change.

What I wish to know is how to solve this issue.

Please let me know if anything else is required.

Any help is appreciated.

Below is my entity mapped bean

    @Entity
    @Table(name="mast")
    public class Mast implements Serializable{

        @Id
        @Column(name="id",length =30)
        private String id;

        @Column(name="wid",length =50,nullable = false,updatable=false)
        private String wId;

        @Column(name = "mobileno", unique = true, nullable = false, length = 12)
        private String mobileno;

        @Column(name = "emailid", unique = true, nullable = false, length = 100)
        private String emailid;

        @Column(name = "password", nullable = false, length = 100)
        private String password;

        @Column(name = "name", nullable = false, length = 100)
        private String name;

        @Column(name = "usertype", nullable = false, length = 2 ,columnDefinition = "int default 0")
        private int usertype;

        @Column(name = "userstatus", nullable = false, length = 2)
        private String userstatus;

        @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
        private Date creationDate;

        @Column(name = "aggreatorid", nullable = true, length = 100)
        private String aggreatorid;

        @Column(name = "distributerid", nullable = true, length = 100)
        private String distributerid;

        @Column(name = "agentid", nullable = true, length = 100)
        private String agentid;

        @Column(name = "subagentid", nullable = true, length = 100)
        private String subAgentId;

        @Column(name = "createdby", nullable = true, length = 100)
        private String createdby;

        @Column(name = "loginStatus", nullable = false, length = 2 ,columnDefinition = "int default 0")
        private int loginStatus;

        @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
        private Date lastlogintime;

        @Column(name="address1",length =50,nullable = true)
        private String address1;

        @Column(name="address2",length =50,nullable = true)
        private String address2;

        @Column(name="city",length =50,nullable = true)
        private String city;

        @Column(name="state",length =50,nullable = true)
        private String state;

        @Column(name="pin",length =50,nullable = true)
        private String pin;

        @Column(name="pan",length =20,nullable = true)
        private String pan;

        @Column(name="adhar",length =20,nullable = true)
        private String adhar;

        @Column(name="kycstatus",length =20,nullable = true)
        private String kycstatus;

        @Column(name = "approvalrequired", nullable = true, length = 2)
        private String approvalRequired;

        @Column(name = "agent",  length = 300 )
        private String agent;

        @Column(name = "loginipiemi",  length = 20 )
        private String loginipiemi;

        @Column(name = "loginagent",  length = 300 )
        private String loginagent;

        @Column(name = "oldpassword",  length = 1000 )
        private String oldPassword;

    }

Below is my DB schema

    CREATE TABLE mast (
        id VARCHAR(30) NOT NULL,
        wid VARCHAR(50) NOT NULL,
        mobileno VARCHAR(12) NOT NULL,
        emailid VARCHAR(100) NOT NULL,
        password VARCHAR(100) NOT NULL,
        name VARCHAR(100) NOT NULL,
        usertype INT(11) NOT NULL DEFAULT '0',
        userstatus VARCHAR(2) NOT NULL,
        creationDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        aggreatorid VARCHAR(100) NULL DEFAULT NULL,
        distributerid VARCHAR(100) NULL DEFAULT NULL,
        agentid VARCHAR(100) NULL DEFAULT NULL,
        subagentid VARCHAR(30) NULL DEFAULT NULL,
        createdby VARCHAR(100) NULL DEFAULT NULL,
        loginStatus INT(11) NOT NULL DEFAULT '0',
        lastlogintime TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
        address1 VARCHAR(50) NULL DEFAULT NULL,
        address2 VARCHAR(50) NULL DEFAULT NULL,
        city VARCHAR(50) NULL DEFAULT NULL,
        state VARCHAR(50) NULL DEFAULT NULL,
        pin VARCHAR(50) NULL DEFAULT NULL,
        pan VARCHAR(20) NULL DEFAULT NULL,
        adhar VARCHAR(20) NULL DEFAULT NULL,
        kycstatus VARCHAR(20) NULL DEFAULT NULL,
        approvalrequired VARCHAR(2) NULL DEFAULT NULL,
        prepaidcardnumber VARCHAR(20) NULL DEFAULT NULL,
        agent TEXT NULL,
        loginipiemi VARCHAR(20) NULL DEFAULT NULL,
        loginagent TEXT NULL,
        oldpassword TEXT NULL,
        PRIMARY KEY (id)
    )COLLATE='utf8_general_ci'
ENGINE=InnoDB;


问:
(PHP) How to arrange HTML table content having breaking row element for outputting as one line output?
I want to arrange a output format from a crawled file.

The output file I want to make them all in one line.

For parting each td, my expected output is as below:

```<code><b>Nation / Area</b>(Name tag)    <b>Detail</b>Address Telephone
</code>```

(Explanation) "Nation / Area", "(Name tag)", "4 spaces", "Detail" and
  "Address Telephone" are sequently listed as my expected output. Totally there are 5 fields.

==================================================

I don't know how to handle this case.

This is the page HTML code.

```<code><table border='1' id='hi_hosts_table_id' cellspacing='0' cellpadding='4'>
    <tr>
        <td class='hi_table_header'><b>Nation / Area</b><br>(Name tag)</td>
        <td class='hi_table_header'><b>Detail</b><br>Address<br>Telephone</td>
    </tr>
</table>
</code>```

This is my code for arranging that output file.

```<code>$absolute_path = '/home/hi/mycrawler/benchmark';
include($absolute_path.'/simple_html_dom/simple_html_dom.php');
$dom = file_get_html($absolute_path.'/'.$datetime.'benchmark.html');
#download the list
if ($dom->find('table[id=hi_hosts_table_id]'))
{
  foreach($dom->find('table[id=hi_hosts_table_id]')->find('tr') as $row)
    {
      $location = $row->find('td',0)->plaintext;
      $detail= $row->find('td',1)->plaintext;
      echo "$location $detail\n";
    }
} else {
  #Pending match or not match
  echo "No match. There are some problems.\n";
  exit(0);
}
exit(0);
?>
</code>```

答:
When you execute $row->find('td',0), the result is a node that described the Nation / Area
(Name tag	 part of the HTML.

When you then do ->plaintext, the code that gets executed is simple_html_dom_node::text(). While this method seems to do a lot of things, it doesn't transform the HTML into plaintext; rather, it just returns all the "text".

So, if you want to remove line break, you'll have to do that yourself:

```<code>$location = str_replace('<br>', ' ', $row->find('td',0)->plaintext);
$detail= str_replace('<br>', ' ', $row->find('td',1)->plaintext);
</code>```

Body:
I want to arrange a output format from a crawled file.

The output file I want to make them all in one line.

For parting each td, my expected output is as below:

Nation / Area(Name tag)    DetailAddress Telephone

(Explanation) "Nation / Area", "(Name tag)", "4 spaces", "Detail" and
  "Address Telephone" are sequently listed as my expected output. Totally there are 5 fields.

==================================================

I don't know how to handle this case.

This is the page HTML code.

        Nation / Area
(Name tag)
        Detail
Address
Telephone

This is my code for arranging that output file.

$absolute_path = '/home/hi/mycrawler/benchmark';
include($absolute_path.'/simple_html_dom/simple_html_dom.php');
$dom = file_get_html($absolute_path.'/'.$datetime.'benchmark.html');
#download the list
if ($dom->find('table[id=hi_hosts_table_id]'))
{
  foreach($dom->find('table[id=hi_hosts_table_id]')->find('tr') as $row)
    {
      $location = $row->find('td',0)->plaintext;
      $detail= $row->find('td',1)->plaintext;
      echo "$location $detail\n";
    }
} else {
  #Pending match or not match
  echo "No match. There are some problems.\n";
  exit(0);
}
exit(0);
?>

Body:
When you execute $row->find('td',0), the result is a node that described the <td class='hi_table_header'><b>Nation / Area</b><br>(Name tag</td> part of the HTML.

When you then do ->plaintext, the code that gets executed is simple_html_dom_node::text(). While this method seems to do a lot of things, it doesn't transform the HTML into plaintext; rather, it just returns all the "text".

So, if you want to remove line break, you'll have to do that yourself:

$location = str_replace('<br>', ' ', $row->find('td',0)->plaintext);
$detail= str_replace('<br>', ' ', $row->find('td',1)->plaintext);


问:
Passing a function as a parameter but getting unexpected results
I'm using Racket with the "Advanced Student" language setting and I'm having difficulty trying to write a function that takes a function, executes it n times and reports the time elapsed for each run. This is what I've got so far.

```<code>(define (many n fn)
  (cond
    [(= n 0) true]
    [else (many (sub1 n) (local ((define k (time fn))) k))]))
</code>```

I have a function called fact that computes the factorial of a number.

```<code>(define (fact n)
  (cond
    [(= 0 n) 1]
    [else (* n (fact (- n 1)))]))
</code>```

If I evaluate (time (fact 10000)), I get reasonable results for cpu, real and gc time, as well as a large number. All well and good.

However, when I try to evaluate (many 3 (fact 10000)) I get:

```<code>cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
true
</code>```

Why is the function not evaluating fact despite being passed as a parameter?

答:
Let's examine what you many does. First you defined it:

```<code>(define (many n fn)
  (cond
    [(= n 0) true]
    [else (many (sub1 n)
                (local ((define k (time fn)))
                       k))]))
</code>```

Then call it:

```<code>> (many 3 (add1 41))
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
#t
>
</code>```

Here what happens on every iteration when many calls itself recursively:

```<code>(define (many 3 42)
  (cond
    [(= 3 0) true]
    [else (many (sub1 3)
                (local ((define k (time 42)))
                       42))]))

(define (many 2 42)
  (cond
    [(= 2 0) true]
    [else (many (sub1 2)
                (local ((define k (time 42)))
                       42))]))

(define (many 1 42)
  (cond
    [(= 1 0) true]
    [else (many (sub1 1)
                (local ((define k (time 42)))
                       42))]))

(define (many 0 42)
  (cond
    [(= 0 0) true]
    [else (many (sub1 0)
                (local ((define k (time 42)))
                       42))]))
</code>```

Your definition of many recursively calls itself with the result value of the first (time fn) application, but it is not correct, because you want to collect timing information for your procedure application, not the value (value of (add1 41) in our case). Just substitute true with fn in your definition of many:

```<code>(define (many n fn)
  (cond
    [(= n 0) fn]
    [else (many (sub1 n)
                (local ((define k (time fn)))
                 k))]))
</code>```

and you'll get the following:

```<code>> (many 3 (add1 41))
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
42
>
</code>```

You see that fn on every recursive call equals 42. This happens because many (if not all) FP languages use Applicative order of evaluation, and (add1 41) is evaluated before the first call to many happens.

Thus we have to use lambda to ensure a function (thunk in our case) is passed to many as it's second argument (fn). As you already know function application in Scheme is expressed as () around expression:

```<code>(define (many n fn)
  (time (fn))
  (if (= n 0)
      true
      (many (sub1 n) fn)))
</code>```

Example output:

```<code>> (many 3 (lambda () (fact 10000)))
cpu time: 2734 real time: 2828 gc time: 1922
cpu time: 906 real time: 953 gc time: 171
cpu time: 891 real time: 953 gc time: 204
cpu time: 938 real time: 984 gc time: 251
#t
>
</code>```

As you see above (fn) performs application of the result of function (lambda () (fact 10000) (thunk), time gets exactly what you wanted to pass it (an expression) and displays the correct timing information.

Hope that helps. Correct me if I'm wrong.

ContentLicense: CC BY-SA 2.5

Body:
I'm using Racket with the "Advanced Student" language setting and I'm having difficulty trying to write a function that takes a function, executes it n times and reports the time elapsed for each run. This is what I've got so far.

(define (many n fn)
  (cond
    [(= n 0) true]
    [else (many (sub1 n) (local ((define k (time fn))) k))]))

I have a function called fact that computes the factorial of a number.

(define (fact n)
  (cond
    [(= 0 n) 1]
    [else (* n (fact (- n 1)))]))

If I evaluate (time (fact 10000)), I get reasonable results for cpu, real and gc time, as well as a large number. All well and good.

However, when I try to evaluate (many 3 (fact 10000)) I get:

cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
true

Why is the function not evaluating fact despite being passed as a parameter?

Body:
Let's examine what you many does. First you defined it:

(define (many n fn)
  (cond
    [(= n 0) true]
    [else (many (sub1 n)
                (local ((define k (time fn)))
                       k))]))

Then call it:

> (many 3 (add1 41))
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
#t
>

Here what happens on every iteration when many calls itself recursively:

(define (many 3 42)
  (cond
    [(= 3 0) true]
    [else (many (sub1 3)
                (local ((define k (time 42)))
                       42))]))

(define (many 2 42)
  (cond
    [(= 2 0) true]
    [else (many (sub1 2)
                (local ((define k (time 42)))
                       42))]))

(define (many 1 42)
  (cond
    [(= 1 0) true]
    [else (many (sub1 1)
                (local ((define k (time 42)))
                       42))]))

(define (many 0 42)
  (cond
    [(= 0 0) true]
    [else (many (sub1 0)
                (local ((define k (time 42)))
                       42))]))

Your definition of many recursively calls itself with the result value of the first (time fn) application, but it is not correct, because you want to collect timing information for your procedure application, not the value (value of (add1 41) in our case). Just substitute true with fn in your definition of many:

(define (many n fn)
  (cond
    [(= n 0) fn]
    [else (many (sub1 n)
                (local ((define k (time fn)))
                 k))]))

and you'll get the following:

> (many 3 (add1 41))
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
cpu time: 0 real time: 0 gc time: 0
42
>

You see that fn on every recursive call equals 42. This happens because many (if not all) FP languages use Applicative order of evaluation, and (add1 41) is evaluated before the first call to many happens.

Thus we have to use lambda to ensure a function (thunk in our case) is passed to many as it's second argument (fn). As you already know function application in Scheme is expressed as () around expression:

(define (many n fn)
  (time (fn))
  (if (= n 0)
      true
      (many (sub1 n) fn)))

Example output:

> (many 3 (lambda () (fact 10000)))
cpu time: 2734 real time: 2828 gc time: 1922
cpu time: 906 real time: 953 gc time: 171
cpu time: 891 real time: 953 gc time: 204
cpu time: 938 real time: 984 gc time: 251
#t
>

As you see above (fn) performs application of the result of function (lambda () (fact 10000) (thunk), time gets exactly what you wanted to pass it (an expression) and displays the correct timing information.

Hope that helps. Correct me if I'm wrong.


问:
pyqt5 QTableWidget won't display id key value from PyEve dataset
i'm trying to build a pyqt5 widget to display a dataset from PyEve, but i'm unable to display the id key value into the table row header. this is the part of the code that generate the QTableWidget

```<code>http = "http://127.0.0.1:5000/people"
con = requests.get(http)

self.tview = QTableWidget()
self.tview.setRowCount(len(con.json()['_items']))
self.tview.setColumnCount(2)

self.tview.setHorizontalHeaderItem(0, QTableWidgetItem("Firstname"))
self.tview.setHorizontalHeaderItem(1, QTableWidgetItem("Lastname"))

row = 0
for item in con.json()['_items']:
    self.tview.setVerticalHeaderItem(row, QTableWidgetItem(item["id"]))
    self.tview.setItem(row, 0, QTableWidgetItem(item['firstname']))
    self.tview.setItem(row, 1, QTableWidgetItem(item['lastname']))
    row += 1
</code>```

which resulted:
QTableWidget

this is the dataset from the API call in shell

```<code>    $ http localhost:5000/people

    {
    "_items": [
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "34418931281956ee9f0d73f5015a325276dce0a8",
            "_links": {
                "self": {
                    "href": "people/1",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "George",
            "fullname": "George Washington",
            "id": 1,
            "lastname": "Washington"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "8efc3ef35256de6e9bf530e54188ba5c3526cf0b",
            "_links": {
                "self": {
                    "href": "people/2",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "John",
            "fullname": "John Adams",
            "id": 2,
            "lastname": "Adams"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "b1e81fb3519dda0d723043203c06c2df235c9450",
            "_links": {
                "self": {
                    "href": "people/3",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Thomas",
            "fullname": "Thomas Jefferson",
            "id": 3,
            "lastname": "Jefferson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "5d3bc841cefdb56710445b2cf9d89c3a0c899551",
            "_links": {
                "self": {
                    "href": "people/4",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "George",
            "fullname": "George Clinton",
            "id": 4,
            "lastname": "Clinton"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "a83d11293f00374f91f66ae9da5373dc6c924bca",
            "_links": {
                "self": {
                    "href": "people/5",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Madison",
            "id": 5,
            "lastname": "Madison"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "e6abc69c3f2cb05676b0f2e6d76bde51b3ee467c",
            "_links": {
                "self": {
                    "href": "people/6",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Elbridge",
            "fullname": "Elbridge Gerry",
            "id": 6,
            "lastname": "Gerry"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "5621734381fe51fc4bb6d05bdc94ffe2cfe91c75",
            "_links": {
                "self": {
                    "href": "people/7",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Monroe",
            "id": 7,
            "lastname": "Monroe"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "a03e9261c3a06526893ba074f62b939d9f7798ed",
            "_links": {
                "self": {
                    "href": "people/8",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "John",
            "fullname": "John Adams",
            "id": 8,
            "lastname": "Adams"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "1b7c8e7674a75e876547567839f0496f4e2f893e",
            "_links": {
                "self": {
                    "href": "people/9",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Andrew",
            "fullname": "Andrew Jackson",
            "id": 9,
            "lastname": "Jackson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "975dd0527d63b8bb10fe63c6d648df8eaafc1a4d",
            "_links": {
                "self": {
                    "href": "people/10",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Martin",
            "fullname": "Martin Van Buren",
            "id": 10,
            "lastname": "Van Buren"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "d2aed37174724a07dd4f3262b703490319c9aa9a",
            "_links": {
                "self": {
                    "href": "people/11",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "William",
            "fullname": "William Harrison",
            "id": 11,
            "lastname": "Harrison"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "60938a8ea70dc4be7082dc12510c19bd2d802623",
            "_links": {
                "self": {
                    "href": "people/12",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "John",
            "fullname": "John Tyler",
            "id": 12,
            "lastname": "Tyler"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "f158fb234f0be3da9701779bcc953311bcaf9e89",
            "_links": {
                "self": {
                    "href": "people/13",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Polk",
            "id": 13,
            "lastname": "Polk"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "32cd09027db237a97c1d26a365403385e7eb9e40",
            "_links": {
                "self": {
                    "href": "people/14",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Zachary",
            "fullname": "Zachary Taylor",
            "id": 14,
            "lastname": "Taylor"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "9c211e916acb0327c2cc02f71a894e1f445d21ba",
            "_links": {
                "self": {
                    "href": "people/15",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Millard",
            "fullname": "Millard Fillmore",
            "id": 15,
            "lastname": "Fillmore"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "f8d4dc8f5d8ffed19cdd5304c66a5f930e085fcb",
            "_links": {
                "self": {
                    "href": "people/16",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Franklin",
            "fullname": "Franklin Pierce",
            "id": 16,
            "lastname": "Pierce"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "1b64a097904bb043e9d52f85c0620d5743fe41f7",
            "_links": {
                "self": {
                    "href": "people/17",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Buchanan",
            "id": 17,
            "lastname": "Buchanan"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "dbc84c7bffdcaa6268f64556db373f96a308025c",
            "_links": {
                "self": {
                    "href": "people/18",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Abraham",
            "fullname": "Abraham Lincoln",
            "id": 18,
            "lastname": "Lincoln"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "c9e29f8cc5b81bc406336780fbdd211490af33c6",
            "_links": {
                "self": {
                    "href": "people/19",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Andrew",
            "fullname": "Andrew Johnson",
            "id": 19,
            "lastname": "Johnson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "b3ebe09856c4e5e6e04a5e5fb88c087f5cf93165",
            "_links": {
                "self": {
                    "href": "people/20",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Ulysses",
            "fullname": "Ulysses Grant",
            "id": 20,
            "lastname": "Grant"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "e874ccb8f1ff91efb4f25d0d86ac0d1c15ba9260",
            "_links": {
                "self": {
                    "href": "people/21",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Henry",
            "fullname": "Henry Wilson",
            "id": 21,
            "lastname": "Wilson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "a62dd991fd36fdfc427c6823ecd1baf9b9a2a55f",
            "_links": {
                "self": {
                    "href": "people/22",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Rutherford",
            "fullname": "Rutherford Hayes",
            "id": 22,
            "lastname": "Hayes"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "21071baad27a9fed4ed01be7b32b7962fabd9414",
            "_links": {
                "self": {
                    "href": "people/23",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Garfield",
            "id": 23,
            "lastname": "Garfield"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "cdbd9450d58cd7258ce977cbf89a13efc3bd05df",
            "_links": {
                "self": {
                    "href": "people/24",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Chester",
            "fullname": "Chester Arthur",
            "id": 24,
            "lastname": "Arthur"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "f6d202e5f0ef01ccc1bc73a215e93378935bac0b",
            "_links": {
                "self": {
                    "href": "people/25",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Grover",
            "fullname": "Grover Cleveland",
            "id": 25,
            "lastname": "Cleveland"
        }
    ],
    "_links": {
        "last": {
            "href": "people?page=3",
            "title": "last page"
        },
        "next": {
            "href": "people?page=2",
            "title": "next page"
        },
        "parent": {
            "href": "/",
            "title": "home"
        },
        "self": {
            "href": "people",
            "title": "people"
        }
    },
    "_meta": {
        "max_results": 25,
        "page": 1,
        "total": 55
    }
}
</code>```

and this is the output i got from python console to print the "id" value

```<code>import requests
r = requests.get('http://127.0.0.1:5000/people')
for i in r.json()["_items"]: print(i["id"])
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
</code>```

i also tried to display the ID number outside the verticalHeader but to no avail

any insight would be very helpfull, thanks in advance

答:
as @eyllanesc said.. change it to

```<code>self.tview.setVerticalHeaderItem(row, QTableWidgetItem(str(item["id"])))
</code>```

does the trick. thanks

Body:
i'm trying to build a pyqt5 widget to display a dataset from PyEve, but i'm unable to display the id key value into the table row header. this is the part of the code that generate the QTableWidget

http = "http://127.0.0.1:5000/people"
con = requests.get(http)

self.tview = QTableWidget()
self.tview.setRowCount(len(con.json()['_items']))
self.tview.setColumnCount(2)

self.tview.setHorizontalHeaderItem(0, QTableWidgetItem("Firstname"))
self.tview.setHorizontalHeaderItem(1, QTableWidgetItem("Lastname"))

row = 0
for item in con.json()['_items']:
    self.tview.setVerticalHeaderItem(row, QTableWidgetItem(item["id"]))
    self.tview.setItem(row, 0, QTableWidgetItem(item['firstname']))
    self.tview.setItem(row, 1, QTableWidgetItem(item['lastname']))
    row += 1

which resulted:
QTableWidget

this is the dataset from the API call in shell

    $ http localhost:5000/people

    {
    "_items": [
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "34418931281956ee9f0d73f5015a325276dce0a8",
            "_links": {
                "self": {
                    "href": "people/1",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "George",
            "fullname": "George Washington",
            "id": 1,
            "lastname": "Washington"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "8efc3ef35256de6e9bf530e54188ba5c3526cf0b",
            "_links": {
                "self": {
                    "href": "people/2",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "John",
            "fullname": "John Adams",
            "id": 2,
            "lastname": "Adams"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "b1e81fb3519dda0d723043203c06c2df235c9450",
            "_links": {
                "self": {
                    "href": "people/3",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Thomas",
            "fullname": "Thomas Jefferson",
            "id": 3,
            "lastname": "Jefferson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "5d3bc841cefdb56710445b2cf9d89c3a0c899551",
            "_links": {
                "self": {
                    "href": "people/4",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "George",
            "fullname": "George Clinton",
            "id": 4,
            "lastname": "Clinton"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "a83d11293f00374f91f66ae9da5373dc6c924bca",
            "_links": {
                "self": {
                    "href": "people/5",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Madison",
            "id": 5,
            "lastname": "Madison"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "e6abc69c3f2cb05676b0f2e6d76bde51b3ee467c",
            "_links": {
                "self": {
                    "href": "people/6",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Elbridge",
            "fullname": "Elbridge Gerry",
            "id": 6,
            "lastname": "Gerry"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "5621734381fe51fc4bb6d05bdc94ffe2cfe91c75",
            "_links": {
                "self": {
                    "href": "people/7",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Monroe",
            "id": 7,
            "lastname": "Monroe"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "a03e9261c3a06526893ba074f62b939d9f7798ed",
            "_links": {
                "self": {
                    "href": "people/8",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "John",
            "fullname": "John Adams",
            "id": 8,
            "lastname": "Adams"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "1b7c8e7674a75e876547567839f0496f4e2f893e",
            "_links": {
                "self": {
                    "href": "people/9",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Andrew",
            "fullname": "Andrew Jackson",
            "id": 9,
            "lastname": "Jackson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "975dd0527d63b8bb10fe63c6d648df8eaafc1a4d",
            "_links": {
                "self": {
                    "href": "people/10",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Martin",
            "fullname": "Martin Van Buren",
            "id": 10,
            "lastname": "Van Buren"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "d2aed37174724a07dd4f3262b703490319c9aa9a",
            "_links": {
                "self": {
                    "href": "people/11",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "William",
            "fullname": "William Harrison",
            "id": 11,
            "lastname": "Harrison"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "60938a8ea70dc4be7082dc12510c19bd2d802623",
            "_links": {
                "self": {
                    "href": "people/12",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "John",
            "fullname": "John Tyler",
            "id": 12,
            "lastname": "Tyler"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "f158fb234f0be3da9701779bcc953311bcaf9e89",
            "_links": {
                "self": {
                    "href": "people/13",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Polk",
            "id": 13,
            "lastname": "Polk"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "32cd09027db237a97c1d26a365403385e7eb9e40",
            "_links": {
                "self": {
                    "href": "people/14",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Zachary",
            "fullname": "Zachary Taylor",
            "id": 14,
            "lastname": "Taylor"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "9c211e916acb0327c2cc02f71a894e1f445d21ba",
            "_links": {
                "self": {
                    "href": "people/15",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Millard",
            "fullname": "Millard Fillmore",
            "id": 15,
            "lastname": "Fillmore"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "f8d4dc8f5d8ffed19cdd5304c66a5f930e085fcb",
            "_links": {
                "self": {
                    "href": "people/16",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Franklin",
            "fullname": "Franklin Pierce",
            "id": 16,
            "lastname": "Pierce"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "1b64a097904bb043e9d52f85c0620d5743fe41f7",
            "_links": {
                "self": {
                    "href": "people/17",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Buchanan",
            "id": 17,
            "lastname": "Buchanan"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "dbc84c7bffdcaa6268f64556db373f96a308025c",
            "_links": {
                "self": {
                    "href": "people/18",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Abraham",
            "fullname": "Abraham Lincoln",
            "id": 18,
            "lastname": "Lincoln"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "c9e29f8cc5b81bc406336780fbdd211490af33c6",
            "_links": {
                "self": {
                    "href": "people/19",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Andrew",
            "fullname": "Andrew Johnson",
            "id": 19,
            "lastname": "Johnson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "b3ebe09856c4e5e6e04a5e5fb88c087f5cf93165",
            "_links": {
                "self": {
                    "href": "people/20",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Ulysses",
            "fullname": "Ulysses Grant",
            "id": 20,
            "lastname": "Grant"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "e874ccb8f1ff91efb4f25d0d86ac0d1c15ba9260",
            "_links": {
                "self": {
                    "href": "people/21",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Henry",
            "fullname": "Henry Wilson",
            "id": 21,
            "lastname": "Wilson"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "a62dd991fd36fdfc427c6823ecd1baf9b9a2a55f",
            "_links": {
                "self": {
                    "href": "people/22",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Rutherford",
            "fullname": "Rutherford Hayes",
            "id": 22,
            "lastname": "Hayes"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "21071baad27a9fed4ed01be7b32b7962fabd9414",
            "_links": {
                "self": {
                    "href": "people/23",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "James",
            "fullname": "James Garfield",
            "id": 23,
            "lastname": "Garfield"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "cdbd9450d58cd7258ce977cbf89a13efc3bd05df",
            "_links": {
                "self": {
                    "href": "people/24",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Chester",
            "fullname": "Chester Arthur",
            "id": 24,
            "lastname": "Arthur"
        },
        {
            "_created": "Tue, 14 Nov 2017 13:33:50 GMT",
            "_etag": "f6d202e5f0ef01ccc1bc73a215e93378935bac0b",
            "_links": {
                "self": {
                    "href": "people/25",
                    "title": "person"
                }
            },
            "_updated": "Tue, 14 Nov 2017 13:33:50 GMT",
            "firstname": "Grover",
            "fullname": "Grover Cleveland",
            "id": 25,
            "lastname": "Cleveland"
        }
    ],
    "_links": {
        "last": {
            "href": "people?page=3",
            "title": "last page"
        },
        "next": {
            "href": "people?page=2",
            "title": "next page"
        },
        "parent": {
            "href": "/",
            "title": "home"
        },
        "self": {
            "href": "people",
            "title": "people"
        }
    },
    "_meta": {
        "max_results": 25,
        "page": 1,
        "total": 55
    }
}

and this is the output i got from python console to print the "id" value

import requests
r = requests.get('http://127.0.0.1:5000/people')
for i in r.json()["_items"]: print(i["id"])
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

i also tried to display the ID number outside the verticalHeader but to no avail

any insight would be very helpfull, thanks in advance

Body:
as @eyllanesc said.. change it to

self.tview.setVerticalHeaderItem(row, QTableWidgetItem(str(item["id"])))

does the trick. thanks


问:
python dictionary attribute error
I am using the following code to 'invert' a dictionary. Some of the keys in the source dictionary have synonyms in other entries, so where there are multiple values for an inverted key I am trying to append eg commandante = captain and so does capitano = captain, so I am trying to achieve captain : commandante, capitano. I have used defaultdict which I naively thought would solve my problem, but I continuely get an Attribute error: 'str' object has no attribute 'append'

```<code>def form_eng_dict():
    #temp_dict =  pickle.load( open( "penult_dict.txt", "rb" ) )
    temp_dict ={'commandante': 'captain', 'capitano':'skipper,captain', 'alaggio': 'towing, hauling'}
    try:
        e_dict =  pickle.load( open( "penult_eng.txt", "rb" ) )
    except:
        e_dict = defaultdict(list)

    for key, value in temp_dict.items():
        for word in value.split(','):
            word.strip(' ')
            #print(word)
            if word not in e_dict:
                e_dict[word] = key
            else:
                e_dict[word].append(key) # causes error

    for key, value in e_dict.items():
        print(key, value)
    pickle.dump(temp_dict, open( "penult_eng.txt", "wb" ) )
</code>```

I am uncertain what I am doing incorrectly and how to solve the issue.I don't understand how I am creating a string. I am sure that I am making an absolutely basic error and will feel really stupid when you point out my error(s)! But thanks for your time

答:
Modify:

```<code>e_dict[word] = key
</code>```

to:

```<code>e_dict[word] = [key]
</code>```

You want to be able to append, so you should create an initial list with [key] inside - otherwise you're trying to append to a string which is why you're getting:

Attribute error: 'str' object has no attribute 'append'

Title: python dictionary attribute error

Body:
I am using the following code to 'invert' a dictionary. Some of the keys in the source dictionary have synonyms in other entries, so where there are multiple values for an inverted key I am trying to append eg commandante = captain and so does capitano = captain, so I am trying to achieve captain : commandante, capitano. I have used defaultdict which I naively thought would solve my problem, but I continuely get an Attribute error: 'str' object has no attribute 'append'

def form_eng_dict():
    #temp_dict =  pickle.load( open( "penult_dict.txt", "rb" ) )
    temp_dict ={'commandante': 'captain', 'capitano':'skipper,captain', 'alaggio': 'towing, hauling'}
    try:
        e_dict =  pickle.load( open( "penult_eng.txt", "rb" ) )
    except:
        e_dict = defaultdict(list)

    for key, value in temp_dict.items():
        for word in value.split(','):
            word.strip(' ')
            #print(word)
            if word not in e_dict:
                e_dict[word] = key
            else:
                e_dict[word].append(key) # causes error

    for key, value in e_dict.items():
        print(key, value)
    pickle.dump(temp_dict, open( "penult_eng.txt", "wb" ) )

I am uncertain what I am doing incorrectly and how to solve the issue.I don't understand how I am creating a string. I am sure that I am making an absolutely basic error and will feel really stupid when you point out my error(s)! But thanks for your time

Body:
Modify:

e_dict[word] = key

to:

e_dict[word] = [key]

You want to be able to append, so you should create an initial list with [key] inside - otherwise you're trying to append to a string which is why you're getting:

Attribute error: 'str' object has no attribute 'append'


问:
How to find if a value in a dictionary is in a certain range
I need to determine if a year (which is a value in  a dictionary) is within a certain range of years. the dictionary looks like this: print(movies[3520029]) = {'genre': ['Sci-Fi', 'Action', 'Adventure'], 'movie_year': 2010, 'name': 'TRON: Legacy', 'rating': 6.8, 'numvotes': 254865}. there are numerous entries. I need to find the movies in a range between two years, which are inputs given by the user. Im not sure how to do this. i tried

```<code>for i in movies:
    vals = list(movies.values())
        if vals[2][0] >= minimum and vals[2][0] <= maximum:
            print(movie)
</code>```

but i got builtins.KeyError: 0 and im not sure what that means, and im also not sure where to go from here.

答:
I think is Python 3.  Where you need to use list(dict.values()).

(1)The error is because there is no Index 0 inside vals[2], What is in vals[2]?

(2)You are not using i from the loop.

(3) Is movies a dict?

It should be something like this:

```<code>for key in movies:
     movie = movies[key]
     year= movie['movie_year']
</code>```

Body:
I need to determine if a year (which is a value in  a dictionary) is within a certain range of years. the dictionary looks like this: print(movies[3520029]) = {'genre': ['Sci-Fi', 'Action', 'Adventure'], 'movie_year': 2010, 'name': 'TRON: Legacy', 'rating': 6.8, 'numvotes': 254865}. there are numerous entries. I need to find the movies in a range between two years, which are inputs given by the user. Im not sure how to do this. i tried

for i in movies:
    vals = list(movies.values())
        if vals[2][0] >= minimum and vals[2][0] <= maximum:
            print(movie)

but i got builtins.KeyError: 0 and im not sure what that means, and im also not sure where to go from here.

Body:
I think is Python 3.  Where you need to use list(dict.values()).

(1)The error is because there is no Index 0 inside vals[2], What is in vals[2]?

(2)You are not using i from the loop.

(3) Is movies a dict?

It should be something like this:

for key in movies:
     movie = movies[key]
     year= movie['movie_year']


问:
Double Click Crypto in Golang
doc: https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-price#sample_code

There is no official "Double Click Crypto" example code in golang, so I try to implement by myself. But I can't pass the test in doc. Please help me!

```<code>skU7Ax_NL5pPAFyKdkfZjZz2-VhIN8bjj1rVFOaJ_5o=  // Encryption key (e_key)

arO23ykdNqUQ5LEoQ0FVmPkBd7xB5CO89PDZlSjpFxo=  // Integrity key (i_key)

WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA  // 100 CPI micros

WEp8sQAAAACwF6CtLJrXSRFBM8UiTTIyngN-og  // 1900 CPI micros

WEp8nQAAAAADG-y45xxIC1tMWuTjzmDW6HtroQ  // 2700 CPI micros
</code>```

Here is my code:

```<code>package main

// https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-price?hl=zh-CN

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha1"
    "encoding/base64"
    "encoding/binary"
    "fmt"
)

var base64Codec = base64.URLEncoding.WithPadding(base64.NoPadding)

func safeXORBytes(dst, a, b []byte) int {
    n := len(a)
    if len(b) < n {
        n = len(b)
    }
    for i := 0; i < n; i++ {
        dst[i] = a[i] ^ b[i]
    }
    return n
}

func EncryptPrice(eKey []byte, iKey []byte, price uint64, iv []byte) (finalMessage string, err error) {
    if len(iv) != 16 {
        err = fmt.Errorf("len(iv) = %d != 16", len(iv))
        return
    }

    h1 := hmac.New(sha1.New, eKey)
    h1.Write(iv)
    pad := h1.Sum(nil)[:8]

    priceBytes := make([]byte, 8)
    binary.BigEndian.PutUint64(priceBytes, price)

    encPrice := make([]byte, 8)
    n := safeXORBytes(encPrice, priceBytes, pad)
    if n != 8 {
        err = fmt.Errorf("safeXORBytes n != %d", n)
        return
    }

    h2 := hmac.New(sha1.New, iKey)
    h2.Write(priceBytes)
    h2.Write(iv)
    signature := h2.Sum(nil)[:4]

    finalMessage = base64Codec.EncodeToString(append(append(iv, encPrice...), signature...))
    return
}

func DecryptPrice(eKey []byte, iKey []byte, finalMessage string) (price uint64, err error) {
    finalMessageBytes, err := base64Codec.DecodeString(finalMessage)
    if err != nil {
        return
    }
    if len(finalMessageBytes) != 28 {
        err = fmt.Errorf("len(finalMessageBytes) = %d != 28", len(finalMessageBytes))
        return
    }

    iv := finalMessageBytes[:16]
    encPrice := finalMessageBytes[16:24]
    signature := finalMessageBytes[24:]

    h1 := hmac.New(sha1.New, eKey)
    h1.Write(iv)
    pad := h1.Sum(nil)[:8]

    priceBytes := make([]byte, 8)
    n := safeXORBytes(priceBytes, encPrice, pad)
    if n != 8 {
        err = fmt.Errorf("safeXORBytes n != %d", n)
        return
    }

    h2 := hmac.New(sha1.New, iKey)
    h2.Write(priceBytes)
    h2.Write(iv)
    confSignature := h2.Sum(nil)[:4]

    if bytes.Compare(confSignature, signature) != 0 {
        err = fmt.Errorf("sinature mismatch: confSignature = %s, sinature = %s", confSignature, signature)
        return
    }

    price = binary.BigEndian.Uint64(priceBytes)
    return
}
</code>```

```<code>package main

import (
    "github.com/stretchr/testify/assert"
    "testing"
)

func TestEncryptPrice(t *testing.T) {
    eKeyBase64Encoded := "skU7Ax_NL5pPAFyKdkfZjZz2-VhIN8bjj1rVFOaJ_5o"
    eKey, err := base64Codec.DecodeString(eKeyBase64Encoded)
    assert.Nil(t, err)

    iKeyBase64Encoded := "arO23ykdNqUQ5LEoQ0FVmPkBd7xB5CO89PDZlSjpFxo"
    iKey, err := base64Codec.DecodeString(iKeyBase64Encoded)
    assert.Nil(t, err)

    finalMessage, err := EncryptPrice(eKey, iKey, uint64(100), []byte{88, 74, 124, 193, 0, 0, 0, 0, 103, 21, 222, 68, 144, 29, 164, 215})
    assert.Nil(t, err)
    assert.Equal(t, "WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA", finalMessage)
}

func TestDecryptPrice(t *testing.T) {
    eKeyBase64Encoded := "skU7Ax_NL5pPAFyKdkfZjZz2-VhIN8bjj1rVFOaJ_5o"
    eKey, err := base64Codec.DecodeString(eKeyBase64Encoded)
    assert.Nil(t, err)

    iKeyBase64Encoded := "arO23ykdNqUQ5LEoQ0FVmPkBd7xB5CO89PDZlSjpFxo"
    iKey, err := base64Codec.DecodeString(iKeyBase64Encoded)
    assert.Nil(t, err)

    price, err := DecryptPrice(eKey, iKey, "WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA")
    assert.Nil(t, err)
    assert.Equal(t, uint64(100), price)
}
</code>```

test result:

```<code>--- FAIL: TestEncryptPrice (0.00s)
        Error Trace:    price_test.go:19
    Error:          Not equal:
                    expected: "WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA"
                    actual: "WEp8wQAAAABnFd5EkB2k1wf7jAcG7gZ9tPUnAA"
--- FAIL: TestDecryptPrice (0.00s)
        Error Trace:    price_test.go:32
    Error:          Expected nil, but got: &errors.errorString{s:"sinature mismatch: confSignature = \xbe\xaa\xf6h, sinature = T\xe7\x86\xcc"}
        Error Trace:    price_test.go:33
    Error:          Not equal:
                    expected: 0x64
                    actual: 0x0
FAIL
</code>```

答:
this code can pass the test in https://github.com/google/openrtb-doubleclick/blob/0.9.0/doubleclick-core/src/test/java/com/google/doubleclick/crypto/DoubleClickCryptoTest.java
, so I guess that the encrypted price in the doc are not excrypted by the e_key and i_key in the doc.</p>

Title: Double Click Crypto in Golang

Body:
doc: https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-price#sample_code

There is no official "Double Click Crypto" example code in golang, so I try to implement by myself. But I can't pass the test in doc. Please help me!

skU7Ax_NL5pPAFyKdkfZjZz2-VhIN8bjj1rVFOaJ_5o=  // Encryption key (e_key)

arO23ykdNqUQ5LEoQ0FVmPkBd7xB5CO89PDZlSjpFxo=  // Integrity key (i_key)

WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA  // 100 CPI micros

WEp8sQAAAACwF6CtLJrXSRFBM8UiTTIyngN-og  // 1900 CPI micros

WEp8nQAAAAADG-y45xxIC1tMWuTjzmDW6HtroQ  // 2700 CPI micros

Here is my code:

package main

// https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-price?hl=zh-CN

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha1"
    "encoding/base64"
    "encoding/binary"
    "fmt"
)

var base64Codec = base64.URLEncoding.WithPadding(base64.NoPadding)

func safeXORBytes(dst, a, b []byte) int {
    n := len(a)
    if len(b) < n {
        n = len(b)
    }
    for i := 0; i < n; i++ {
        dst[i] = a[i] ^ b[i]
    }
    return n
}

func EncryptPrice(eKey []byte, iKey []byte, price uint64, iv []byte) (finalMessage string, err error) {
    if len(iv) != 16 {
        err = fmt.Errorf("len(iv) = %d != 16", len(iv))
        return
    }

    h1 := hmac.New(sha1.New, eKey)
    h1.Write(iv)
    pad := h1.Sum(nil)[:8]

    priceBytes := make([]byte, 8)
    binary.BigEndian.PutUint64(priceBytes, price)

    encPrice := make([]byte, 8)
    n := safeXORBytes(encPrice, priceBytes, pad)
    if n != 8 {
        err = fmt.Errorf("safeXORBytes n != %d", n)
        return
    }

    h2 := hmac.New(sha1.New, iKey)
    h2.Write(priceBytes)
    h2.Write(iv)
    signature := h2.Sum(nil)[:4]

    finalMessage = base64Codec.EncodeToString(append(append(iv, encPrice...), signature...))
    return
}

func DecryptPrice(eKey []byte, iKey []byte, finalMessage string) (price uint64, err error) {
    finalMessageBytes, err := base64Codec.DecodeString(finalMessage)
    if err != nil {
        return
    }
    if len(finalMessageBytes) != 28 {
        err = fmt.Errorf("len(finalMessageBytes) = %d != 28", len(finalMessageBytes))
        return
    }

    iv := finalMessageBytes[:16]
    encPrice := finalMessageBytes[16:24]
    signature := finalMessageBytes[24:]

    h1 := hmac.New(sha1.New, eKey)
    h1.Write(iv)
    pad := h1.Sum(nil)[:8]

    priceBytes := make([]byte, 8)
    n := safeXORBytes(priceBytes, encPrice, pad)
    if n != 8 {
        err = fmt.Errorf("safeXORBytes n != %d", n)
        return
    }

    h2 := hmac.New(sha1.New, iKey)
    h2.Write(priceBytes)
    h2.Write(iv)
    confSignature := h2.Sum(nil)[:4]

    if bytes.Compare(confSignature, signature) != 0 {
        err = fmt.Errorf("sinature mismatch: confSignature = %s, sinature = %s", confSignature, signature)
        return
    }

    price = binary.BigEndian.Uint64(priceBytes)
    return
}

package main

import (
    "github.com/stretchr/testify/assert"
    "testing"
)

func TestEncryptPrice(t *testing.T) {
    eKeyBase64Encoded := "skU7Ax_NL5pPAFyKdkfZjZz2-VhIN8bjj1rVFOaJ_5o"
    eKey, err := base64Codec.DecodeString(eKeyBase64Encoded)
    assert.Nil(t, err)

    iKeyBase64Encoded := "arO23ykdNqUQ5LEoQ0FVmPkBd7xB5CO89PDZlSjpFxo"
    iKey, err := base64Codec.DecodeString(iKeyBase64Encoded)
    assert.Nil(t, err)

    finalMessage, err := EncryptPrice(eKey, iKey, uint64(100), []byte{88, 74, 124, 193, 0, 0, 0, 0, 103, 21, 222, 68, 144, 29, 164, 215})
    assert.Nil(t, err)
    assert.Equal(t, "WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA", finalMessage)
}

func TestDecryptPrice(t *testing.T) {
    eKeyBase64Encoded := "skU7Ax_NL5pPAFyKdkfZjZz2-VhIN8bjj1rVFOaJ_5o"
    eKey, err := base64Codec.DecodeString(eKeyBase64Encoded)
    assert.Nil(t, err)

    iKeyBase64Encoded := "arO23ykdNqUQ5LEoQ0FVmPkBd7xB5CO89PDZlSjpFxo"
    iKey, err := base64Codec.DecodeString(iKeyBase64Encoded)
    assert.Nil(t, err)

    price, err := DecryptPrice(eKey, iKey, "WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA")
    assert.Nil(t, err)
    assert.Equal(t, uint64(100), price)
}

test result:

--- FAIL: TestEncryptPrice (0.00s)
        Error Trace:    price_test.go:19
    Error:          Not equal:
                    expected: "WEp8wQAAAABnFd5EkB2k1wJeFcAj-Z_JVOeGzA"
                    actual: "WEp8wQAAAABnFd5EkB2k1wf7jAcG7gZ9tPUnAA"
--- FAIL: TestDecryptPrice (0.00s)
        Error Trace:    price_test.go:32
    Error:          Expected nil, but got: &errors.errorString{s:"sinature mismatch: confSignature = \xbe\xaa\xf6h, sinature = T\xe7\x86\xcc"}
        Error Trace:    price_test.go:33
    Error:          Not equal:
                    expected: 0x64
                    actual: 0x0
FAIL


问:
performance problem
OK so I need to know if anyone can see a way to reduce the number of iterations of these loops because I can't. The first while loop is for going through a file, reading one line at a time. The first foreach loop is then comparing each of the compareSet with what was read in the first while loop. Then the next while loop is to do with bit counting.

As requested, an explaination of my algorithm:

There is a file that is too large to fit in memory. It contains a word followed by the pages in a very large document that this word is on. EG:

sky 1 7 9 32....... (it is not in this format, but you get the idea).

so parseLine reads in the line and converts it into a list of ints that are like a bit array where 1 means the word is on the page, and 0 means it isn't.

CompareSet is a bunch of other words. I can't fit my entire list of words into memory so I can only fit a subset of them. This is a bunch of words just like the "sky" example. I then compare each word in compareSet with Sky by seeing if they are on the same page.

So if sky and some other word both have 1 set at a certain index in the bit array (simulated as an int array for performance), they are on the same page. The algorithm therefore counts the occurances of any two words on a particular page. So in the end I will have a list like:

(for all words in list) is on the same page as (for all words in list) x number of times.

eg sky and land is on the same page x number of times.

```<code> while ((line = parseLine(s)) != null) {
     getPageList(line.Item2, compareWord);
     foreach (Tuple<int, uint[], List<Tuple<int, int>>> word in compareSet) {
         unchecked {
             for (int i = 0; i < 327395; i++) {
                 if (word.Item2[i] == 0 || compareWord[i] == 0)
                     continue;
                 uint combinedNumber = word.Item2[i] & compareWord[i];
                 while (combinedNumber != 0) {
                     actual++;
                     combinedNumber = combinedNumber & (combinedNumber - 1);
                 }
             }
         }
</code>```

答:
As my old professor Bud used to say: "When you see nested loops like this, your spidey senses should be goin' CRAZY!"

You have a while with a nested for with another while. This nesting of loops is an exponential increase on the order of operations. Your one for loop has 327395 iterations. Assuming they have the same or similar number of iterations, that means you have an order of operations of

```<code>327,395 * 327,395 * 327,395 = 35,092,646,987,154,875 (insane)
</code>```

It's no wonder that things would be slowing down. You need to redefine your algorithm to remove these nested loops or combine work somewhere. Even if the numbers are smaller than my assumptions, the nesting of the loops is creating a LOT of operations that are probably unnecessary.

Title: performance problem

Body:
OK so I need to know if anyone can see a way to reduce the number of iterations of these loops because I can't. The first while loop is for going through a file, reading one line at a time. The first foreach loop is then comparing each of the compareSet with what was read in the first while loop. Then the next while loop is to do with bit counting.

As requested, an explaination of my algorithm:

There is a file that is too large to fit in memory. It contains a word followed by the pages in a very large document that this word is on. EG:

sky 1 7 9 32....... (it is not in this format, but you get the idea).

so parseLine reads in the line and converts it into a list of ints that are like a bit array where 1 means the word is on the page, and 0 means it isn't.

CompareSet is a bunch of other words. I can't fit my entire list of words into memory so I can only fit a subset of them. This is a bunch of words just like the "sky" example. I then compare each word in compareSet with Sky by seeing if they are on the same page.

So if sky and some other word both have 1 set at a certain index in the bit array (simulated as an int array for performance), they are on the same page. The algorithm therefore counts the occurances of any two words on a particular page. So in the end I will have a list like:

(for all words in list) is on the same page as (for all words in list) x number of times.

eg sky and land is on the same page x number of times.

 while ((line = parseLine(s)) != null) {
     getPageList(line.Item2, compareWord);
     foreach (Tuple<int, uint[], List<Tuple<int, int>>> word in compareSet) {
         unchecked {
             for (int i = 0; i < 327395; i++) {
                 if (word.Item2[i] == 0 || compareWord[i] == 0)
                     continue;
                 uint combinedNumber = word.Item2[i] & compareWord[i];
                 while (combinedNumber != 0) {
                     actual++;
                     combinedNumber = combinedNumber & (combinedNumber - 1);
                 }
             }
         }

Body:
As my old professor Bud used to say: "When you see nested loops like this, your spidey senses should be goin' CRAZY!"

You have a while with a nested for with another while. This nesting of loops is an exponential increase on the order of operations. Your one for loop has 327395 iterations. Assuming they have the same or similar number of iterations, that means you have an order of operations of

327,395 * 327,395 * 327,395 = 35,092,646,987,154,875 (insane)

It's no wonder that things would be slowing down. You need to redefine your algorithm to remove these nested loops or combine work somewhere. Even if the numbers are smaller than my assumptions, the nesting of the loops is creating a LOT of operations that are probably unnecessary.


问:
Property 'autoTable' does not exist on type jsPDF
I am using angular2 and Node JS. I have installed jspdf and jspdf-autotable both modules using npm.
In angular-cli.json file, I have embedded the scripts:

```<code>"scripts": [
        "../node_modules/jspdf/dist/jspdf.min.js",
        "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
      ],
</code>```

In my component.ts file , I have imported these files as follows:

```<code> import * as jsPDF from 'jspdf';
 import * as autoTable from 'jspdf-autotable';
</code>```

I have also tried these lines to import jspdf-autotable

```<code>import { autoTable } from 'jspdf-autotable';
import 'jspdf-autotable';
</code>```

But nothing is working.

In function of component.ts file I am using sample code as follows:

```<code>var columns = ["ID", "Country", "Rank", "Capital"];
        var data = [
            [1, "Denmark", 7.526, "Copenhagen"],
            [2, "Switzerland",  7.509, "Bern"],
            [3, "Iceland", 7.501, "Reykjavík"],
            [4, "Norway", 7.498, "Oslo"],
            [5, "Finland", 7.413, "Helsinki"]
        ];
        var doc = new jsPDF();
        doc.autoTable(columns, data);
        doc.output("dataurlnewwindow");
</code>```

But now when I run the node command to start app then during compilation I am getting error as:

Property 'autoTable' does not exist on type 'jsPDF'.

Can any one please suggest?

答:
Hi I think you have to use jspdf.plugin.autotable.min.js along with jspdf.js to work.
Here is the github link you can refer to https://github.com/simonbengtsson/jsPDF-AutoTable
Sample from above link.

```<code>    // app.component.ts or any other component
import { Component } from '@angular/core';

declare
var jsPDF: any; // Important

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app works!';

    constructor() {
        var doc = new jsPDF('p', 'pt');
        doc.autoTable(columns, data);
        doc.save("table.pdf");
    }
}
</code>```

Updated Sample:

```<code>    import { Component } from '@angular/core';
declare var jsPDF: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'app';
  constructor() {
    console.log('hi i m constr');
    var test = new jsPDF();
    console.dir(test.autoTable);
  }

}
</code>```

Body:
I am using angular2 and Node JS. I have installed jspdf and jspdf-autotable both modules using npm.
In angular-cli.json file, I have embedded the scripts:

"scripts": [
        "../node_modules/jspdf/dist/jspdf.min.js",
        "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
      ],

In my component.ts file , I have imported these files as follows:

 import * as jsPDF from 'jspdf';
 import * as autoTable from 'jspdf-autotable';

I have also tried these lines to import jspdf-autotable

import { autoTable } from 'jspdf-autotable';
import 'jspdf-autotable';

But nothing is working.

In function of component.ts file I am using sample code as follows:

var columns = ["ID", "Country", "Rank", "Capital"];
        var data = [
            [1, "Denmark", 7.526, "Copenhagen"],
            [2, "Switzerland",  7.509, "Bern"],
            [3, "Iceland", 7.501, "Reykjavík"],
            [4, "Norway", 7.498, "Oslo"],
            [5, "Finland", 7.413, "Helsinki"]
        ];
        var doc = new jsPDF();
        doc.autoTable(columns, data);
        doc.output("dataurlnewwindow");

But now when I run the node command to start app then during compilation I am getting error as:

Property 'autoTable' does not exist on type 'jsPDF'.

Can any one please suggest?

Body:
Hi I think you have to use jspdf.plugin.autotable.min.js along with jspdf.js to work.
Here is the github link you can refer to https://github.com/simonbengtsson/jsPDF-AutoTable
Sample from above link.

    // app.component.ts or any other component
import { Component } from '@angular/core';

declare
var jsPDF: any; // Important

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app works!';

    constructor() {
        var doc = new jsPDF('p', 'pt');
        doc.autoTable(columns, data);
        doc.save("table.pdf");
    }
}

Updated Sample:

    import { Component } from '@angular/core';
declare var jsPDF: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'app';
  constructor() {
    console.log('hi i m constr');
    var test = new jsPDF();
    console.dir(test.autoTable);
  }

}


问:
Downloaded font won't display properly
I downloaded a font and in my CSS I have :

```<code>@font-face {
font-family: "Gotham Medium";
src: url("Gotham/Gotham-Medium.otf");}
</code>```

When I call say in

```<code> h1 { font-family:'Gotham Medium'}
</code>```

the font display does not match what Gotham should look like. Nor is it a default font.

Is the problem a matter of something being changed when downloaded in my laptop ?
The font is not in the google API so I can't try with an external link.

答:
Your Css should be like this :

```<code>@font-face {
     font-family: 'MyWebFont';
     src: url('webfont.eot'); /* IE9 Compat Modes */
     src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
     url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
     url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
     url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
     url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
</code>```

css Trick

To do this you can use a generator for font-face but you must have the license for the web font

Title: Downloaded font won't display properly

Body:
I downloaded a font and in my CSS I have :

@font-face {
font-family: "Gotham Medium";
src: url("Gotham/Gotham-Medium.otf");}

When I call say in

 h1 { font-family:'Gotham Medium'}

the font display does not match what Gotham should look like. Nor is it a default font.

Is the problem a matter of something being changed when downloaded in my laptop ?
The font is not in the google API so I can't try with an external link.

Body:
Your Css should be like this :

@font-face {
     font-family: 'MyWebFont';
     src: url('webfont.eot'); /* IE9 Compat Modes */
     src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
     url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
     url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
     url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
     url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

css Trick

To do this you can use a generator for font-face but you must have the license for the web font


问:
Make text bold in SQLite
I'm new to Android I want to make some text bold or italic or insert a new paragraph in Android sqlite database.db
I know that I can do it using HTML tags but it doesn't show in the app it displays tags instead of bold or italic text. Can anyone help here is my code
https://drive.google.com/file/d/0B7KpqDyiTdk5cVc0X2t3N3F1WjA/view
I could have pasted it here but stack overflow doesn't let me paste that much code.

Also it would be a huge help if any one can tell me how can I mark some words as favorite and display them in new activity.

Thanks

答:
Try following code in your CustomAdapter</p>

```<code>word1.setText(Html.fromHtml(dataSet.get(listPosition).getWord()));
meaning1.setText(Html.fromHtml(dataSet.get(listPosition).getMeaning()));
</code>```

Title: Make text bold in SQLite

Body:
Try following code in your CustomAdapter

word1.setText(Html.fromHtml(dataSet.get(listPosition).getWord()));
meaning1.setText(Html.fromHtml(dataSet.get(listPosition).getMeaning()));


问:
Following action a from state s, is the outcome probablisitc or deterministic?
I am struggling to understand one aspect of the Markov Decison Process.

When I am in state s and do action a, is it deterministic or stochastic to arrive in state s+1?

In most examples it seems to be deterministic. However I found one example in the picture below (David Silvers lecture on RL) where the transistion is stochastic. Namely following action "Pub".

答:
In general, in Markov Decission Processes the transition between states can be stochastic. Usually the probability trasition to another state is denoted with P_a(s, s'), where s is the current state, s' the next state, and a the action performed.

The deterministic case is a particular case of the stochastic one. If P_a(s, s') is equal to 1 for a given s' and 0 for the remaining states, we have a deterministic transition.