问:
Constructing an LC-3 symbol table
I have a question about symbol tables. Now according to my textbook the rules of a symbol table are as follows:

Find the .ORIG statement,
which tells us the address of the first instruction and initialize location counter (LC), which keeps track of the
current instruction.

For each non-empty line in the program:
a) If line contains a label, add label and LC to symbol table.
b) Increment LC.
– NOTE: If statement is .BLKW or .STRINGZ,
increment LC by the number of words allocated.

Stop when .END statement is reached.

I'm having a problem with the second rule. Specifically, the statement about .BLKW or .STRINGZ (increment LC by the number of words allocated). I could not find any example in the textbook that could help me understand this, but I did find some code online.

In my example code, what are the addresses of the statements that contain .BLKW and .STRINGZ?

```<code>01 .ORIG x 3000
02
03 INIT
04     LEA   R0, START.STR
05     JSR   PRINST.STR
06     LD    R0, TEN
07     LEA   R1, DATA.B
08
09 STORE_LOOP
10     STR   RO, R1, %0
11     ADD   R1, R1, %1
12     ADD   R0, R0, %-1
13     BRp   ST.LOOP
14
15     LD    R0, TEN
16     ADD   R1, R1, %-1
17     AND   R2, R2, %0
18
19 ADD_LOOP
20     LDR   R3, R1, %0
21     ADD   R2, R3, R2
22     ADD   R1, R1, %-1
23     ADD   R0, R0, %-1
24     BRp   ADD_LOOP
25
26 STORE_SUM
27     ST    R2, RESULT
28     TRAP  %25
29
30 PRINT_STR
31     ST    R7, SAVE.R7
32     PUTS
33     LD    R7, SAVE.R7
34     RET
35
36  TEN       .FILL #10
37  SAVE.R7   .BLKW #1
38  DATA.B    .BLKW #10
39  START_STR .STRINGZ "Starting..."
40  RESULT    .FILL #0
41  END
</code>```

答:
Code annotated with comments showing the address of each one.

```<code>01 .ORIG x 3000
02
03 INIT                             ; x3000
04     LEA   R0, START.STR          ; x3000
05     JSR   PRINST.STR             ; x3001
06     LD    R0, TEN                ; x3002
07     LEA   R1, DATA.B             ; x3003
08
09 STORE_LOOP                       ; x3004
10     STR   RO, R1, %0             ; x3004
11     ADD   R1, R1, %1             ; x3005
12     ADD   R0, R0, %-1            ; x3006
13     BRp   ST.LOOP                ; x3007
14
15     LD    R0, TEN                ; x3008
16     ADD   R1, R1, %-1            ; x3009
17     AND   R2, R2, %0             ; x300A
18
19 ADD_LOOP                         ; x300B
20     LDR   R3, R1, %0             ; x300B
21     ADD   R2, R3, R2             ; x300C
22     ADD   R1, R1, %-1            ; x300D
23     ADD   R0, R0, %-1            ; x300E
24     BRp   ADD_LOOP               ; x300F
25
26 STORE_SUM                        ; x3010
27     ST    R2, RESULT             ; x3010
28     TRAP  %25                    ; x3011
29
30 PRINT_STR                        ; x3012
31     ST    R7, SAVE.R7            ; x3012
32     PUTS                         ; x3013
33     LD    R7, SAVE.R7            ; x3014
34     RET                          ; x3015
35
36  TEN       .FILL #10             ; x3016
37  SAVE.R7   .BLKW #1              ; x3017
38  DATA.B    .BLKW #10             ; x3018
39  START_STR .STRINGZ "Starting..."; x3022
40  RESULT    .FILL #0              ; x302E
41  END
</code>```

Things to note.

Whenever you encounter a BLKW you add however many addresses it is reserving.

Whenever you encounter a .stringz you add however many characters that are in the string PLUS 1 for the NUL terminator character.

Also (for at least the tools I work with) some assemblers / simulators will generate a symbol table file when assembling, and some simulators will visibly show what labels are at what addresses.

Title: Constructing an LC-3 symbol table

Body:
I have a question about symbol tables. Now according to my textbook the rules of a symbol table are as follows:

Find the .ORIG statement,
which tells us the address of the first instruction and initialize location counter (LC), which keeps track of the
current instruction.

For each non-empty line in the program:
a) If line contains a label, add label and LC to symbol table.
b) Increment LC.
– NOTE: If statement is .BLKW or .STRINGZ,
increment LC by the number of words allocated.

Stop when .END statement is reached.

I'm having a problem with the second rule. Specifically, the statement about .BLKW or .STRINGZ (increment LC by the number of words allocated). I could not find any example in the textbook that could help me understand this, but I did find some code online.

In my example code, what are the addresses of the statements that contain .BLKW and .STRINGZ?

01 .ORIG x 3000
02
03 INIT
04     LEA   R0, START.STR
05     JSR   PRINST.STR
06     LD    R0, TEN
07     LEA   R1, DATA.B
08
09 STORE_LOOP
10     STR   RO, R1, %0
11     ADD   R1, R1, %1
12     ADD   R0, R0, %-1
13     BRp   ST.LOOP
14
15     LD    R0, TEN
16     ADD   R1, R1, %-1
17     AND   R2, R2, %0
18
19 ADD_LOOP
20     LDR   R3, R1, %0
21     ADD   R2, R3, R2
22     ADD   R1, R1, %-1
23     ADD   R0, R0, %-1
24     BRp   ADD_LOOP
25
26 STORE_SUM
27     ST    R2, RESULT
28     TRAP  %25
29
30 PRINT_STR
31     ST    R7, SAVE.R7
32     PUTS
33     LD    R7, SAVE.R7
34     RET
35
36  TEN       .FILL #10
37  SAVE.R7   .BLKW #1
38  DATA.B    .BLKW #10
39  START_STR .STRINGZ "Starting..."
40  RESULT    .FILL #0
41  END

Body:
Code annotated with comments showing the address of each one.

01 .ORIG x 3000
02
03 INIT                             ; x3000
04     LEA   R0, START.STR          ; x3000
05     JSR   PRINST.STR             ; x3001
06     LD    R0, TEN                ; x3002
07     LEA   R1, DATA.B             ; x3003
08
09 STORE_LOOP                       ; x3004
10     STR   RO, R1, %0             ; x3004
11     ADD   R1, R1, %1             ; x3005
12     ADD   R0, R0, %-1            ; x3006
13     BRp   ST.LOOP                ; x3007
14
15     LD    R0, TEN                ; x3008
16     ADD   R1, R1, %-1            ; x3009
17     AND   R2, R2, %0             ; x300A
18
19 ADD_LOOP                         ; x300B
20     LDR   R3, R1, %0             ; x300B
21     ADD   R2, R3, R2             ; x300C
22     ADD   R1, R1, %-1            ; x300D
23     ADD   R0, R0, %-1            ; x300E
24     BRp   ADD_LOOP               ; x300F
25
26 STORE_SUM                        ; x3010
27     ST    R2, RESULT             ; x3010
28     TRAP  %25                    ; x3011
29
30 PRINT_STR                        ; x3012
31     ST    R7, SAVE.R7            ; x3012
32     PUTS                         ; x3013
33     LD    R7, SAVE.R7            ; x3014
34     RET                          ; x3015
35
36  TEN       .FILL #10             ; x3016
37  SAVE.R7   .BLKW #1              ; x3017
38  DATA.B    .BLKW #10             ; x3018
39  START_STR .STRINGZ "Starting..."; x3022
40  RESULT    .FILL #0              ; x302E
41  END

Things to note.

Whenever you encounter a BLKW you add however many addresses it is reserving.

Whenever you encounter a .stringz you add however many characters that are in the string PLUS 1 for the NUL terminator character.

Also (for at least the tools I work with) some assemblers / simulators will generate a symbol table file when assembling, and some simulators will visibly show what labels are at what addresses.


来源: stackexchange

问:
Center Latex lstlisting
This is driving me crazy.

I want to center a lstlisting in LaTeX.

After 3 hours attempting here's some code:

```<code>\lstset{ %
    caption=Descriptive Caption Text,
    label=lst:descr_capti_text,
    basicstyle=\ttfamily\footnotesize\bfseries,
    frame=tb,
    linewidth=0.6\textwidth
 }
\centering\begin{tabular}{c}
\begin{lstlisting}
printf("this should be centered!");
\end{lstlisting}
\end{tabular}
</code>```

This is putting the lstlisting on the center but not its caption, that goes to the right. If I take out the tabular, then caption gets centered but the code goes to the left! :(

Thank you.

答: Actually, what did work for me is the converse: putting the minipage inside the center environment.</p>

ContentLicense: CC BY-SA 2.5

Title: Center Latex lstlisting

Body:
This is driving me crazy.

I want to center a lstlisting in LaTeX.

After 3 hours attempting here's some code:

\lstset{ %
    caption=Descriptive Caption Text,
    label=lst:descr_capti_text,
    basicstyle=\ttfamily\footnotesize\bfseries,
    frame=tb,
    linewidth=0.6\textwidth
 }
\centering\begin{tabular}{c}
\begin{lstlisting}
printf("this should be centered!");
\end{lstlisting}
\end{tabular}

This is putting the lstlisting on the center but not its caption, that goes to the right. If I take out the tabular, then caption gets centered but the code goes to the left! :(

Thank you.


问:
How to create REST endpoint service consume multipart using Spring 4.x?
I am trying to create a REST service that consumes the "multipart/form-data" with text and attachment objects. For files i can use "org.springframework.web.multipart.MultipartFile", but how do i specify the service method for Text objects?

Below is the expected client call to service.

答:
create Rest endpoint by using this way

```<code>  public void sendEmail(@RequestParam String to,@RequestParam String from,@RequestParam String cc,@RequestParam String body, @RequestParam(required = false)MultipartFile[] file){
  }
</code>```

or

create pojo class for strings

```<code>public class Email{
  private String from;
  private String to;
  private String cc;
  private String body;
 // getters and setters
}
 //email should be json string
 public void sendEmail(@RequestParam String email,@RequestParam(required = false) MultipartFile[] file){
   ObjectMapper mapper=new ObjectMapper();
   Email email_pojo=mapper.readValue(email,Email.class);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
create Rest endpoint by using this way

  public void sendEmail(@RequestParam String to,@RequestParam String from,@RequestParam String cc,@RequestParam String body, @RequestParam(required = false)MultipartFile[] file){
  }

or

create pojo class for strings

public class Email{
  private String from;
  private String to;
  private String cc;
  private String body;
 // getters and setters
}
 //email should be json string
 public void sendEmail(@RequestParam String email,@RequestParam(required = false) MultipartFile[] file){
   ObjectMapper mapper=new ObjectMapper();
   Email email_pojo=mapper.readValue(email,Email.class);
}


问:
creation of Solr shard
I am trying to create multiple shard in SOLR but i am not able to create and getting error :

Cannot create collection dummypersoncollection(collectionName). Value of maxShardsPerNode is 1, and the number of live nodes is 1. This allows a maximum of 1 to be created. Value of numShards is 2 and value of replicationFactor is 1

is it possible for us to configure Solr to increase maxShardsPerNode?
if yes the let me know how to create

Thanks in advance

答:
You can provide maxShardsPerNode argument when creating the collection. For example:

```<code>curl "http://server:port/solr/admin/collections?action=CREATE&name=collection_name&numShards=5&replicationFactor=3&maxShardsPerNode=5&collection.configName=config_name&shards=s0,s1,s2,s3,s4"
</code>```

It will create a collection with 5 shards, 2 replicas each. If you have 2 nodes, maxShardsPerNode must be at least 5 to hold 10 replicas (if you set it lower, you get the error)

Title: creation of Solr shard

Body:
You can provide maxShardsPerNode argument when creating the collection. For example:

curl "http://server:port/solr/admin/collections?action=CREATE&name=collection_name&numShards=5&replicationFactor=3&maxShardsPerNode=5&collection.configName=config_name&shards=s0,s1,s2,s3,s4"

It will create a collection with 5 shards, 2 replicas each. If you have 2 nodes, maxShardsPerNode must be at least 5 to hold 10 replicas (if you set it lower, you get the error)


问:
Transfer files to azure vm using ip address
I need to create a release definition in VSTS in which one task will be to copy jar files to azure vms using their ip address. These ip addresses will be stored in some variable of release definition. We are able to do it using ssh file copy task but we are creating ssh endpoint for that where we specify the address as hard coded value but we need to use variable there instead of hard coded value.
Is their any way to do it using batch script or powershell script. We need to move jar files to ubuntu VM on Azure.</p>

答:
Refer to this blog: Copy files to an Azure VM through PSRemoting

Create credential with this code:

```<code>$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
</code>```

On other hand, there is Azure File Copy task

Body:
Refer to this blog: Copy files to an Azure VM through PSRemoting

Create credential with this code:

$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)

On other hand, there is Azure File Copy task


问:
Show single statistics in Grafana table
Using the Prometheus plugin, is it possible to show single statistics in a table as key:value table rows in stead of time series?

This means the current_value only.

E.g. node_uname_info giving:

```<code>key     | value
------- |-------
machine | x86_64
nodename| ServerName
release | 4.10.51-1-amd64
sysname | Linux
version | #1 SMP Debian 4.10.51-1
</code>```

Preferably I want to manually select one value per table row from different sources. E.g.:

```<code>A: node_uname_info.release
B: node_uname_info.version
C: "Some Manual String"
D: node_memory_MemTotal
</code>```

答:
As of Grafana 4.3, indeed you can:

http://docs.grafana.org/guides/whats-new-in-v4-3/#prometheus-table-data-column-per-label

But column C in your example, containing Some Random String, will be hard to accomplish in Grafana. Consider using Prometheus relabeling to permanently add additional data to you metrics in Prometheus.

Title: Show single statistics in Grafana table

Body:
Using the Prometheus plugin, is it possible to show single statistics in a table as key:value table rows in stead of time series?

This means the current_value only.

E.g. node_uname_info giving:

key     | value
------- |-------
machine | x86_64
nodename| ServerName
release | 4.10.51-1-amd64
sysname | Linux
version | #1 SMP Debian 4.10.51-1

Preferably I want to manually select one value per table row from different sources. E.g.:

A: node_uname_info.release
B: node_uname_info.version
C: "Some Manual String"
D: node_memory_MemTotal


问:
Adding to integers in a list which is inside a dictionary
I have a dictionary which houses some integer values in a list:

```<code>d = {"Numbers": [5, 10, 15, 20]}
</code>```

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

```<code>d = {"Numbers": [15, 20, 25, 30]}
</code>```

Thanks for the help!

答:
You can use list comprehension:

```<code>d['Numbers'] = [i+10 for i in d["Numbers"]]
</code>```

Slightly more verbose:

```<code>new = [i+10 for i in d['Numbers']]
d.update({"Numbers": new})
</code>```

Body:
I have a dictionary which houses some integer values in a list:

d = {"Numbers": [5, 10, 15, 20]}

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

d = {"Numbers": [15, 20, 25, 30]}

Thanks for the help!

Body:
You can use list comprehension:

d['Numbers'] = [i+10 for i in d["Numbers"]]

Slightly more verbose:

new = [i+10 for i in d['Numbers']]
d.update({"Numbers": new})


问:
Sending data stream from python program to web app
I have a python program appending lines to a .csv file every few seconds. I also have a web app that was created using Django. My goal is to continuously read the data from the python program as it runs and display it on the website without having to refresh.

My proposed solution is to send the python output to a server using requests.put(), and then read from the server using AJAX.

1.) Is this the best solution, or is there a better manner to connect the program and the site.

2.) If this is a good solution, what's the easiest way to get a server running to POST, PUT, and GET from? It can be local and will never expect heavy traffic.

Thank you!

答:
Reading from csv is not good solution,message quene is suitable solution for this context。

python program can post a data message to django when adding lines
to csv.

django webapp can send data message to browser when getting
message by SSE or socket.io lib


问:
.net WCF - CXF/WSS4j interoperability
I would like to consume a CXF web-service from a .net c# client. We are currently working with java-to-java requests and we protect SOAP envelopes through ws-security (WSS4J library).

My question is: how can I implement a C# WS-client which produces the same SOAP requests as the following client-side java code?

```<code>//doc is the original SOAP envelope to process with WSS4J
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);

//add username token with password digest
WSSecUsernameToken usrNameTok = new WSSecUsernameToken();
usrNameTok.setPasswordType(WSConstants.PASSWORD_DIGEST);
usrNameTok.setUserInfo("guest",psw_guest);
usrNameTok.prepare(doc);
usrNameTok.appendToHeader(secHeader);

//sign the envelope body with client key
WSSecSignature sign = new WSSecSignature();
sign.setUserInfo("clientx509v1", psw_clientx509v1);
sign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);

Document signedDoc = null;
sign.prepare(doc, sigCrypto, secHeader);
signedDoc = sign.build(doc, sigCrypto, secHeader);

//encrypt envelope body with server public key
WSSecEncrypt encrypt = new WSSecEncrypt();
encrypt.setUserInfo("serverx509v1");

// build the encrypted SOAP part
String out = null;
Document encryptedDoc = encrypt.build(signedDoc, encCrypto, secHeader);
return encryptedDoc;
</code>```

Does anybody know where I could find a microsoft how-to or a .net working example?

================================ EDIT ====================================

Thank you Ladislav! I applied your suggestions and I came up with something like:

```<code>X509Certificate2 client_pk, server_cert;
client_pk = new X509Certificate2(@"C:\x509\clientKey.pem", "blablabla");
server_cert = new X509Certificate2(@"C:\x509\server-cert.pfx", "blablabla");

// Create the binding.
System.ServiceModel.WSHttpBinding myBinding = new WSHttpBinding();
myBinding.TextEncoding = ASCIIEncoding.UTF8;
myBinding.MessageEncoding = WSMessageEncoding.Text;
myBinding.Security.Mode = SecurityMode.Message;
myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
myBinding.Security.Message.AlgorithmSuite =
            System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128;

// Disable credential negotiation and the establishment of
// a security context.
myBinding.Security.Message.NegotiateServiceCredential = false;
myBinding.Security.Message.EstablishSecurityContext = false;

// Create the endpoint address.
EndpointAddress ea =
    new EndpointAddress(new Uri("http://bla.bla.bla"),
            EndpointIdentity.CreateDnsIdentity("issuer"));

// configure the username credentials on the channel factory
UsernameClientCredentials credentials = new UsernameClientCredentials(new
                                    UsernameInfo("superadmin", "secret"));

// Create the client.
PersistenceClient client = new PersistenceClient(myBinding, ea);

client.Endpoint.Contract.ProtectionLevel =
            System.Net.Security.ProtectionLevel.EncryptAndSign;

// replace ClientCredentials with UsernameClientCredentials
client.Endpoint.Behaviors.Remove(typeof(ClientCredentials));
client.Endpoint.Behaviors.Add(credentials);

// Specify a certificate to use for authenticating the client.
client.ClientCredentials.ClientCertificate.Certificate = client_pk;

// Specify a default certificate for the service.
client.ClientCredentials.ServiceCertificate.DefaultCertificate = server_cert;

// Begin using the client.
client.Open();
clientProxyNetwork[] response = client.GetAllNetwork();
</code>```

As a result I get (server-side) the following CXF exception:

```<code> java.security.SignatureException: Signature does not match.
at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:421)
at sun.security.provider.certpath.BasicChecker.verifySignature(BasicChecker.java:133)
at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:112)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate  (PKIXMasterCertPathValidator.java:117)
</code>```

Therefore it seems a key jks->pem conversion problem... Or am I am missing something in the client-code above?

答:
This is usually pretty big problem because WCF does not support UserNameToken Profile with Digested password. I needed it few months ago and we had to implement our own custom binding but that code is not ready for publishing. Fortunatelly this blog article describes other implementation and contains sample code with new UserNameClientCredentials class supporting digested password.

Btw. same security configuration should be possible with older API called WSE 3.0. It was replaced by WCF but still some WS-* stack configuration are much simpler with that API and old ASMX services.

Title: .net WCF - CXF/WSS4j interoperability

Body:
I would like to consume a CXF web-service from a .net c# client. We are currently working with java-to-java requests and we protect SOAP envelopes through ws-security (WSS4J library).

My question is: how can I implement a C# WS-client which produces the same SOAP requests as the following client-side java code?

//doc is the original SOAP envelope to process with WSS4J
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);

//add username token with password digest
WSSecUsernameToken usrNameTok = new WSSecUsernameToken();
usrNameTok.setPasswordType(WSConstants.PASSWORD_DIGEST);
usrNameTok.setUserInfo("guest",psw_guest);
usrNameTok.prepare(doc);
usrNameTok.appendToHeader(secHeader);

//sign the envelope body with client key
WSSecSignature sign = new WSSecSignature();
sign.setUserInfo("clientx509v1", psw_clientx509v1);
sign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);

Document signedDoc = null;
sign.prepare(doc, sigCrypto, secHeader);
signedDoc = sign.build(doc, sigCrypto, secHeader);

//encrypt envelope body with server public key
WSSecEncrypt encrypt = new WSSecEncrypt();
encrypt.setUserInfo("serverx509v1");

// build the encrypted SOAP part
String out = null;
Document encryptedDoc = encrypt.build(signedDoc, encCrypto, secHeader);
return encryptedDoc;

Does anybody know where I could find a microsoft how-to or a .net working example?

================================ EDIT ====================================

Thank you Ladislav! I applied your suggestions and I came up with something like:

X509Certificate2 client_pk, server_cert;
client_pk = new X509Certificate2(@"C:\x509\clientKey.pem", "blablabla");
server_cert = new X509Certificate2(@"C:\x509\server-cert.pfx", "blablabla");

// Create the binding.
System.ServiceModel.WSHttpBinding myBinding = new WSHttpBinding();
myBinding.TextEncoding = ASCIIEncoding.UTF8;
myBinding.MessageEncoding = WSMessageEncoding.Text;
myBinding.Security.Mode = SecurityMode.Message;
myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
myBinding.Security.Message.AlgorithmSuite =
            System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128;

// Disable credential negotiation and the establishment of
// a security context.
myBinding.Security.Message.NegotiateServiceCredential = false;
myBinding.Security.Message.EstablishSecurityContext = false;

// Create the endpoint address.
EndpointAddress ea =
    new EndpointAddress(new Uri("http://bla.bla.bla"),
            EndpointIdentity.CreateDnsIdentity("issuer"));

// configure the username credentials on the channel factory
UsernameClientCredentials credentials = new UsernameClientCredentials(new
                                    UsernameInfo("superadmin", "secret"));

// Create the client.
PersistenceClient client = new PersistenceClient(myBinding, ea);

client.Endpoint.Contract.ProtectionLevel =
            System.Net.Security.ProtectionLevel.EncryptAndSign;

// replace ClientCredentials with UsernameClientCredentials
client.Endpoint.Behaviors.Remove(typeof(ClientCredentials));
client.Endpoint.Behaviors.Add(credentials);

// Specify a certificate to use for authenticating the client.
client.ClientCredentials.ClientCertificate.Certificate = client_pk;

// Specify a default certificate for the service.
client.ClientCredentials.ServiceCertificate.DefaultCertificate = server_cert;

// Begin using the client.
client.Open();
clientProxyNetwork[] response = client.GetAllNetwork();

As a result I get (server-side) the following CXF exception:

 java.security.SignatureException: Signature does not match.
at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:421)
at sun.security.provider.certpath.BasicChecker.verifySignature(BasicChecker.java:133)
at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:112)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate  (PKIXMasterCertPathValidator.java:117)

Therefore it seems a key jks->pem conversion problem... Or am I am missing something in the client-code above?


问:
Laravel 5.5 Web App and Ionic 3 Mobile App
I currently have a web app built on Laravel 5.5 with a MySQL DB and would like to build a Mobile App using Ionic 3/Angular 5.

From what I understand, Ionic needs Firebase as its backend for it to work with sockets (I need event broadcasts and server pushes). My concern is that my Mysql database is fairly complicated with over 120 tables all relationally linked together. Would it still work?

What is the best way for me to implement Ionic 5 with a Mysql DB that is being used by Laravel (with jquery)

Thanks for the guidance.

答:
You need to develop RESTful Web API using your Mysql DB and PHP/Laravel. After that, you can easily consume that API through Ionic 3 app. Ionic is just a front-end framework where it can consume any backend services.

Firebase has a lot of BAAS services. Its real-time DB or cloud firestore is just another service where we can use it as a database. Since you have your own DB then you don't need firebase database service. But still, you can use other firebase services like Cloud Messaging or else as you wish. If you have any other questions about this feel free to ask.

All Firebase services are here.


问:
Draw Tank in Certain Place
Currently, I am trying to make my tank to draw in the designated place that I have written in my code.

Code:

```<code>import pygame, assetloader
from pygame.locals import *
import random, time, math
import pygame

GRAD = math.pi/180
blue = (0, 0, 255)

wallRects = []

maze = [[] for i in range(25)]

assetloader.set_asset_path("assets/")

def generateMaze():
    global grid
    width  = 12
    height = 12
    seed   = time.time()

    random.seed(seed)

    grid = [[0 for j in range(width)] for i in range(height)]

    N, S, E, W = 1, 2, 4, 8
    DX         = { E: 1, W: -1, N: 0, S: 0 }
    DY         = { E: 0, W:  0, N: -1, S: 1 }
    OPPOSITE   = { E: W, W:  E, N: S, S: N }

    def carve_passages_from(cx, cy, grid):
        directions = random.sample([N, S, E, W], 4)

        for direction in directions:
            nx, ny = cx + DX[direction], cy + DY[direction]

            if (ny >= 0 and ny <= len(grid) - 1) and (nx >= 0 and nx <= len(grid[0]) - 1) and grid[ny][nx] == 0:
                grid[cy][cx] += direction
                grid[ny][nx] += OPPOSITE[direction]
                carve_passages_from(nx, ny, grid)

    carve_passages_from(0, 0, grid)

    global maze
    maze[0] = [2 for i in range(25)]
    mrow = 1

    # 0 = path
    # 1 = vertical wall
    # 2 = horizontal wall
    for y in range(height):
        row1 = maze[mrow]
        row2 = maze[mrow+1]
        row1.append(1)
        row2.append(1)
        for x in range(width):
            if grid[y][x] & S != 0:
                row1.append(0)
                row2.append(0)
            else:
                row1.append(0)
                row2.append(2)
            if grid[y][x] & E != 0:
                if (grid[y][x] | grid[y][x+1]) & S != 0:
                    row1.append(0)
                    row2.append(0)
                else:
                    row1.append(0)
                    row2.append(2)
            else:
                row1.append(1)
                if y < height - 1:
                    row2.append(1)
                else:
                    row2.append(2)
        mrow += 2

def printMaze():
    for row in range(len(maze)):
        for col in range(len(maze[row])):
            print maze[row][col],
        print

def CreateWallRects():
    for row in range(len(maze)):
        for col in range(len(maze[row])):
            if maze[row][col] == 1 and row < 23:
                x = (start_x + col * gsize) + (0.5 * gsize) - 1
                y = (start_y + (row - 1) * gsize) + (0.5 * gsize)
                wallRects.append(pygame.Rect(x, y, 3, gsize))
            elif maze[row][col] == 1 and row == 23:
                x = (start_x + col * gsize) + (0.5 * gsize) - 1
                y = (start_y + (row - 1) * gsize) + (0.5 * gsize)
                wallRects.append(pygame.Rect(x, y, 3, gsize * 2))
            elif maze[row][col] == 2:
                x = (start_x + (col-1) * gsize) + (0.5 * gsize)
                y = (start_y + row * gsize) + (0.5 * gsize) - 1
                wallRects.append(pygame.Rect(x, y, gsize * 2, 3))

def drawMaze():

    lineColor = 255, 255, 255

    for x in range(0, width, gsize):
        pygame.draw.line(screen, lineColor, (x, 0), (x, height), 3)    #line(Surface, color, start_pos, end_pos, width=1)

    for y in range(0, height, gsize):
        pygame.draw.line(screen, lineColor, (0, y), (width, y), 3)

    wallColor = 0, 0, 0
    for wr in wallRects:
        pygame.draw.rect(screen, wallColor, wr)

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, pos):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = assetloader.load_image("Tank.png", -1)
        self.rect.x = x
        self.rect.y = y
        self.rect.clamp_ip(screen.get_rect())
        self.dir = 0
        self.vel_y = 0
        self.vel_x = 0
        self.rows = pos[0]
        self.cols = pos[1]
        self.x = self.cols * gsize
        self.y = self.rows * gsize
 #       self.orig_image, self.orig_rect = assetloader.load_image(img_name, -1)
        self.orig_rect.x = self.x
        self.orig_rect.y = self.y
        self.orig_gun_pos = self.orig_rect.midtop
        self.ammo = 5
        self.vel = [0, 0]
        self.dead = False

    def draw(self, screen):
        image = pygame.transform.rotate(self.image, self.dir)
        screen.blit(image, self.rect)

    def update(self):
        oldCenter = self.rect.center

        self.rect = self.image.get_rect()
        self.rect.center = oldCenter
        screen_rect = screen.get_rect()
        keys = pygame.key.get_pressed()

        if keys[K_UP]:
            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = -1

               self.vel_y = -1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = 1
                self.vel_y = -1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = -1
                self.vel_y = 1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = 1
                self.vel_y = 1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 90 :
                self.vel_x = -1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 270:
                self.vel_x = 1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        elif keys[K_DOWN]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = 1

               self.vel_y = 1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = -1
                self.vel_y = 1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = 1
                self.vel_y = -1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = -1
                self.vel_y = -1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 90 :
                self.vel_x = 1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 270:
                self.vel_x = -1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        if keys[K_LEFT]:
            self.dir += 5
            if self.dir > 360:
                self.dir = 0
        elif keys[K_RIGHT]:
            self.dir -= 5
            if self.dir < -360:
                self.dir = 0

        if not screen_rect.contains(self.rect):
            self.rect.clamp_ip(screen_rect)

size = width, height = 500, 400
gsize = 25
start_x, start_y = 0, 0
bgColor = 255, 255, 255

pygame.init()
screen = pygame.display.set_mode(size)#, pygame.FULLSCREEN)
pygame.display.set_caption("Sample Sprite")
clock = pygame.time.Clock()

p = Player(width/2, height/4, pos)

coll_font = pygame.font.Font(None, 30)

going = True
while going:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                going = False

        p.update()

        screen.fill(bgColor)

        p.draw(screen)

        pygame.display.flip()

pygame.quit()
</code>```

I know that the init function that I used for class Player contains four things (self, x, y, pos), and I have Player(width/2, height/4, pos) to define where it gets placed right now - but it says pos is undefined. So what should I use to substitue or define "pos" somewhere else?

Right now, I am getting :

Traceback (most recent call last):
  File "tinytanks3.py", line 375, in <module>
    p = Player(width/2, height/4, pos)
NameError: name 'pos' is not defined
```

Can someone please explain what to put for pos and why?

答:
You can see from your Player class's __init__() method that pos is an argument that you need to specify when you create an instance of the class.

It should be a 2-element tuple of integers whose entries specify the columns and rows attributes of the created player object. You can tell this from the fact that elsewhere in your __init__() method, you have references to pos[0] and pos[1].

For example,

```<code>p = Player(width/2, height/2, (3,4))
</code>```

will create a player object named p, such that p.rows = 3 and p.columns = 4.

Title: Draw Tank in Certain Place

Body:
Currently, I am trying to make my tank to draw in the designated place that I have written in my code.

Code:

import pygame, assetloader
from pygame.locals import *
import random, time, math
import pygame

GRAD = math.pi/180
blue = (0, 0, 255)

wallRects = []

maze = [[] for i in range(25)]

assetloader.set_asset_path("assets/")

def generateMaze():
    global grid
    width  = 12
    height = 12
    seed   = time.time()

    random.seed(seed)

    grid = [[0 for j in range(width)] for i in range(height)]

    N, S, E, W = 1, 2, 4, 8
    DX         = { E: 1, W: -1, N: 0, S: 0 }
    DY         = { E: 0, W:  0, N: -1, S: 1 }
    OPPOSITE   = { E: W, W:  E, N: S, S: N }

    def carve_passages_from(cx, cy, grid):
        directions = random.sample([N, S, E, W], 4)

        for direction in directions:
            nx, ny = cx + DX[direction], cy + DY[direction]

            if (ny >= 0 and ny <= len(grid) - 1) and (nx >= 0 and nx <= len(grid[0]) - 1) and grid[ny][nx] == 0:
                grid[cy][cx] += direction
                grid[ny][nx] += OPPOSITE[direction]
                carve_passages_from(nx, ny, grid)

    carve_passages_from(0, 0, grid)

    global maze
    maze[0] = [2 for i in range(25)]
    mrow = 1

    # 0 = path
    # 1 = vertical wall
    # 2 = horizontal wall
    for y in range(height):
        row1 = maze[mrow]
        row2 = maze[mrow+1]
        row1.append(1)
        row2.append(1)
        for x in range(width):
            if grid[y][x] & S != 0:
                row1.append(0)
                row2.append(0)
            else:
                row1.append(0)
                row2.append(2)
            if grid[y][x] & E != 0:
                if (grid[y][x] | grid[y][x+1]) & S != 0:
                    row1.append(0)
                    row2.append(0)
                else:
                    row1.append(0)
                    row2.append(2)
            else:
                row1.append(1)
                if y < height - 1:
                    row2.append(1)
                else:
                    row2.append(2)
        mrow += 2

def printMaze():
    for row in range(len(maze)):
        for col in range(len(maze[row])):
            print maze[row][col],
        print

def CreateWallRects():
    for row in range(len(maze)):
        for col in range(len(maze[row])):
            if maze[row][col] == 1 and row < 23:
                x = (start_x + col * gsize) + (0.5 * gsize) - 1
                y = (start_y + (row - 1) * gsize) + (0.5 * gsize)
                wallRects.append(pygame.Rect(x, y, 3, gsize))
            elif maze[row][col] == 1 and row == 23:
                x = (start_x + col * gsize) + (0.5 * gsize) - 1
                y = (start_y + (row - 1) * gsize) + (0.5 * gsize)
                wallRects.append(pygame.Rect(x, y, 3, gsize * 2))
            elif maze[row][col] == 2:
                x = (start_x + (col-1) * gsize) + (0.5 * gsize)
                y = (start_y + row * gsize) + (0.5 * gsize) - 1
                wallRects.append(pygame.Rect(x, y, gsize * 2, 3))

def drawMaze():

    lineColor = 255, 255, 255

    for x in range(0, width, gsize):
        pygame.draw.line(screen, lineColor, (x, 0), (x, height), 3)    #line(Surface, color, start_pos, end_pos, width=1)

    for y in range(0, height, gsize):
        pygame.draw.line(screen, lineColor, (0, y), (width, y), 3)

    wallColor = 0, 0, 0
    for wr in wallRects:
        pygame.draw.rect(screen, wallColor, wr)

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, pos):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = assetloader.load_image("Tank.png", -1)
        self.rect.x = x
        self.rect.y = y
        self.rect.clamp_ip(screen.get_rect())
        self.dir = 0
        self.vel_y = 0
        self.vel_x = 0
        self.rows = pos[0]
        self.cols = pos[1]
        self.x = self.cols * gsize
        self.y = self.rows * gsize
 #       self.orig_image, self.orig_rect = assetloader.load_image(img_name, -1)
        self.orig_rect.x = self.x
        self.orig_rect.y = self.y
        self.orig_gun_pos = self.orig_rect.midtop
        self.ammo = 5
        self.vel = [0, 0]
        self.dead = False

    def draw(self, screen):
        image = pygame.transform.rotate(self.image, self.dir)
        screen.blit(image, self.rect)

    def update(self):
        oldCenter = self.rect.center

        self.rect = self.image.get_rect()
        self.rect.center = oldCenter
        screen_rect = screen.get_rect()
        keys = pygame.key.get_pressed()

        if keys[K_UP]:
            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = -1

               self.vel_y = -1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = 1
                self.vel_y = -1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = -1
                self.vel_y = 1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = 1
                self.vel_y = 1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 90 :
                self.vel_x = -1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 270:
                self.vel_x = 1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        elif keys[K_DOWN]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = 1

               self.vel_y = 1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = -1
                self.vel_y = 1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = 1
                self.vel_y = -1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = -1
                self.vel_y = -1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 90 :
                self.vel_x = 1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 270:
                self.vel_x = -1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        if keys[K_LEFT]:
            self.dir += 5
            if self.dir > 360:
                self.dir = 0
        elif keys[K_RIGHT]:
            self.dir -= 5
            if self.dir < -360:
                self.dir = 0

        if not screen_rect.contains(self.rect):
            self.rect.clamp_ip(screen_rect)

size = width, height = 500, 400
gsize = 25
start_x, start_y = 0, 0
bgColor = 255, 255, 255

pygame.init()
screen = pygame.display.set_mode(size)#, pygame.FULLSCREEN)
pygame.display.set_caption("Sample Sprite")
clock = pygame.time.Clock()

p = Player(width/2, height/4, pos)

coll_font = pygame.font.Font(None, 30)

going = True
while going:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                going = False

        p.update()

        screen.fill(bgColor)

        p.draw(screen)

        pygame.display.flip()

pygame.quit()

I know that the init function that I used for class Player contains four things (self, x, y, pos), and I have Player(width/2, height/4, pos) to define where it gets placed right now - but it says pos is undefined. So what should I use to substitue or define "pos" somewhere else?

Right now, I am getting :

Traceback (most recent call last):
  File "tinytanks3.py", line 375, in <module>
    p = Player(width/2, height/4, pos)
NameError: name 'pos' is not defined

Can someone please explain what to put for pos and why?

Body:
You can see from your Player class's __init__() method that pos is an argument that you need to specify when you create an instance of the class.

It should be a 2-element tuple of integers whose entries specify the columns and rows attributes of the created player object. You can tell this from the fact that elsewhere in your __init__() method, you have references to pos[0] and pos[1].

For example,

p = Player(width/2, height/2, (3,4))

will create a player object named p, such that p.rows = 3 and p.columns = 4.


问:
Javascript to typescript
I want to convert this code to typescript :

```<code>var dataSource = new DevExpress.data.DataSource({
    store: {
        type: "local",
        name: "MyLocalData",
        key: "id"
    }
});
</code>```

Thank you

答:
JavaScript is TypeScript so the following would work:

```<code>var dataSource = new DevExpress.data.DataSource({
    store: {
        type: "local",
        name: "MyLocalData",
        key: "id"
    }
});
</code>```

If it doesn't you might need to simply declare it:

```<code>declare var DevExpress: any; // Declare it

var dataSource = new DevExpress.data.DataSource({
    store: {
        type: "local",
        name: "MyLocalData",
        key: "id"
    }
});
</code>```

More

JavaScript is TypeScript : https://basarat.gitbooks.io/typescript/content/docs/javascript/recap.html

Title: Javascript to typescript

Body:
I want to convert this code to typescript :

var dataSource = new DevExpress.data.DataSource({
    store: {
        type: "local",
        name: "MyLocalData",
        key: "id"
    }
});

Thank you

Body:
JavaScript is TypeScript so the following would work:

var dataSource = new DevExpress.data.DataSource({
    store: {
        type: "local",
        name: "MyLocalData",
        key: "id"
    }
});

If it doesn't you might need to simply declare it:

declare var DevExpress: any; // Declare it

var dataSource = new DevExpress.data.DataSource({
    store: {
        type: "local",
        name: "MyLocalData",
        key: "id"
    }
});

More

JavaScript is TypeScript : https://basarat.gitbooks.io/typescript/content/docs/javascript/recap.html


问:
Information about remote IP addresses
I want to track all IP addresses with which my computer is communicating. I am using C# and Visual Studio. There is one listBox in which I will put all remote IP address. I am new to network programming so I need some direction about that kind of problem.

My question is how to do this? How to get information about remote IP addresses which which my computer make connections?

答:
Assuming you have ObservableCollection<string> mAccessInfo somewhere in your code as a publicly visible variable bound to your list, you could place this in the part of the code where you listen for connections:

```<code>Socket socketForClient = tcpListener.AcceptSocket( );

if (socketForClient.Connected)
{
    mAccessInfo.Add(socketForClient.RemoteEndPoint.ToString());
    //do other stuff...
}
</code>```

Since it's ObservableCollection, on each new connection that enters the list, the list you're bound to is updated.

Edit: As Cody Gray pointed out, this won't work if you have IP's in between as proxy/router/NAT etc...

Title: Information about remote IP addresses

Body:
Assuming you have ObservableCollection<string> mAccessInfo somewhere in your code as a publicly visible variable bound to your list, you could place this in the part of the code where you listen for connections:

Socket socketForClient = tcpListener.AcceptSocket( );

if (socketForClient.Connected)
{
    mAccessInfo.Add(socketForClient.RemoteEndPoint.ToString());
    //do other stuff...
}

Since it's ObservableCollection, on each new connection that enters the list, the list you're bound to is updated.

Edit: As Cody Gray pointed out, this won't work if you have IP's in between as proxy/router/NAT etc...


问:
Make TextBox Editable by ContextMenuStrip - c# winform
I have a textbox in my C# Winform. The program assigns a value to the textbox by default.

I want the user to have a right click function to edit this text at runtime. So when the user right click to edit, the backgroud should become white and user should be able to edit the text. And after editing, the background should return to default and non editable

I have created a ContextMenuStrip with right click event to edit text as follows and assigned readonly property to false when user right clicks and press edit menu item:

```<code>private void editTextToolStripMenuItem_Click(object sender, EventArgs e)
{
    itxt_CommonTitle.ReadOnly = false;
}
</code>```

I am not sure how to proceed further. Is this possible using textbox?

答:
If you have not changed the BackColor of the TextBox in the designer then the background color should automatically change from white to gray when you set ReadOnly = true and change from gray back to white when you set ReadOnly = false.  However, if you have changed it to something else in the designer, then the easiest way is just to set a private variable to remember the original BackColor before you enable the control for editing.  Then you can restore the color after you set it back to read-only.

```<code>private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
    MakeTextBoxEditable(itxt_CommonTitle);
}

private void itxt_CommonTitle_Leave(object sender, EventArgs e)
{
    MakeTextBoxReadOnly(itxt_CommonTitle);
}

private void Form1_Click(object sender, EventArgs e)
{
    MakeTextBoxReadOnly(itxt_CommonTitle);
}

private Color origTextBoxBackColor = SystemColors.Control;

private void MakeTextBoxEditable(TextBox textBox)
{
    origTextBoxBackColor = textBox.BackColor;
    textBox.ReadOnly = false;
    textBox.BackColor = Color.White;
    textBox.Focus();
}

private void MakeTextBoxReadOnly(TextBox textBox)
{
    textBox.ReadOnly = true;
    textBox.BackColor = origTextBoxBackColor;
}
</code>```

Body:
I have a textbox in my C# Winform. The program assigns a value to the textbox by default.

I want the user to have a right click function to edit this text at runtime. So when the user right click to edit, the backgroud should become white and user should be able to edit the text. And after editing, the background should return to default and non editable

I have created a ContextMenuStrip with right click event to edit text as follows and assigned readonly property to false when user right clicks and press edit menu item:

private void editTextToolStripMenuItem_Click(object sender, EventArgs e)
{
    itxt_CommonTitle.ReadOnly = false;
}

I am not sure how to proceed further. Is this possible using textbox?

Body:
If you have not changed the BackColor of the TextBox in the designer then the background color should automatically change from white to gray when you set ReadOnly = true and change from gray back to white when you set ReadOnly = false.  However, if you have changed it to something else in the designer, then the easiest way is just to set a private variable to remember the original BackColor before you enable the control for editing.  Then you can restore the color after you set it back to read-only.

private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
    MakeTextBoxEditable(itxt_CommonTitle);
}

private void itxt_CommonTitle_Leave(object sender, EventArgs e)
{
    MakeTextBoxReadOnly(itxt_CommonTitle);
}

private void Form1_Click(object sender, EventArgs e)
{
    MakeTextBoxReadOnly(itxt_CommonTitle);
}

private Color origTextBoxBackColor = SystemColors.Control;

private void MakeTextBoxEditable(TextBox textBox)
{
    origTextBoxBackColor = textBox.BackColor;
    textBox.ReadOnly = false;
    textBox.BackColor = Color.White;
    textBox.Focus();
}

private void MakeTextBoxReadOnly(TextBox textBox)
{
    textBox.ReadOnly = true;
    textBox.BackColor = origTextBoxBackColor;
}


问:
an efficient way to loop an slice/array in go
basically I have this:

```<code>package main

import "fmt"

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    var (
     s1 []Struct1
     s2 []Struct2
     s3 []Struct3
    )
    s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
}
</code>```

I want to show something like this:

Eliot Anderson real(true)

Tyrell Wellick real(true)

But I don't want to loop the s1 inside the s2 and then inside the s3

Example:

```<code>for i := 0; i < len(s1); i++ {
        for j := 0; j < len(s2); j++ {
            if s1[i].id == s2[j].id {
                for k := 0; k < len(s3); k++ {
                    if s2[j].id == s3[k].id {
                        // some code ...
                    }
                }
            }
        }
    }
</code>```

So, what other ways are there to doing that?

答:
Use a map for indexing the data by the person name.

```<code>type Person struct {
     firstName: string
     lastName: string
     real: string
}

var data map[int]Person
</code>```

Then look up and put data to the map.

Body:
basically I have this:

package main

import "fmt"

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    var (
     s1 []Struct1
     s2 []Struct2
     s3 []Struct3
    )
    s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
}

I want to show something like this:

Eliot Anderson real(true)

Tyrell Wellick real(true)

But I don't want to loop the s1 inside the s2 and then inside the s3

Example:

for i := 0; i < len(s1); i++ {
        for j := 0; j < len(s2); j++ {
            if s1[i].id == s2[j].id {
                for k := 0; k < len(s3); k++ {
                    if s2[j].id == s3[k].id {
                        // some code ...
                    }
                }
            }
        }
    }

So, what other ways are there to doing that?

Body:
Use a map for indexing the data by the person name.

type Person struct {
     firstName: string
     lastName: string
     real: string
}

var data map[int]Person

Then look up and put data to the map.


问:
How can I erase the old data from logcat?
When I execute the command

adb logcat

while running the android emulator, all of the old logs blow past and so I figure they are stored in a file somewhere. Is there a command I can run to clear the logs and start fresh? If not, is there some other way to do this?

答:
Dup of
How to empty (clear) the logcat buffer in Android

The following command will clear only non-rooted buffers (main, system ..etc).

```<code>adb logcat -c
</code>```

If you want to clear all the buffers (like radio, kernel..etc), Please use the following commands

```<code>adb logcat -b all -c
</code>```

or

```<code>adb root
adb shell logcat -b all -c
</code>```

Body:
Dup of
How to empty (clear) the logcat buffer in Android

The following command will clear only non-rooted buffers (main, system ..etc).

adb logcat -c

If you want to clear all the buffers (like radio, kernel..etc), Please use the following commands

adb logcat -b all -c

or

adb root
adb shell logcat -b all -c


问:
Best way to import a large dataset into Oracle sql database?
I'm new to oracle Database and I'm making a very simple bilingual dictionary ( 2 tables - English and French).

A dictionary often contains thousands of words. My question is that instead of writing thousand of [INSERT INTO ... VALUES] commands, is there any better way to somehow automate the process, like making a import form? Since the book my school provides only mentions about the INSERT command.

答:
If you have your data in a file, you can use the UTL_FILE package to read, parse and load your data.
Oracle ULT_FILE package

You can use Oracle's external table feature as well. See here
Oracle External tables


问:
Getting a list of folders in a directory
How do I get a list of the folders that exist in a certain directory with ruby?

Dir.entries() looks close but I don't know how to limit to folders only.

答:
We can combine Borh's answer and johannes' answer to get quite an elegant solution to getting the directory names in a folder.</p>

```<code># user globbing to get a list of directories for a path
base_dir_path = ''
directory_paths = Dir.glob(File.join(base_dir_path, '*', ''))

# or recursive version:
directory_paths = Dir.glob(File.join(base_dir_path, '**', '*', ''))

# cast to Pathname
directories = directory_paths.collect {|path| Pathname.new(path) }

# return the basename of the directories
directory_names = directories.collect {|dir| dir.basename.to_s }
</code>```

Body:
We can combine Borh's answer and johannes' answer to get quite an elegant solution to getting the directory names in a folder.

# user globbing to get a list of directories for a path
base_dir_path = ''
directory_paths = Dir.glob(File.join(base_dir_path, '*', ''))

# or recursive version:
directory_paths = Dir.glob(File.join(base_dir_path, '**', '*', ''))

# cast to Pathname
directories = directory_paths.collect {|path| Pathname.new(path) }

# return the basename of the directories
directory_names = directories.collect {|dir| dir.basename.to_s }


问:
XPath axis, get all following nodes until
I have the following example of HTML:

```<code><!-- lots of html -->
<h2>Foo bar</h2>
<p>lorem</p>
<p>ipsum</p>
<p>etc</p>

<h2>Bar baz</h2>
<p>dum dum dum</p>
<p>poopfiddles</p>
<!-- lots more html ... -->
</code>```

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

答:
Use:

(//h2[. = 'Foo bar'])[1]/following-sibling::p
   [1 = count(preceding-sibling::h2[1] | (//h2[. = 'Foo bar'])[1])]
```

<p>In case it is guaranteed that every <code>h2</code> has a distinct value, this may be simplified to:</p>

<pre class="lang-none prettyprint-override"><code>//h2[. = 'Foo bar']/following-sibling::p
   [1 = count(preceding-sibling::h2[1] | ../h2[. = 'Foo bar'])]
</code>```

This means: Select all p elements that are following siblings of the h2 (first or only one in the document) whose string value is 'Foo bar' and also the first preceding sibling h2 for all these p elements is exactly the h2(first or only one in the document) whose string value is'Foo bar'`.

Here we use a method of finding whether two nodes are identical:

```<code>count($n1 | $n2) = 1
</code>```

is true() exactly when the nodes $n1 and $n2 are the same node.

This expression can be generalized:

```<code>$x/following-sibling::p
       [1 = count(preceding-sibling::node()[name() = name($x)][1] | $x)]
</code>```

selects all "immediate following siblings" of any node specified by $x.

Body:
I have the following example of HTML:

Foo bar

lorem

ipsum

etc

Bar baz

dum dum dum

poopfiddles

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

Body:
Use:

(//h2[. = 'Foo bar'])[1]/following-sibling::p
   [1 = count(preceding-sibling::h2[1] | (//h2[. = 'Foo bar'])[1])]

In case it is guaranteed that every h2 has a distinct value, this may be simplified to:

//h2[. = 'Foo bar']/following-sibling::p
   [1 = count(preceding-sibling::h2[1] | ../h2[. = 'Foo bar'])]

This means: Select all p elements that are following siblings of the h2 (first or only one in the document) whose string value is 'Foo bar' and also the first preceding sibling h2 for all these p elements is exactly the h2(first or only one in the document) whose string value is'Foo bar'`.

Here we use a method of finding whether two nodes are identical:

count($n1 | $n2) = 1

is true() exactly when the nodes $n1 and $n2 are the same node.

This expression can be generalized:

$x/following-sibling::p
       [1 = count(preceding-sibling::node()[name() = name($x)][1] | $x)]

selects all "immediate following siblings" of any node specified by $x.


问:
Ionic local notifications. Is there a way to disable permissions from code?
I’m just looking to disable the permissions to trigger notifications using the app and not the settings of the device.</p>

答:
disable the permissions to trigger notifications using the app and not the settings of the device.

No. It is a user controlled feature.


问:
http-proxy-middleware create new session for per request
I build a proxy with http-proxy-middleware and it generates new session for every request, thus I can't validate the login status with token store in session.anynoe has idea to resolve this issue.

答:
```<code>// proxy middleware options
var options = {
  target: 'http://localhost:8081', // target host
  changeOrigin: true,               // needed for virtual hosted sites
  ws: true,                         // proxy websockets
  logLevel: "debug",
  pathRewrite: {
    '^/src/wxmservice/' : '/wxmservice/'
  },
  onProxyRes: function (proxyRes, req, res) {
    if (proxyRes.headers['set-cookie'] != undefined) {
        req.session['cookie'] = proxyRes.headers['set-cookie'];  // must be or you will get new session for each call
        req.session['proxy-cookie'] = proxyRes.headers['set-cookie'];  // add to other key because cookie will be lost
    }
    console.log("response: " + req.session.id);
    console.log(req.session);
  },
  onProxyReq: function (proxyReq, req, res) {
    // check for whether the session be freshed
    if (req.session.view)
      req.session.view ++;
    else
      req.session.view = 1;

    // use ower key to restore cookie
    if (req.session['proxy-cookie'] != undefined)
      proxyReq.setHeader('cookie', req.session['proxy-cookie'][0]);

    console.log("request: " + req.session.id);
    console.log(req.session);
  }
};

var session = require('express-session');
app.use(session({
    secret: 'sessiontest',
    resave: true,
    saveUninitialized:true
}));
</code>```

ContentLicense: CC BY-SA 4.0


问:
Not reading lesser or greater than input properly
So this is the problem section in a simple "Is your amount greater than or less than 50?" program. This section is entirely independent, but it doesn't work. If my input is 50 or anything less, it says "Sorry, not enough money." But strangely, from 100 and on, it also registers those amounts as "Sorry, that is not enough money." I've tried a bunch of things with it and I can't get it to work! What am I missing? Thank you!</p>

```<code>money_amount = input("Type your amount with no quotations.")

if money_amount <= "50":
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")
</code>```

答:
As @Brad Solomon suggests, you need to convert the value into a number (integer) before you can do reasonable mathematical comparisons.

So here is a simple solution:

```<code>money_amount = input("Type your amount with no quotations.")
money_amount = int(money_amount)

if money_amount <= 50:
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")
</code>```

Body:
So this is the problem section in a simple "Is your amount greater than or less than 50?" program. This section is entirely independent, but it doesn't work. If my input is 50 or anything less, it says "Sorry, not enough money." But strangely, from 100 and on, it also registers those amounts as "Sorry, that is not enough money." I've tried a bunch of things with it and I can't get it to work! What am I missing? Thank you!

money_amount = input("Type your amount with no quotations.")

if money_amount <= "50":
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")

Body:
As @Brad Solomon suggests, you need to convert the value into a number (integer) before you can do reasonable mathematical comparisons.

So here is a simple solution:

money_amount = input("Type your amount with no quotations.")
money_amount = int(money_amount)

if money_amount <= 50:
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")


问:
How can I sort dataframe with str+number
I got a dataframe now and try to sort it by 'No.'
dataframe is like:

```<code>         No.              value1                  value2
 0     NODE11              1654                     14
 1     NODE10              1710                    817
 2      NODE9              1162                     23
 3      NODE8              1883                    198
 4   no match              2303                      0
 5      NODE1              1098                     67
 6      NODE3              1488                     78
 7      NODE2              2426                     49
 8      NODE5              1974                     90
 9      NODE4              1767                     11
 10     NODE7              1708                     26
 11     NODE6              2418                    248
</code>```

I tried:

```<code>df.to_csv('count.csv',index = False)
df = pd.read_csv('count.csv', thousands=',', parse_dates=['No.'])
df = df.sort_values(by=['No.', 'only can on this node'], ascending=[True, False])
df.to_csv('count.csv',index = False)
</code>```

Its work but:

```<code>         No.              value1                 value2
 5      NODE1              1098                     67
 1     NODE10              1710                    817  -------error
 0     NODE11              1654                     14   -------error
 7      NODE2              2426                     49
 6      NODE3              1488                     78
 9      NODE4              1767                     11
 8      NODE5              1974                     90
 11     NODE6              2418                    248
 10     NODE7              1708                     26
 3      NODE8              1883                    198
 2      NODE9              1162                     23
 4   no match              2303                      0
</code>```

I dont know how to sort this dataframe because this sort key is str+number. any ideas? Thanks!

答:
When you are sorting by a string, it will sort alphabetically (i.e. 10 before 9).

I suggest you create a reference column, remove "Node", convert to a integer, sort accordingly and remove the reference column.

e.g.

```<code>#split into sortable and not
df_to_sort = df.ix[df['No.'] != "no match",:]
df_to_not_sort = df.ix[df['No.'] == "no match",:]

#create a reference column
df_to_sort.ix[:,'reference'] = df_to_sort['No.'].str.replace("NODE","")

#convert type to an integer
df_to_sort.ix[:,'reference'] = df.ix[:,'reference'].astype(int)

#sort the sortable part
df_sorted = df_to_sort.sort_values('reference')

#drop the reference column
df_sorted = df_sorted.drop(['reference'],axis=1)

#append the non sorted (i.e. no match) section to the bottom
df = df_sorted.append([df_to_not_sort])
</code>```

Hopefully that works!

FYI James' answer is way more succinct, use that.

Body:
I got a dataframe now and try to sort it by 'No.'
dataframe is like:

         No.              value1                  value2
 0     NODE11              1654                     14
 1     NODE10              1710                    817
 2      NODE9              1162                     23
 3      NODE8              1883                    198
 4   no match              2303                      0
 5      NODE1              1098                     67
 6      NODE3              1488                     78
 7      NODE2              2426                     49
 8      NODE5              1974                     90
 9      NODE4              1767                     11
 10     NODE7              1708                     26
 11     NODE6              2418                    248

I tried:

df.to_csv('count.csv',index = False)
df = pd.read_csv('count.csv', thousands=',', parse_dates=['No.'])
df = df.sort_values(by=['No.', 'only can on this node'], ascending=[True, False])
df.to_csv('count.csv',index = False)

Its work but:

         No.              value1                 value2
 5      NODE1              1098                     67
 1     NODE10              1710                    817  -------error
 0     NODE11              1654                     14   -------error
 7      NODE2              2426                     49
 6      NODE3              1488                     78
 9      NODE4              1767                     11
 8      NODE5              1974                     90
 11     NODE6              2418                    248
 10     NODE7              1708                     26
 3      NODE8              1883                    198
 2      NODE9              1162                     23
 4   no match              2303                      0

I dont know how to sort this dataframe because this sort key is str+number. any ideas? Thanks!

Body:
When you are sorting by a string, it will sort alphabetically (i.e. 10 before 9).

I suggest you create a reference column, remove "Node", convert to a integer, sort accordingly and remove the reference column.

e.g.

#split into sortable and not
df_to_sort = df.ix[df['No.'] != "no match",:]
df_to_not_sort = df.ix[df['No.'] == "no match",:]

#create a reference column
df_to_sort.ix[:,'reference'] = df_to_sort['No.'].str.replace("NODE","")

#convert type to an integer
df_to_sort.ix[:,'reference'] = df.ix[:,'reference'].astype(int)

#sort the sortable part
df_sorted = df_to_sort.sort_values('reference')

#drop the reference column
df_sorted = df_sorted.drop(['reference'],axis=1)

#append the non sorted (i.e. no match) section to the bottom
df = df_sorted.append([df_to_not_sort])

Hopefully that works!

FYI James' answer is way more succinct, use that.


问:
How to send a Salesforce platform event from AWS
I need help understanding how to authenticate and send data from AWS to the force.com API.

Specifically, I want to transform device data I receive in AWS into the Salesforce Platform Event format and send it to the Salesforce Platform Event API.

Thanks!

答:
Publishing a Platform Event on the force.com platform through their api works through essentially the same process as creating a record, and you can use either the Rest and SOAP api to do this.

A good overview can be found in the Platform Events Developer Guide.

As for authentication, there are a few options available. If your AWS application is going to have it's own SF license, the SOAP api's login method is pretty straightforward (link), otherwise, there are a collection of oAuth login flows available that you can reference in the REST API Developer Guide.


问:
Sending a csv file via curl POST to Django REST Framework endpoint
I have a csv file that I want to send via curl to a Django Rest Framework API View I have developed. The csv file itself contains only foo,bar and this is the curl command I'm using:

```<code>curl URL -H 'Accept:
application/json' -H 'Referer: http://localhost:5011/ost:5011' -H
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94
Safari/537.36' -H 'Authorization: JWT TOKEN  -H 'Content-Type:
multipart/form-data' -F upload=@testcsv.csv
</code>```

When it hits my API View in Django, and I run

```<code>request.data.get('file').read()
</code>```

the output is some metadata around the file and not the file contents itself:

```<code>(Pdb) b'--------------------------001ec735bfc1a929\r\nContent-
Disposition: form-data; name="upload";
filename="testcsv.csv"\r\nContent-Type: application/octet-
stream\r\n\r\n\r\n--------------------------001ec735bfc1a929--\r\n'
</code>```

How can I access the actual file itself through this method? My APIview is using

```<code>class FileUploadView(APIView):
     parser_classes = (MultiPartParser,)
</code>```

Thanks!

答:
```<code>f = request.FILES["filefield_name"]
</code>```

Body:
I have a csv file that I want to send via curl to a Django Rest Framework API View I have developed. The csv file itself contains only foo,bar and this is the curl command I'm using:

curl URL -H 'Accept:
application/json' -H 'Referer: http://localhost:5011/ost:5011' -H
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94
Safari/537.36' -H 'Authorization: JWT TOKEN  -H 'Content-Type:
multipart/form-data' -F upload=@testcsv.csv

When it hits my API View in Django, and I run

request.data.get('file').read()

the output is some metadata around the file and not the file contents itself:

(Pdb) b'--------------------------001ec735bfc1a929\r\nContent-
Disposition: form-data; name="upload";
filename="testcsv.csv"\r\nContent-Type: application/octet-
stream\r\n\r\n\r\n--------------------------001ec735bfc1a929--\r\n'

How can I access the actual file itself through this method? My APIview is using

class FileUploadView(APIView):
     parser_classes = (MultiPartParser,)

Thanks!

Body: f = request.FILES["filefield_name"]


问:
How would I change an equation to modulate a number on a line, to one that that modulates on a sine curve?
I'm trying to modulate an alpha value in a Java application I'm building on Android. Right now it goes like this:

```<code>if (goingUp) {
    newAlpha = oldAlpha + rateOfChange;
    if (newAlpha > maxAlpha) {
        newAlpha = maxAlpha;
        goingUp = false;
    }
} else {
    newAlpha = oldAlpha - rateOfChange;
    if (newAlpha < minAlpha) {
        newAlpha = minAlpha;
        goingUp = true;
    }
}
</code>```

Where rateOfChange is an arbitrary int that cannot be greater than maxAlpha. The equation is evaluate every tick in a thread and is independent of time.

Is there a way using only the variables given + Math.PI and other Math elements (I'm assuming Math.Sine will be in there) to get newAlpha to be a number on a Sine?

I'm thinking min and max would be the amp of the wave and rateOfChange would be a product of the Sine function, I just can't figure out how it all goes together.

答:
Based on duffymo's general equation I had to go all the way back to my TI-83 days (literally, put the app on my phone). But I was able to put all the pieces together so it ended up looking like this:

```<code>newAlpha = (int)((alphaMax - alphaMin) * 0.5 * Math.sin(rateOfChange * ticks + randomPhaseOffset) + (alphaMin + (alphaMax - alphaMin) * 0.5))
</code>```

FMI: http://en.wikipedia.org/wiki/Sine_wave

Body:
I'm trying to modulate an alpha value in a Java application I'm building on Android. Right now it goes like this:

if (goingUp) {
    newAlpha = oldAlpha + rateOfChange;
    if (newAlpha > maxAlpha) {
        newAlpha = maxAlpha;
        goingUp = false;
    }
} else {
    newAlpha = oldAlpha - rateOfChange;
    if (newAlpha < minAlpha) {
        newAlpha = minAlpha;
        goingUp = true;
    }
}

Where rateOfChange is an arbitrary int that cannot be greater than maxAlpha. The equation is evaluate every tick in a thread and is independent of time.

Is there a way using only the variables given + Math.PI and other Math elements (I'm assuming Math.Sine will be in there) to get newAlpha to be a number on a Sine?

I'm thinking min and max would be the amp of the wave and rateOfChange would be a product of the Sine function, I just can't figure out how it all goes together.

Body:
Based on duffymo's general equation I had to go all the way back to my TI-83 days (literally, put the app on my phone). But I was able to put all the pieces together so it ended up looking like this:

newAlpha = (int)((alphaMax - alphaMin) * 0.5 * Math.sin(rateOfChange * ticks + randomPhaseOffset) + (alphaMin + (alphaMax - alphaMin) * 0.5))

FMI: http://en.wikipedia.org/wiki/Sine_wave


问:
EF Core Table Splitting - One table to multiple classes
My table has four columns and I want to split it between multiple classes.

```<code>table1
 key
 col1
 col2
 col3
 col4

Class ClassA
  key
  col1
  col2

class ClassB
   key
   col3
   col4
</code>```

modelBuilder.Entity().ToTable("table1");

modelBuilder.Entity().ToTable("table1");

Currently it give me

System.InvalidOperationException: 'Cannot use table 'table1' for entity type 'ClassB' since it is being used for entity type 'ClassA'

Is it possible in EF Core?

Thanks

答:
You may need a relationship defined like the following based on to this MS docs:</p>

```<code>modelBuilder.Entity<ClassA>()
    .HasOne(e => e.ClassB).WithOne(e => e.ClassA)
    .HasForeignKey<ClassB>(e => e.Key);
modelBuilder.Entity<ClassA>().ToTable("Products");
modelBuilder.Entity<ClassB>().ToTable("Products");
</code>```

Body:
My table has four columns and I want to split it between multiple classes.

table1
 key
 col1
 col2
 col3
 col4

Class ClassA
  key
  col1
  col2

class ClassB
   key
   col3
   col4

modelBuilder.Entity().ToTable("table1");

modelBuilder.Entity().ToTable("table1");

Currently it give me

System.InvalidOperationException: 'Cannot use table 'table1' for entity type 'ClassB' since it is being used for entity type 'ClassA'

Is it possible in EF Core?

Thanks

Body:
You may need a relationship defined like the following based on to this MS docs:

modelBuilder.Entity<ClassA>()
    .HasOne(e => e.ClassB).WithOne(e => e.ClassA)
    .HasForeignKey<ClassB>(e => e.Key);
modelBuilder.Entity<ClassA>().ToTable("Products");
modelBuilder.Entity<ClassB>().ToTable("Products");


问:
React-redux : listening to state changes to trigger action
I have my redux state like this:

```<code>{
  parks: [
    {
      _id:"ad1esdad",
      fullName : "Some Name"
    },
    {
      _id:"ad1es3s",
      fullName : "Some Name2"
    }
  ],
  parkInfo: {
    id : "search Id",
    start_time : "Some Time",
    end_time : "Some Time"
  }
}
</code>```

I have a parkSelector component from which a user selects parkId and start_time and end_time

```<code>import React, { Component } from 'react';
import { changeParkInfo } from '../../Actions';

class ParkSelector extends Component {

  constructor(props) {
    super(props);

    this.handleApply = this.handleApply.bind(this);
    this.rederOptions = this.rederOptions.bind(this);

    this.state = {
      startDate: moment().subtract(1, 'days'),
      endDate: moment(),
      parkId : this.props.parks[0]
    };
  }

  handleApply(event) {
    this.setState({
      parkId : event.target.parkId.value
      startDate: event.target.start_time.value,
      endDate: event.target.end_time.value,
    });
    this.props.changeParkInfo(this.state.parkId,this.state.startDate,this.state.endDate);
  }

  rederOptions(){
    return _.map(this.props.parks,(park,index)=>{
      return(
        <option value={park._id} key={park._id}>{park.profile.fullName}</option>
      );
    });
  }

  render() {

    return (
      <div className="row">
        <div className="pb-4 col-sm-3">
          <form onSubmit={this.handleApply}>
          <select name="parkId" value={this.state.parkId} className="form-control input-sm">
              {this.rederOptions()}
          </select>
          <input name="start_time" type="date" />
          <input name="end_time" type="date" />
          <button type="submit">Apply</button>
          </form>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    parks : state.parks
  };
}

export default connect(mapStateToProps,{ changeParkInfo })(ParkSelector);
</code>```

I have another component 'stats' which needs to displays information related with parkInfo which will be loaded my api request.

```<code>import React, { Component } from 'react';
import StatsCard from '../../components/StatsCard';
import { getDashboardStats } from '../../Actions';

class Dashboard extends Component {

  constructor(props) {
    super(props);
  }

  render() {

    return (
      <div className="animated fadeIn">
        <div className="row">
          <StatsCard text="Revenue Collected" value={9999} cardStyle="card-success" />
          <StatsCard text="Total Checkins" value={39} cardStyle="card-info" />
          <StatsCard text="Total Checkouts" value={29} cardStyle="card-danger" />
          <StatsCard text="Passes Issued" value={119} cardStyle="card-warning" />
        </div>

      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    parkInfo : state.parkInfo,
    dashboardStats : state.dashboardStats
  };
}

export default connect(mapStateToProps,{ getDashboardStats })(Dashboard);
</code>```

I need to call getDashboardStats action (which makes api call and stores in results in dashboardStats of the redux state) whenever the redux state of parkInfo changes.

What is the best way to call this action, I have tried componentWillUpdate but it keeps on updating infinitely. What is best practice for this scenario ?

答:
Goal: A change in parkInfo redux-state should prompt Dashboard to dispatch getDashboardInfo and re-render. (This behavior will also be similar in other components).

I use babel transform-class-properties, syntax is slightly different.

example:

```<code>// SomeLayout.js

import ParkSelector from 'containers/ParkSelector'
import Dashboard from 'containers/Dashboard'

const SomeLayout = () => {
  return (
    <div>
      <ParkSelector />
      <Dashboard />
    </div>
  )
}

export default SomeLayout
</code>```

-

```<code>// Dashboard.js

// connect maps redux-state to *props* not state, so a new park selection
//  will not trigger this component to re-render, so no infinite loop there

@connect((store) => ({ currentParkId: store.parkInfo.id }, //decorator syntax
                     { getDashboardStats })
)
class Dashboard extends Component {
  state = {
    currentId: this.props.currentParkID,
    parkInfoFoo: '',
    parkInfoBar: ''
  }

  // using null for when no park has been selected, in which case nothing runs
  //  here.
  componentWillReceiveProps(nextProps) {

    // when Dashboard receives new id via props make API call
    // assumes you are setting initial state of id to null in your reducer
    if (nextProps.currentParkId !== null) {
      getDashboardStats(`someurl/info/${nextProps.id}`).then((data) => {

        // update state of Dashboard, triggering a re-render
        this.setState({
          currentId: nextProps.id
          parkInfoFoo: data.foo,
          parkInfoBar: data.bar
        })
      })
    }
  }

  render() {
    const { currentId, parkInfoFoo } = this.state

    if (currentId !== null) {
       return <span>{parkInfoFoo}</span>
    }
    return null
  }
}

export default Dashboard
</code>```

Body:
I have my redux state like this:

{
  parks: [
    {
      _id:"ad1esdad",
      fullName : "Some Name"
    },
    {
      _id:"ad1es3s",
      fullName : "Some Name2"
    }
  ],
  parkInfo: {
    id : "search Id",
    start_time : "Some Time",
    end_time : "Some Time"
  }
}

I have a parkSelector component from which a user selects parkId and start_time and end_time

import React, { Component } from 'react';
import { changeParkInfo } from '../../Actions';

class ParkSelector extends Component {

  constructor(props) {
    super(props);

    this.handleApply = this.handleApply.bind(this);
    this.rederOptions = this.rederOptions.bind(this);

    this.state = {
      startDate: moment().subtract(1, 'days'),
      endDate: moment(),
      parkId : this.props.parks[0]
    };
  }

  handleApply(event) {
    this.setState({
      parkId : event.target.parkId.value
      startDate: event.target.start_time.value,
      endDate: event.target.end_time.value,
    });
    this.props.changeParkInfo(this.state.parkId,this.state.startDate,this.state.endDate);
  }

  rederOptions(){
    return _.map(this.props.parks,(park,index)=>{
      return(
        <option value={park._id} key={park._id}>{park.profile.fullName}</option>
      );
    });
  }

  render() {

    return (

          <form onSubmit={this.handleApply}>
          <select name="parkId" value={this.state.parkId} className="form-control input-sm">
              {this.rederOptions()}
          </select>
          <input name="start_time" type="date" />
          <input name="end_time" type="date" />
          <button type="submit">Apply</button>
          </form>

    )
  }
}

function mapStateToProps(state){
  return {
    parks : state.parks
  };
}

export default connect(mapStateToProps,{ changeParkInfo })(ParkSelector);

I have another component 'stats' which needs to displays information related with parkInfo which will be loaded my api request.

import React, { Component } from 'react';
import StatsCard from '../../components/StatsCard';
import { getDashboardStats } from '../../Actions';

class Dashboard extends Component {

  constructor(props) {
    super(props);
  }

  render() {

    return (

          <StatsCard text="Revenue Collected" value={9999} cardStyle="card-success" />
          <StatsCard text="Total Checkins" value={39} cardStyle="card-info" />
          <StatsCard text="Total Checkouts" value={29} cardStyle="card-danger" />
          <StatsCard text="Passes Issued" value={119} cardStyle="card-warning" />

    )
  }
}

function mapStateToProps(state){
  return {
    parkInfo : state.parkInfo,
    dashboardStats : state.dashboardStats
  };
}

export default connect(mapStateToProps,{ getDashboardStats })(Dashboard);

I need to call getDashboardStats action (which makes api call and stores in results in dashboardStats of the redux state) whenever the redux state of parkInfo changes.

What is the best way to call this action, I have tried componentWillUpdate but it keeps on updating infinitely. What is best practice for this scenario ?

Body:
Goal: A change in parkInfo redux-state should prompt Dashboard to dispatch getDashboardInfo and re-render. (This behavior will also be similar in other components).

I use babel transform-class-properties, syntax is slightly different.

example:

// SomeLayout.js

import ParkSelector from 'containers/ParkSelector'
import Dashboard from 'containers/Dashboard'

const SomeLayout = () => {
  return (
    <div>
      <ParkSelector />
      <Dashboard />
    </div>
  )
}

export default SomeLayout

-

// Dashboard.js

// connect maps redux-state to *props* not state, so a new park selection
//  will not trigger this component to re-render, so no infinite loop there

@connect((store) => ({ currentParkId: store.parkInfo.id }, //decorator syntax
                     { getDashboardStats })
)
class Dashboard extends Component {
  state = {
    currentId: this.props.currentParkID,
    parkInfoFoo: '',
    parkInfoBar: ''
  }

  // using null for when no park has been selected, in which case nothing runs
  //  here.
  componentWillReceiveProps(nextProps) {

    // when Dashboard receives new id via props make API call
    // assumes you are setting initial state of id to null in your reducer
    if (nextProps.currentParkId !== null) {
      getDashboardStats(`someurl/info/${nextProps.id}`).then((data) => {

        // update state of Dashboard, triggering a re-render
        this.setState({
          currentId: nextProps.id
          parkInfoFoo: data.foo,
          parkInfoBar: data.bar
        })
      })
    }
  }

  render() {
    const { currentId, parkInfoFoo } = this.state

    if (currentId !== null) {
       return <span>{parkInfoFoo}</span>
    }
    return null
  }
}

export default Dashboard


问:
Using Widgets in Google Colaboratory
Is it possible to use Jupyter Widgets in Google Colaboratory?

I followed the instructions here, both with ipyleaflet and bqplot

But I got this error message.

Failed to display Jupyter Widget of type Map.

If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean that the widgets JavaScript is still loading. If this message persists, it likely means that the widgets JavaScript library is either not installed or not enabled. See the Jupyter Widgets Documentation for setup instructions.

If you're reading this message in another frontend (for example, a static rendering on GitHub or NBViewer), it may mean that your frontend doesn't currently support widgets.

Is it possible to use these widgets? Or did I make a mistake somewhere?

答:
It is not currently possible to use them- currently comms messages are not supported, the WidgetManager code is not loaded into outputframes, and multiple output frames on a page is not a configuration that the WidgetManager works with.

Feel free to open a bug at https://github.com/googlecolab/colabtools/issues

Title: Using Widgets in Google Colaboratory


问:
The ImageBase's Address of Excutable file
Why does the ImageBase is difference between CFF and OllyDbg?

答:
CFF is showing you static analysis, meaning it's just reading the file from disk not debugging it at runtime, showing you the "Preferred ImageBase" from the PE header, this is where the binary wants to be loaded at runtime.

When you do dynamic analysis such as with ollydbg it's showing you the values in the PE header at runtime, ImageBase will hold the current ImageBase, not the preferred one from disk.  But when you read DllCharacteristics from the optional PE header you will see it is set to 0x8140.

The 0x0040 = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE meaning Address Space Layout Randomisation is enabled, causing the Windows loader to load modules into random addresses in effort to make exploits more difficult because hard coded jmps and addresses will not be accurate.

The exploit developers now need to calculate everything at runtime, well unless you use Windows 8 or 10 because a bug has been causing ASLR to not work correctly...


问:
Compact Framework Current Folder
How do I know which is the current folder of an App?

I mean... Is there a way to know where is the exe located from the running code?

答:
The following is correct.```<code>string fullAppName = Assembly.GetCallingAssembly().GetName().CodeBase;
fullAppPath = Path.GetDirectoryName(fullAppName);</code>```
For equivalent code in other languages Refer to this link
</p>

Title: Compact Framework Current Folder

Body:
The following is correct.
string fullAppName = Assembly.GetCallingAssembly().GetName().CodeBase;
fullAppPath = Path.GetDirectoryName(fullAppName);

For equivalent code in other languages Refer to this link


问:
Type 'Object' is defined in an assembly that is not referenced (NET Standard 2.0/.NET Framework 4.6.1)
I'm using the .NET Standard 2.0 preview, on which my Class Libraries are based.

After having trouble with a few NuGet packages, especially regarding archive extraction, I decided to migrate my .NET Core 2.0 Console projects back to the .NET Framework 4.6.1.

The .NET Framework 4.6.1 is supposed to implement the .NET Standard 2.0 specification - according to different sources. Especially the dotnet/standard GitHub Repo.

Unfortunately, the migration to the .NET Framework resulted in the following errrors throughout all of .NET Framework Console projects:

Error CS0012  The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

Where Object can be anything: Enum, Task, ...

How would I reference .NET Standard 2.0 class libraries with .NET Framework (4.6.1) without getting such errors?

答:
I had this issue in my test project when using TestServer to test my MVC views.

The test project, web project and associated libraries were all netcoreapp2.0.

Upgrading vs2017 to 15.5 did not work, and editing my test .csproj with the following suggested fixes did not work:

<RestoreProjectStyle>PackageReference</RestoreProjectStyle>

<ItemGroup><Reference Include="netstandard" /></ItemGroup>

<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>

As per https://github.com/aspnet/Razor/issues/1212#issuecomment-297885722 however, this worked:

```<code>  <Target Name="CopyDepsFiles" AfterTargets="Build" Condition="'$(TargetFramework)'!=''">
    <ItemGroup>
      <DepsFilePaths Include="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />
    </ItemGroup>
    <Copy SourceFiles="%(DepsFilePaths.FullPath)" DestinationFolder="$(OutputPath)" Condition="Exists('%(DepsFilePaths.FullPath)')" />
  </Target>
</code>```

Body:
I had this issue in my test project when using TestServer to test my MVC views.

The test project, web project and associated libraries were all netcoreapp2.0.

Upgrading vs2017 to 15.5 did not work, and editing my test .csproj with the following suggested fixes did not work:

<RestoreProjectStyle>PackageReference</RestoreProjectStyle>

<ItemGroup><Reference Include="netstandard" /></ItemGroup>

<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>

As per https://github.com/aspnet/Razor/issues/1212#issuecomment-297885722 however, this worked:

  <Target Name="CopyDepsFiles" AfterTargets="Build" Condition="'$(TargetFramework)'!=''">
    <ItemGroup>
      <DepsFilePaths Include="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />
    </ItemGroup>
    <Copy SourceFiles="%(DepsFilePaths.FullPath)" DestinationFolder="$(OutputPath)" Condition="Exists('%(DepsFilePaths.FullPath)')" />
  </Target>


问:
Current code displays a list from A2 cell, but I want the VBA code to be modified in such a way that the list starts from B2 cell?
The VBA code displayed below helps in capturing list of filenames in folders and sub-folders and displays that list in the excel sheet starting from A2 cell, but I want the VBA code to be modified in such a way that the list starts from B2 cell ?

```<code>Sub MainList()

    Set folder = Application.FileDialog(msoFileDialogFolderPicker)

    If folder.Show <> -1 Then Exit Sub

    xDir = folder.SelectedItems(1)
    Call ListFilesInFolder(xDir, True)
End Sub

Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
    Dim xFileSystemObject As Object
    Dim xFolder As Object
    Dim xSubFolder As Object
    Dim xFile As Object
    Dim rowIndex As Long

    rowIndex = 2

    Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Set xFolder = xFileSystemObject.GetFolder(xFolderName)

    rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1

    For Each xFile In xFolder.Files
        Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name
        rowIndex = rowIndex + 1
    Next xFile

    If xIsSubfolders Then
        For Each xSubFolder In xFolder.SubFolders
            ListFilesInFolder xSubFolder.Path, True
        Next xSubFolder
    End If

    Set xFile = Nothing
    Set xFolder = Nothing
    Set xFileSystemObject = Nothing
End Sub

Function GetFileOwner(ByVal xPath As String, ByVal xName As String)
    Dim xFolder As Object
    Dim xFolderItem As Object
    Dim xShell As Object

    xName = StrConv(xName, vbUnicode)
    xPath = StrConv(xPath, vbUnicode)

    Set xShell = CreateObject("Shell.Application")
    Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))

    If Not xFolder Is Nothing Then
        Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))
    End If

    If Not xFolderItem Is Nothing Then
        GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
    Else
        GetFileOwner = ""
    End If

    Set xShell = Nothing
    Set xFolder = Nothing
    Set xFolderItem = Nothing
End Function
</code>```

Please let me know how to do the modification, so that the starting cell will be B2 instead of A2.

答:
Change the part that says:

```<code>Cells(rowIndex, 1)
</code>```

to

```<code>Cells(rowIndex, 2).
</code>```

Also some recommended reading:

Referring to Ranges in VBA

Excel VBA For Complete Beginners (a free course)

 -

Body:
The VBA code displayed below helps in capturing list of filenames in folders and sub-folders and displays that list in the excel sheet starting from A2 cell, but I want the VBA code to be modified in such a way that the list starts from B2 cell ?

Sub MainList()

    Set folder = Application.FileDialog(msoFileDialogFolderPicker)

    If folder.Show <> -1 Then Exit Sub

    xDir = folder.SelectedItems(1)
    Call ListFilesInFolder(xDir, True)
End Sub

Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
    Dim xFileSystemObject As Object
    Dim xFolder As Object
    Dim xSubFolder As Object
    Dim xFile As Object
    Dim rowIndex As Long

    rowIndex = 2

    Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Set xFolder = xFileSystemObject.GetFolder(xFolderName)

    rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1

    For Each xFile In xFolder.Files
        Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name
        rowIndex = rowIndex + 1
    Next xFile

    If xIsSubfolders Then
        For Each xSubFolder In xFolder.SubFolders
            ListFilesInFolder xSubFolder.Path, True
        Next xSubFolder
    End If

    Set xFile = Nothing
    Set xFolder = Nothing
    Set xFileSystemObject = Nothing
End Sub

Function GetFileOwner(ByVal xPath As String, ByVal xName As String)
    Dim xFolder As Object
    Dim xFolderItem As Object
    Dim xShell As Object

    xName = StrConv(xName, vbUnicode)
    xPath = StrConv(xPath, vbUnicode)

    Set xShell = CreateObject("Shell.Application")
    Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))

    If Not xFolder Is Nothing Then
        Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))
    End If

    If Not xFolderItem Is Nothing Then
        GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
    Else
        GetFileOwner = ""
    End If

    Set xShell = Nothing
    Set xFolder = Nothing
    Set xFolderItem = Nothing
End Function

Please let me know how to do the modification, so that the starting cell will be B2 instead of A2.

Body:
Change the part that says:

Cells(rowIndex, 1)

to

Cells(rowIndex, 2).

Also some recommended reading:

Referring to Ranges in VBA

Excel VBA For Complete Beginners (a free course)

 -