问:
Optional arguments in Objective-C 2.0?
In Objective-C 2.0, is it possible to make a method where the argument is optional? That is, you can have a method call like this:

```<code>[aFraction print];
</code>```

as well as this:

```<code>[aFraction print: someParameter];
</code>```

in the same program.

Apple's Objective-C 2.0 Programming Language guide contrasts Obj-C with Python and seems to say this is not allowed. I'm still learning and I want to be sure. If it is possible, then what is the syntax, because my second code example does not work.

Update:
OK, I just made two methods, both named "print".

header

```<code>-(void) print;
-(void) print: (BOOL) someSetting;
</code>```

implementation

```<code>-(void) print {
    [self print:0];
}

-(void) print: (BOOL) someSetting {
    BOOL sv;
    sv = someSetting;

    if ( sv ) {
        NSLog(@"cool stuff turned on");
    }
    else {
        NSLog(@"cool stuff turned off");
    }
}
</code>```

the relevant program lines

```<code>    ...
    printParamFlag = TRUE;

// no parameter
    [aCodeHolder print];

// single parameter
    [aCodeHolder print:printParamFlag];
    ...
</code>```

I can't believe that worked. Is there any reason I shouldn't do this?

答:
The way you did it is the right way to do it in Objective-C. It's used extensively in Cocoa itself. For example, some of NSString's initializers:

```<code>– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:
</code>```

The reason it works is because the : is part of the method name, so as far as the compiler is concerned, print and print: are completely different messages that are no more closely connected than "print" and "sprint".

However, the particular names of the methods you gave aren't a very good case for this, because it's unclear from the name what the parameter is (or what "print" by itself means if the parameter is what the object prints). It would be better to have, say, printFalseMessage and printMessageWithFlag:.

Title: Optional arguments in Objective-C 2.0?

Body:
In Objective-C 2.0, is it possible to make a method where the argument is optional? That is, you can have a method call like this:

[aFraction print];

as well as this:

[aFraction print: someParameter];

in the same program.

Apple's Objective-C 2.0 Programming Language guide contrasts Obj-C with Python and seems to say this is not allowed. I'm still learning and I want to be sure. If it is possible, then what is the syntax, because my second code example does not work.

Update:
OK, I just made two methods, both named "print".

header

-(void) print;
-(void) print: (BOOL) someSetting;

implementation

-(void) print {
    [self print:0];
}

-(void) print: (BOOL) someSetting {
    BOOL sv;
    sv = someSetting;

    if ( sv ) {
        NSLog(@"cool stuff turned on");
    }
    else {
        NSLog(@"cool stuff turned off");
    }
}

the relevant program lines

    ...
    printParamFlag = TRUE;

// no parameter
    [aCodeHolder print];

// single parameter
    [aCodeHolder print:printParamFlag];
    ...

I can't believe that worked. Is there any reason I shouldn't do this?

Body:
The way you did it is the right way to do it in Objective-C. It's used extensively in Cocoa itself. For example, some of NSString's initializers:

– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:

The reason it works is because the : is part of the method name, so as far as the compiler is concerned, print and print: are completely different messages that are no more closely connected than "print" and "sprint".

However, the particular names of the methods you gave aren't a very good case for this, because it's unclear from the name what the parameter is (or what "print" by itself means if the parameter is what the object prints). It would be better to have, say, printFalseMessage and printMessageWithFlag:.

OwnerDisplayName: Chuck


来源: stackexchange

问:
jQuery Select by Name and ID
I have a table like so:

```<code>    <table>
        <tr>
            <td>
                <input type="radio" name="Sample1" id="Sample1" value="1" />
                <input type="radio" name="Sample1" id="Sample2" value="1" />
            </td>
            <td>
                <input type="radio" name="Sample2" id="Sample1" value="1" />
                <input type="radio" name="Sample2" id="Sample2" value="1" />
            </td>
            etc....
        </tr>
    </table>
</code>```

I want to be able to select a specific radio button by name and id. E.G., select the radio button with the name Sample2 and id Sample1. I tried doing this:

```<code>    $('[id="Sample1"][name="Sample2"]').checked = true;
</code>```

But no luck... How should I be doing this?

答:
.checked = true is wrong. Use .attr('checked', true).

Also, you may only use an ID once. IDs are unique identifiers for elements. I have no idea what you're trying to accomplish here, but:

```<code><html>
    <body>
        <input type="radio" name="Sample1" id="SampleA" />
        <input type="radio" name="Sample1" id="SampleB" />
        <input type="radio" name="Sample2" id="SampleC" />
        <input type="radio" name="Sample2" id="SampleD" />

        <script type="text/javascript">
        $(function() {
            $('#SampleC[name="Sample2"]').attr('checked', true);

            // [id="SampleC"][name="Sample2"] works too
        });
        </script>
    </body>
</html>
</code>```

does the job.

Edit

Actually .attr('checked', 'checked') is more portable.

ContentLicense: CC BY-SA 3.0

Title: jQuery Select by Name and ID

Body:
I have a table like so:

                <input type="radio" name="Sample1" id="Sample1" value="1" />
                <input type="radio" name="Sample1" id="Sample2" value="1" />

                <input type="radio" name="Sample2" id="Sample1" value="1" />
                <input type="radio" name="Sample2" id="Sample2" value="1" />

            etc....

I want to be able to select a specific radio button by name and id. E.G., select the radio button with the name Sample2 and id Sample1. I tried doing this:

    $('[id="Sample1"][name="Sample2"]').checked = true;

But no luck... How should I be doing this?

Body:
.checked = true is wrong. Use .attr('checked', true).

Also, you may only use an ID once. IDs are unique identifiers for elements. I have no idea what you're trying to accomplish here, but:

<html>
    <body>
        <input type="radio" name="Sample1" id="SampleA" />
        <input type="radio" name="Sample1" id="SampleB" />
        <input type="radio" name="Sample2" id="SampleC" />
        <input type="radio" name="Sample2" id="SampleD" />

        <script type="text/javascript">
        $(function() {
            $('#SampleC[name="Sample2"]').attr('checked', true);

            // [id="SampleC"][name="Sample2"] works too
        });
        </script>
    </body>
</html>

does the job.

Edit

Actually .attr('checked', 'checked') is more portable.


问:
How to Run container from docker compose after 1 hour
I have 10 container in docker compose.
I want 9 containers to start working when i up the docker compose and allow docker-compose to run the 10th container after 1 hour of time.

Currently its running all containers at once.

How i can achieve this ?

答:
Docker Compose doesn’t directly have this functionality.  (Kubernetes doesn’t either, though it does have the ability to run a short-lived container at a specified time of day.)

Probably the best workaround to the problem as you’ve stated it is to use a tool like at(1) to run an additional container at a later time

```<code>at +1h docker run ...
</code>```

My experience has generally been that it can get a little messy to depend on starting and stopping Docker containers for workflow management.  You may be better off starting a pool of workers against some job queue system like RabbitMQ and injecting a job after an hour, or using a language-native scheduled-task library in your application, and just always start every container every time.

ContentLicense: CC BY-SA 4.0

Body:
Docker Compose doesn’t directly have this functionality.  (Kubernetes doesn’t either, though it does have the ability to run a short-lived container at a specified time of day.)

Probably the best workaround to the problem as you’ve stated it is to use a tool like at(1) to run an additional container at a later time

at +1h docker run ...

My experience has generally been that it can get a little messy to depend on starting and stopping Docker containers for workflow management.  You may be better off starting a pool of workers against some job queue system like RabbitMQ and injecting a job after an hour, or using a language-native scheduled-task library in your application, and just always start every container every time.


问:
setSharing method on App Script not working for G Suite users?
I am trying to create a document and set its access permissions.
The code below works on my normal Gmail account.

However, when I run it on my unique GSuite address, it returns this error:

TypeError: Cannot find function setSharing in object Document. (line
  6, file "Code")

Here is the code:

```<code>    function createAndSendDocument() {

  //Create a new Google Doc named 'Hello, world!'
  var doc = DocumentApp.create('Hello World');

  //Set user permissions to view and edit.
  doc.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT);

  //Access the body of the document, then add a Paragraph.
  doc.getBody().appendParagraph('This is a test document for people to see and try and lorem ipsum.');

  //Get the URL of the doc
  var url = doc.getUrl();

  //Get email address of the active user - aka you.
  var email = 'example@domain.com';

  //Get the name of doc to use as an email subject line
  var subject = doc.getName();

  //Add a new strong to the url variable to use as an email body.
  var body = 'Link to your document: ' + url;

  //Send yourself an email with a link to the document.
  GmailApp.sendEmail(email, subject, body);

}
</code>```

How can I work around this or use the setSharing method correctly? Am I using the wrong method or am I missing other steps as

答:
I had a similar problem myself that might help you. I used the DocumentApp api to create a document. Then I used the DriveApp api to set the sharing. Notice the the URLs you get from the same document are different. If you email the URL you get for the document from the DocumentApp with someone outside your G Suite organization, they will have to sign in to open the document even though the sharing is set to "Anyone with the link. No sign-in required." But if you email the URL that you get from DriveApp to the person outside your G Suite organization, they will be able to open the link easily, with no sign-in required. So I think your code might work better if you used DriveApp to set the sharing of the document you create. Then make sure that you email the URL you get from the DriveApp api instead of the URL you get from the DocumentApp api.   </p>

```<code>function myFunction() {
var doc = DocumentApp.create("Test Document");
Logger.log("This is the URL that I get with DocumentApp: " + doc.getUrl());

var documentFileID = doc.getId();
var myFileDriveApp = DriveApp.getFileById(documentFileID);
Logger.log("This is the drive app URL: " + myFileDriveApp.getUrl());

//Set the sharing on the file using DriveApp
myFileDriveApp.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
</code>```

<p>}</p>

Body:
I am trying to create a document and set its access permissions.
The code below works on my normal Gmail account.

However, when I run it on my unique GSuite address, it returns this error:

TypeError: Cannot find function setSharing in object Document. (line
  6, file "Code")

Here is the code:

    function createAndSendDocument() {

  //Create a new Google Doc named 'Hello, world!'
  var doc = DocumentApp.create('Hello World');

  //Set user permissions to view and edit.
  doc.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT);

  //Access the body of the document, then add a Paragraph.
  doc.getBody().appendParagraph('This is a test document for people to see and try and lorem ipsum.');

  //Get the URL of the doc
  var url = doc.getUrl();

  //Get email address of the active user - aka you.
  var email = 'example@domain.com';

  //Get the name of doc to use as an email subject line
  var subject = doc.getName();

  //Add a new strong to the url variable to use as an email body.
  var body = 'Link to your document: ' + url;

  //Send yourself an email with a link to the document.
  GmailApp.sendEmail(email, subject, body);

}

How can I work around this or use the setSharing method correctly? Am I using the wrong method or am I missing other steps as

Body:
I had a similar problem myself that might help you. I used the DocumentApp api to create a document. Then I used the DriveApp api to set the sharing. Notice the the URLs you get from the same document are different. If you email the URL you get for the document from the DocumentApp with someone outside your G Suite organization, they will have to sign in to open the document even though the sharing is set to "Anyone with the link. No sign-in required." But if you email the URL that you get from DriveApp to the person outside your G Suite organization, they will be able to open the link easily, with no sign-in required. So I think your code might work better if you used DriveApp to set the sharing of the document you create. Then make sure that you email the URL you get from the DriveApp api instead of the URL you get from the DocumentApp api.

function myFunction() {
var doc = DocumentApp.create("Test Document");
Logger.log("This is the URL that I get with DocumentApp: " + doc.getUrl());

var documentFileID = doc.getId();
var myFileDriveApp = DriveApp.getFileById(documentFileID);
Logger.log("This is the drive app URL: " + myFileDriveApp.getUrl());

//Set the sharing on the file using DriveApp
myFileDriveApp.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);

}


问:
Why am i getting null in java from xml even though value is present in xml?
Im trying to build java object for xml by

java code

```<code> JAXBContext jaxbContext = JAXBContext.newInstance(Enfinity.class);
         Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
         Enfinity enfinity = (Enfinity) jaxbUnmarshaller.unmarshal(xmlFile);
</code>```

xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<enfinity xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dt="http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt" xsi:schemaLocation="http://www.intershop.com/xml/ns/intershop/customer/impex/7.3 b2b_customer.xsd http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt dt.xsd" major="6" minor="1" family="enfinity" branch="enterprise" build="1.0.299">
    <customer id="34627">
    <customer-type>SMB</customer-type>
    <company-name>xxxxx & xxxxx</company-name>
    <industry>Retail</industry>
    <enabled>1</enabled>
    <approval-status>1</approval-status>
    <custom-attributes>
    <custom-attribute name="CustomerPriceLevel" dt:dt="string">4</custom-attribute>
    <custom-attribute name="FreeFreightThreshold" dt:dt="string">300.00</custom-attribute>
    <custom-attribute name="ECOMCustomerId" dt:dt="string">xxxxxx</custom-attribute>
    <custom-attribute name="BlockCreditCardPayment" dt:dt="boolean">true</custom-attribute>
    <custom-attribute name="CustomLoad" dt:dt="string">true</custom-attribute>
    </custom-attributes>
    <users>
    <user business-partner-no="xxxx">
    <business-partner-no>xxxxx</business-partner-no>
    <profile>
    <first-name>xxxx</first-name>
    <last-name>xxxx</last-name>
    <email>xxx</email>
    </profile>
    <user-groups>
    <user-group id="IG_SMBCustomers"/>
    <user-group id="IG_RecurringUsers"/>
    <user-group id="52"/>
    </user-groups>
    </user>
    <user business-partner-no="xxxxx">
    <business-partner-no>xxxxx</business-partner-no>
    <profile>
    <credentials>
    <login>xxxxx.com</login>
    <password encrypted="1">xxxxx</password>
    <enabled>1</enabled>
    <reminder-email>xxxxxx.com</reminder-email>
    <password-creation-date>2019-03-28T06:37:29-07:00</password-creation-date>
    </credentials>
    <creation-date>2019-02-28T03:45:43-08:00</creation-date>
    <phone-home>xxxxxx</phone-home>
    <email>xxxxxxxxx.com</email>
    <last-name>xxxxx</last-name>
    <first-name>xxxxxx</first-name>
    <custom-attributes>
    <custom-attribute name="RoleID" dt:dt="string">APP_B2B_BUYER</custom-attribute>
    </custom-attributes>
    </profile>
    </user>
    </users>
</code>```

when I try to get login from user tag even though value is there im getting null my poji looks like

Customer

```<code>package com.poc.highline;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlElement (name = "id")
    String id;
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @XmlElement (name = "customer-type")
    String customerType;
    public String getCustomerType() {
        return customerType;
    }

    public void setCustomerType(String customerType) {
        this.customerType = customerType;
    }

    @XmlElement (name = "company-name")
    String companyName;
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    @XmlElement (name = "industry")
    String industry;
    public String getIndustry() {
        return industry;
    }

    public void setIndustry(String industry) {
        this.industry = industry;
    }

    @XmlElement (name = "enabled")
    String enabled;
    public String getEnabled() {
        return enabled;
    }

    public void setEnabled(String enabled) {
        this.enabled = enabled;
    }

    @XmlElement (name = "approval-status")
    String approvalStatus;
    public String getApprovalStatus() {
        return approvalStatus;
    }

    public void setApprovalStatus(String approvalStatus) {
        this.approvalStatus = approvalStatus;
    }

    @XmlElement (name = "custom-attributes")
     List<customAttributes> customAttributes;
    public List<customAttributes> getCustomAttributes() {
        return customAttributes;
    }

    public void setCustomAttributes(List<customAttributes> customAttributes) {
        this.customAttributes = customAttributes;
    }

    @XmlElement (name = "users")
    List<Users> users;
    public List<Users> getUsers() {
        return users;
    }

    public void setUsers(List<Users> users) {
        this.users = users;
    }

    @XmlElement (name = "preferred-invoice-to-address")
    PreferredInvoiceAddress invoiceAddress;
    public PreferredInvoiceAddress getInvoiceAddress() {
        return invoiceAddress;
    }

    public void setInvoiceAddress(PreferredInvoiceAddress invoiceAddress) {
        this.invoiceAddress = invoiceAddress;
    }

    @XmlElement (name = "addresses")
    List<Addresses> addresses;
    public List<Addresses> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Addresses> addresses) {
        this.addresses = addresses;
    }

}

</code>```

This is users POJO class

Users

```<code>package com.poc.highline;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "users")
@XmlAccessorType(XmlAccessType.FIELD)
public class Users {

@XmlElement(name="user")
List<User> user;
public List<User> getUser() {
    return user;
}

public void setUser(List<User> user) {
    this.user = user;
}
}

</code>```

this is the user POJO class

user

```<code>package com.poc.highline;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {

@XmlElement(name = "business-partner-no")
String id;
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@XmlElement(name = "profile")
String profile;
public String getProfile() {
    return profile;
}

public void setProfile(String profile) {
    this.profile = profile;
}

@XmlElement(name = "credentials")
String credentials;

public String getCredentials() {
    return credentials;
}

public void setCredentials(String credentials) {
    this.credentials = credentials;
}

String login;
public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}

String email;
public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}

</code>```

Im getting value in id but not in other variable refer the watchList

```<code>enfinity    Enfinity  (id=30)
    customer    ArrayList<E>  (id=32)
        [0] Customer  (id=43)
            addresses   ArrayList<E>  (id=45)
            approvalStatus  "1" (id=46)
            companyName "xxxxx & xxxxx" (id=49)
            customAttributes    ArrayList<E>  (id=50)
            customerType    "SMB" (id=51)
            enabled "1" (id=52)
            id  null
            industry    "Retail" (id=53)
            invoiceAddress  PreferredInvoiceAddress  (id=54)
            users   ArrayList<E>  (id=56)
                [0] Users  (id=58)
                    user    ArrayList<E>  (id=60)
                        [0] User  (id=62)
                            credentials null
                            email   null
                            id  "xxxxx" (id=65)
                            login   null
                            profile "\n    " (id=66)
                        [1] User  (id=63)
                            credentials null
                            email   null
                            id  "xxxxx" (id=67)
                            login   null
                            profile "\n    " (id=68)

</code>```

please help thanks in advance.

答:
You are getting null for the Id of your customer because it's not an @XmlElement. Use @XmlAttribute instead.

For clarification:

```<code><customer id="1">
  <name>somename</name>
<customer>

id: @XmlAttribute
name: @XmlElement
somename: @XmlValue
</code>```

Check https://howtodoinjava.com/jaxb/jaxb-annotations/ or other Jaxb tutorials for other annotations.

Edit:

For login and email, you have to annotate them with @XmlAttribute as well.

Body:
Im trying to build java object for xml by

java code

 JAXBContext jaxbContext = JAXBContext.newInstance(Enfinity.class);
         Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
         Enfinity enfinity = (Enfinity) jaxbUnmarshaller.unmarshal(xmlFile);

xml

<?xml version="1.0" encoding="UTF-8"?>
<enfinity xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dt="http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt" xsi:schemaLocation="http://www.intershop.com/xml/ns/intershop/customer/impex/7.3 b2b_customer.xsd http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt dt.xsd" major="6" minor="1" family="enfinity" branch="enterprise" build="1.0.299">
    <customer id="34627">
    <customer-type>SMB</customer-type>
    <company-name>xxxxx & xxxxx</company-name>
    <industry>Retail</industry>
    <enabled>1</enabled>
    <approval-status>1</approval-status>
    <custom-attributes>
    <custom-attribute name="CustomerPriceLevel" dt:dt="string">4</custom-attribute>
    <custom-attribute name="FreeFreightThreshold" dt:dt="string">300.00</custom-attribute>
    <custom-attribute name="ECOMCustomerId" dt:dt="string">xxxxxx</custom-attribute>
    <custom-attribute name="BlockCreditCardPayment" dt:dt="boolean">true</custom-attribute>
    <custom-attribute name="CustomLoad" dt:dt="string">true</custom-attribute>
    </custom-attributes>
    <users>
    <user business-partner-no="xxxx">
    <business-partner-no>xxxxx</business-partner-no>
    <profile>
    <first-name>xxxx</first-name>
    <last-name>xxxx</last-name>
    <email>xxx</email>
    </profile>
    <user-groups>
    <user-group id="IG_SMBCustomers"/>
    <user-group id="IG_RecurringUsers"/>
    <user-group id="52"/>
    </user-groups>
    </user>
    <user business-partner-no="xxxxx">
    <business-partner-no>xxxxx</business-partner-no>
    <profile>
    <credentials>
    <login>xxxxx.com</login>
    <password encrypted="1">xxxxx</password>
    <enabled>1</enabled>
    <reminder-email>xxxxxx.com</reminder-email>
    <password-creation-date>2019-03-28T06:37:29-07:00</password-creation-date>
    </credentials>
    <creation-date>2019-02-28T03:45:43-08:00</creation-date>
    <phone-home>xxxxxx</phone-home>
    <email>xxxxxxxxx.com</email>
    <last-name>xxxxx</last-name>
    <first-name>xxxxxx</first-name>
    <custom-attributes>
    <custom-attribute name="RoleID" dt:dt="string">APP_B2B_BUYER</custom-attribute>
    </custom-attributes>
    </profile>
    </user>
    </users>

when I try to get login from user tag even though value is there im getting null my poji looks like

Customer

package com.poc.highline;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlElement (name = "id")
    String id;
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @XmlElement (name = "customer-type")
    String customerType;
    public String getCustomerType() {
        return customerType;
    }

    public void setCustomerType(String customerType) {
        this.customerType = customerType;
    }

    @XmlElement (name = "company-name")
    String companyName;
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    @XmlElement (name = "industry")
    String industry;
    public String getIndustry() {
        return industry;
    }

    public void setIndustry(String industry) {
        this.industry = industry;
    }

    @XmlElement (name = "enabled")
    String enabled;
    public String getEnabled() {
        return enabled;
    }

    public void setEnabled(String enabled) {
        this.enabled = enabled;
    }

    @XmlElement (name = "approval-status")
    String approvalStatus;
    public String getApprovalStatus() {
        return approvalStatus;
    }

    public void setApprovalStatus(String approvalStatus) {
        this.approvalStatus = approvalStatus;
    }

    @XmlElement (name = "custom-attributes")
     List<customAttributes> customAttributes;
    public List<customAttributes> getCustomAttributes() {
        return customAttributes;
    }

    public void setCustomAttributes(List<customAttributes> customAttributes) {
        this.customAttributes = customAttributes;
    }

    @XmlElement (name = "users")
    List<Users> users;
    public List<Users> getUsers() {
        return users;
    }

    public void setUsers(List<Users> users) {
        this.users = users;
    }

    @XmlElement (name = "preferred-invoice-to-address")
    PreferredInvoiceAddress invoiceAddress;
    public PreferredInvoiceAddress getInvoiceAddress() {
        return invoiceAddress;
    }

    public void setInvoiceAddress(PreferredInvoiceAddress invoiceAddress) {
        this.invoiceAddress = invoiceAddress;
    }

    @XmlElement (name = "addresses")
    List<Addresses> addresses;
    public List<Addresses> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Addresses> addresses) {
        this.addresses = addresses;
    }

}

This is users POJO class

Users

package com.poc.highline;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "users")
@XmlAccessorType(XmlAccessType.FIELD)
public class Users {

@XmlElement(name="user")
List<User> user;
public List<User> getUser() {
    return user;
}

public void setUser(List<User> user) {
    this.user = user;
}
}

this is the user POJO class

user

package com.poc.highline;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {

@XmlElement(name = "business-partner-no")
String id;
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@XmlElement(name = "profile")
String profile;
public String getProfile() {
    return profile;
}

public void setProfile(String profile) {
    this.profile = profile;
}

@XmlElement(name = "credentials")
String credentials;

public String getCredentials() {
    return credentials;
}

public void setCredentials(String credentials) {
    this.credentials = credentials;
}

String login;
public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}

String email;
public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}

Im getting value in id but not in other variable refer the watchList

enfinity    Enfinity  (id=30)
    customer    ArrayList<E>  (id=32)
        [0] Customer  (id=43)
            addresses   ArrayList<E>  (id=45)
            approvalStatus  "1" (id=46)
            companyName "xxxxx & xxxxx" (id=49)
            customAttributes    ArrayList<E>  (id=50)
            customerType    "SMB" (id=51)
            enabled "1" (id=52)
            id  null
            industry    "Retail" (id=53)
            invoiceAddress  PreferredInvoiceAddress  (id=54)
            users   ArrayList<E>  (id=56)
                [0] Users  (id=58)
                    user    ArrayList<E>  (id=60)
                        [0] User  (id=62)
                            credentials null
                            email   null
                            id  "xxxxx" (id=65)
                            login   null
                            profile "\n    " (id=66)
                        [1] User  (id=63)
                            credentials null
                            email   null
                            id  "xxxxx" (id=67)
                            login   null
                            profile "\n    " (id=68)

please help thanks in advance.

Body:
You are getting null for the Id of your customer because it's not an @XmlElement. Use @XmlAttribute instead.

For clarification:

<customer id="1">
  <name>somename</name>
<customer>

id: @XmlAttribute
name: @XmlElement
somename: @XmlValue

Check https://howtodoinjava.com/jaxb/jaxb-annotations/ or other Jaxb tutorials for other annotations.

Edit:

For login and email, you have to annotate them with @XmlAttribute as well.


问:
Changing datatype of a column in database
I have to change the datatype of a column from CHAR to INTEGER in database. I used the following query:

```<code>ALTER TABLE cert_request
    ALTER column CERT_REQUEST_NBR SET TYPE(INTEGER);
</code>```

however it's showing error in the keyword "column" and giving the error code as -104 on execution. Following is the error log;

```<code>Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=ALTER TABLE CERT_REQUEST   ALTER CERT_R;BEGIN-OF-STATEMENT;<create_proc>, DRIVER=3.50.152
SQLState:  42601
ErrorCode: -104
</code>```

I also tried the using the Modify keyword, but it isn't identified in my database.

I also tried the following query but again of no use.

```<code>alter table CERT_REQUEST alter column cert_request_nbr  integer
</code>```

It gives the following error

```<code>Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=integer;umn cert_request_nbr;<alter_col_action1>, DRIVER=3.50.152
SQLState:  42601
ErrorCode: -104
</code>```

Please provide me some suggestions.

答:
You are missing the word 'Data' between 'Set' and 'Type'.

It should be like this:

ALTER TABLE cert_request
    ALTER column CERT_REQUEST_NBR SET DATA TYPE(INTEGER);

Body:
I have to change the datatype of a column from CHAR to INTEGER in database. I used the following query:

ALTER TABLE cert_request
    ALTER column CERT_REQUEST_NBR SET TYPE(INTEGER);

however it's showing error in the keyword "column" and giving the error code as -104 on execution. Following is the error log;

Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=ALTER TABLE CERT_REQUEST   ALTER CERT_R;BEGIN-OF-STATEMENT;<create_proc>, DRIVER=3.50.152
SQLState:  42601
ErrorCode: -104

I also tried the using the Modify keyword, but it isn't identified in my database.

I also tried the following query but again of no use.

alter table CERT_REQUEST alter column cert_request_nbr  integer

It gives the following error

Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=integer;umn cert_request_nbr;<alter_col_action1>, DRIVER=3.50.152
SQLState:  42601
ErrorCode: -104

Please provide me some suggestions.


问:
Drop-down menu not showing values using Thymeleaf
I am creating a Spring Boot application using Maven and Thymeleaf.
I have a class Sessi0n, and another one Module. Sessi0n contains a list of Module (modules).

What I need to do, is to display in a template (using Thymeleaf) my Sessi0n(s), and populate a drop-down list with the module(s) affected to each sessi0n.

Here is my code:

```<code>    <select>
      <th:block th:each="module : ${sessi0n.modules}">
        <p th:text="${module.libelleModule}"></p>
     </th:block>
    </select>
</code>```

I already searched on sites, read the documentation and looked throughout the solutions proposed by Stackoverflow. Even if there are some suggestions that may be suitable for my situation, I still can not figure it out, how to do, in order to make my code work (for each sessi0n that I choose, show me a drop-down menu with all the modules related for this sessi0n).

Many thanks guys, I am new to Thymeleaf, your help would be greatly appreciated.

```<code>    @Entity
    public class Module {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelleModule;
    private int duree;
    //getters //setters

    @Entity
    public class Sessi0n {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelle;
    private Date dateDebut;
    private Date dateFin;
    @OneToMany (cascade = CascadeType.ALL);
    private List<Module> modules;
    //getter //setter
</code>```

答:
try this: </p>

```<code><select>
    <option th:each="module : ${sessi0n.modules}"
    th:text="${module.libelleModule}">
    </option>
</select>
</code>```

Body:
I am creating a Spring Boot application using Maven and Thymeleaf.
I have a class Sessi0n, and another one Module. Sessi0n contains a list of Module (modules).

What I need to do, is to display in a template (using Thymeleaf) my Sessi0n(s), and populate a drop-down list with the module(s) affected to each sessi0n.

Here is my code:

    <select>

    </select>

I already searched on sites, read the documentation and looked throughout the solutions proposed by Stackoverflow. Even if there are some suggestions that may be suitable for my situation, I still can not figure it out, how to do, in order to make my code work (for each sessi0n that I choose, show me a drop-down menu with all the modules related for this sessi0n).

Many thanks guys, I am new to Thymeleaf, your help would be greatly appreciated.

    @Entity
    public class Module {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelleModule;
    private int duree;
    //getters //setters

    @Entity
    public class Sessi0n {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelle;
    private Date dateDebut;
    private Date dateFin;
    @OneToMany (cascade = CascadeType.ALL);
    private List<Module> modules;
    //getter //setter

Body:
try this:

<select>
    <option th:each="module : ${sessi0n.modules}"
    th:text="${module.libelleModule}">
    </option>
</select>


问:
How can I add an array to a WCF data contract?
I am trying to use the following class in a Windows Communication Foundation project written in Visual Studio 2012:

```<code>[DataContract]
public class SimCoilData : SimInventoryItemData
{
    [DataMember]
    public UnitTemperature? RequiredCoolingHotspot { get; set; }
    [DataMember]
    public UnitTemperature? RequiredHeatingColdspot { get; set; }
    [DataMember]
    public UnitTemperature? HeatingHotspotLimit { get; set; }

    [DataMember]
    public TimeSpan? TimeToRequiredColdspot { get; set; }
    [DataMember]
    public TimeSpan? TimeToRequiredCoolingHotspot { get; set; }
    [DataMember]
    public TimeSpan? TimeToHeatingHotspotLimit { get; set; }

    [DataMember]
    public UnitLength Gauge { get; set; }
    [DataMember]
    public UnitLength Width { get; set; }
    [DataMember]
    public double[] Temperatures { get; set; }

    public SimCoilData() : base()
    {

    }

}
</code>```

Before the addition of the Temperatures array, data was being exchanged well between the server and the client.  I added the Temperatures array, rebuilt the server application, and ran it.  Then, in the client project, I updated the service reference and rebuilt the project.  When I run the client, I get an error message that a meaningless reply was received, which could be caused by a few things, including a data contract mismatch.  I have verified that the array is being populated on the server side.  What is the correct procedure for adjusting my client application to accept the array?

答:
The problem appeared to be that I had not reserved enough space in the client for the messages.  I found that I could handle 250 doubles per object but not 300 doubles per object.   A Google search for "WCF maximum message size" led me to the maxBufferSize and maxReceivedMessageSize parameters.  With this configuration for my client, I was able to get all 1800 values in my arrays:</p>

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
      <bindings>
        <netTcpBinding>
          <binding name="NetTcpBinding_ISimShopServiceLib"
            openTimeout="00:01:00"
            closeTimeout="00:00:05"
            sendTimeout="00:01:00"
            receiveTimeout="00:01:00"
            maxBufferSize="5000000"
            maxReceivedMessageSize="5000000">
          </binding>
        </netTcpBinding>
      </bindings>
      <client>
        <endpoint address="net.tcp://localhost:1236/SimShopService" binding="netTcpBinding"
          bindingConfiguration="NetTcpBinding_ISimShopServiceLib" contract="SimShopServiceReference.ISimShopServiceLib"
          name="NetTcpBinding_ISimShopServiceLib">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
      </client>

    </system.serviceModel>
</configuration>
</code>```

Body:
I am trying to use the following class in a Windows Communication Foundation project written in Visual Studio 2012:

[DataContract]
public class SimCoilData : SimInventoryItemData
{
    [DataMember]
    public UnitTemperature? RequiredCoolingHotspot { get; set; }
    [DataMember]
    public UnitTemperature? RequiredHeatingColdspot { get; set; }
    [DataMember]
    public UnitTemperature? HeatingHotspotLimit { get; set; }

    [DataMember]
    public TimeSpan? TimeToRequiredColdspot { get; set; }
    [DataMember]
    public TimeSpan? TimeToRequiredCoolingHotspot { get; set; }
    [DataMember]
    public TimeSpan? TimeToHeatingHotspotLimit { get; set; }

    [DataMember]
    public UnitLength Gauge { get; set; }
    [DataMember]
    public UnitLength Width { get; set; }
    [DataMember]
    public double[] Temperatures { get; set; }

    public SimCoilData() : base()
    {

    }

}

Before the addition of the Temperatures array, data was being exchanged well between the server and the client.  I added the Temperatures array, rebuilt the server application, and ran it.  Then, in the client project, I updated the service reference and rebuilt the project.  When I run the client, I get an error message that a meaningless reply was received, which could be caused by a few things, including a data contract mismatch.  I have verified that the array is being populated on the server side.  What is the correct procedure for adjusting my client application to accept the array?

Body:
The problem appeared to be that I had not reserved enough space in the client for the messages.  I found that I could handle 250 doubles per object but not 300 doubles per object.   A Google search for "WCF maximum message size" led me to the maxBufferSize and maxReceivedMessageSize parameters.  With this configuration for my client, I was able to get all 1800 values in my arrays:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
      <bindings>
        <netTcpBinding>
          <binding name="NetTcpBinding_ISimShopServiceLib"
            openTimeout="00:01:00"
            closeTimeout="00:00:05"
            sendTimeout="00:01:00"
            receiveTimeout="00:01:00"
            maxBufferSize="5000000"
            maxReceivedMessageSize="5000000">
          </binding>
        </netTcpBinding>
      </bindings>
      <client>
        <endpoint address="net.tcp://localhost:1236/SimShopService" binding="netTcpBinding"
          bindingConfiguration="NetTcpBinding_ISimShopServiceLib" contract="SimShopServiceReference.ISimShopServiceLib"
          name="NetTcpBinding_ISimShopServiceLib">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
      </client>

    </system.serviceModel>
</configuration>


问:
change password with python-ldap
I want change password on ldap user. The script is:

```<code>def changePassword(url,binddn,pw, newpw):
l = ldap.initialize(url)
ldap.
try:
    l.protocol_version=ldap.VERSION3
    l.simple_bind_s(binddn,pw)
except:
    print "Error Bind in changePassword"
    sys.exit(0)

old = {'userPassword':pw}
new = {'userPassword':newpw}
ldif = modlist.modifyModlist(old,new)
try:
    l.modify_s(binddn,ldif)
    l.unbind_s()
except:
    print "error"
</code>```

But when I call this function, I receive "error".
My LDAP has PPolicy for require current password when I change password.

How to change password whit this PPolicy??

Can anyone help me??

Thanks in advance
Dario

答:
With an LDAPv3 server, you should generally never do a direct mod/replace on a user password, and instead use the LDAPv3 Password modify operation.  Using python-ldap, this is done with passwd/passwd_s.  For example:

```<code>import ldap
server = 'localhost'
l = ldap.initialize('ldap://%s' % server)
l.simple_bind_s("cn=Marice McCaugherty,ou=Product Testing,dc=example,dc=com", "ytrehguaCc")
l.passwd_s("cn=Marice McCaugherty,ou=Product Testing,dc=example,dc=com", "ytrehguaCc", "secret")
</code>```

Would bind as the user DN listed, and change their password from "ytrehguaCc" to "secret".

Title: change password with python-ldap

Body:
I want change password on ldap user. The script is:

def changePassword(url,binddn,pw, newpw):
l = ldap.initialize(url)
ldap.
try:
    l.protocol_version=ldap.VERSION3
    l.simple_bind_s(binddn,pw)
except:
    print "Error Bind in changePassword"
    sys.exit(0)

old = {'userPassword':pw}
new = {'userPassword':newpw}
ldif = modlist.modifyModlist(old,new)
try:
    l.modify_s(binddn,ldif)
    l.unbind_s()
except:
    print "error"

But when I call this function, I receive "error".
My LDAP has PPolicy for require current password when I change password.

How to change password whit this PPolicy??

Can anyone help me??

Thanks in advance
Dario

Body:
With an LDAPv3 server, you should generally never do a direct mod/replace on a user password, and instead use the LDAPv3 Password modify operation.  Using python-ldap, this is done with passwd/passwd_s.  For example:

import ldap
server = 'localhost'
l = ldap.initialize('ldap://%s' % server)
l.simple_bind_s("cn=Marice McCaugherty,ou=Product Testing,dc=example,dc=com", "ytrehguaCc")
l.passwd_s("cn=Marice McCaugherty,ou=Product Testing,dc=example,dc=com", "ytrehguaCc", "secret")

Would bind as the user DN listed, and change their password from "ytrehguaCc" to "secret".


问:
Get records from a date range
This is my model:

```<code>public class FlightSchedule {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "takeoff_date")
    private LocalDateTime takeoffDate;

    @ManyToOne
    @JsonIgnoreProperties("airportTakeoff")
    private Airports airportTakeoff;

    @ManyToOne
    @JsonIgnoreProperties("airportArrival")
    private Airports airportArrival;

}
</code>```

This is my repository:

```<code>public List<FlightSchedule> findByAirportTakeoff_idAndAirportArrival_idAndTakeoffDateGreaterThanEqualAndTakeoffDateLessThan(
        String airportTakeoff, String airportArrival, LocalDateTime arrivalDate, LocalDateTime arrivalDate2);
</code>```

And this is my service:

```<code>LocalDateTime takeoffLocalDate =
            Instant.ofEpochMilli(takeoffDate).atZone(ZoneId.systemDefault()).toLocalDateTime();
    LocalDateTime takeoffLocalDate2 =
            Instant.ofEpochMilli(takeoffDate).atZone(ZoneId.systemDefault()).toLocalDateTime().plusDays(1);

    return flightScheduleRepository.findByAirportTakeoff_idAndAirportArrival_idAndTakeoffDateGreaterThanEqualAndTakeoffDateLessThan(
            airportTakeoff, airportArrival, takeoffLocalDate, takeoffLocalDate2)
            .stream().map(flightScheduleMapper::toDto)
            .collect(Collectors.toCollection(LinkedList::new));
</code>```

These are my records:

```<code>1   2019-05-28 17:00:00 TGU   MAD

6   2019-05-28 23:00:00 TGU   MAD
</code>```

However, when make a request with:

```<code>/flight-schedules/optional/1558994400000/TGU/MAD

1558994400000 = 28 May 2019
</code>```

I should get both fligths however, I get the first one. I've noticied that I don't get the flights after 21:00 hours of a day. Any ideas?

答:
```<code>LocalDateTime.of(2019,5,28,0,0,0).toInstant(ZoneOffset.UTC).toEpochMilli();
</code>```

This gives me a long value of 1559001600000 , which differs from your millis. So the problem is probably with your millis value, it's 3 hours different then UTC timezone.

Title: Get records from a date range

Body:
This is my model:

public class FlightSchedule {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "takeoff_date")
    private LocalDateTime takeoffDate;

    @ManyToOne
    @JsonIgnoreProperties("airportTakeoff")
    private Airports airportTakeoff;

    @ManyToOne
    @JsonIgnoreProperties("airportArrival")
    private Airports airportArrival;

}

This is my repository:

public List<FlightSchedule> findByAirportTakeoff_idAndAirportArrival_idAndTakeoffDateGreaterThanEqualAndTakeoffDateLessThan(
        String airportTakeoff, String airportArrival, LocalDateTime arrivalDate, LocalDateTime arrivalDate2);

And this is my service:

LocalDateTime takeoffLocalDate =
            Instant.ofEpochMilli(takeoffDate).atZone(ZoneId.systemDefault()).toLocalDateTime();
    LocalDateTime takeoffLocalDate2 =
            Instant.ofEpochMilli(takeoffDate).atZone(ZoneId.systemDefault()).toLocalDateTime().plusDays(1);

    return flightScheduleRepository.findByAirportTakeoff_idAndAirportArrival_idAndTakeoffDateGreaterThanEqualAndTakeoffDateLessThan(
            airportTakeoff, airportArrival, takeoffLocalDate, takeoffLocalDate2)
            .stream().map(flightScheduleMapper::toDto)
            .collect(Collectors.toCollection(LinkedList::new));

These are my records:

1   2019-05-28 17:00:00 TGU   MAD

6   2019-05-28 23:00:00 TGU   MAD

However, when make a request with:

/flight-schedules/optional/1558994400000/TGU/MAD

1558994400000 = 28 May 2019

I should get both fligths however, I get the first one. I've noticied that I don't get the flights after 21:00 hours of a day. Any ideas?

Body:
LocalDateTime.of(2019,5,28,0,0,0).toInstant(ZoneOffset.UTC).toEpochMilli();

This gives me a long value of 1559001600000 , which differs from your millis. So the problem is probably with your millis value, it's 3 hours different then UTC timezone.


问:
spin UIImageView with core animation
I am trying to make something relatively simple, make a wheel spin 90degrees when the user touches a button, for the most part what I have done so far works the first time, but thereafter the image won't move.  I want it to keep its new position and rotate 90degrees thereafter from the new position, I have
[UIView setAnimationBeginsFromCurrentState:YES];

but that doesn't seem to work

I added an NSTimer to "reset" the original image orientation, so that the wheel springs back to the original position and then rotates again when the user touches it.  ... however this isn't really what I want.

Is there a way to make the image keep rotating 90degrees so four touches by the user would put the image back to its original position.  Thanks for any help!!

here is the sample code

```<code>
-(IBAction) rotatewheel:(id)sender {

      [UIView setAnimationDuration:1];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationRepeatCount:1];
    wheel.transform = CGAffineTransformMakeRotation(M_PI/4);
    [UIView commitAnimations];

    returnwheelTimer = [NSTimer scheduledTimerWithTimeInterval:1.1 target:self selector:@selector (returnwheel) userInfo:nil repeats:NO];

}
</code>```

```<code>
-(void) returnwheel {

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:.5];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationRepeatCount:1];
    wheel.transform = CGAffineTransformMakeRotation(M_PI);
    [UIView commitAnimations];

}
</code>```

答:
Instead of:

```<code>wheel.transform = CGAffineTransformMakeRotation(M_PI/4);
</code>```

use

```<code>wheel.transform = CGAffineTransformRotate(wheel.transform,M_PI/4);
</code>```

That way it will apply the new tranformation to the current one, instead of replacing it.

Title: spin UIImageView with core animation

Body:
I am trying to make something relatively simple, make a wheel spin 90degrees when the user touches a button, for the most part what I have done so far works the first time, but thereafter the image won't move.  I want it to keep its new position and rotate 90degrees thereafter from the new position, I have
[UIView setAnimationBeginsFromCurrentState:YES];

but that doesn't seem to work

I added an NSTimer to "reset" the original image orientation, so that the wheel springs back to the original position and then rotates again when the user touches it.  ... however this isn't really what I want.

Is there a way to make the image keep rotating 90degrees so four touches by the user would put the image back to its original position.  Thanks for any help!!

here is the sample code

-(IBAction) rotatewheel:(id)sender {

      [UIView setAnimationDuration:1];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationRepeatCount:1];
    wheel.transform = CGAffineTransformMakeRotation(M_PI/4);
    [UIView commitAnimations];

    returnwheelTimer = [NSTimer scheduledTimerWithTimeInterval:1.1 target:self selector:@selector (returnwheel) userInfo:nil repeats:NO];

}

-(void) returnwheel {

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:.5];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationRepeatCount:1];
    wheel.transform = CGAffineTransformMakeRotation(M_PI);
    [UIView commitAnimations];

}

Body:
Instead of:

wheel.transform = CGAffineTransformMakeRotation(M_PI/4);

use

wheel.transform = CGAffineTransformRotate(wheel.transform,M_PI/4);

That way it will apply the new tranformation to the current one, instead of replacing it.


问:
I'm trying to search a '.class' file within jar files using Python
```<code>#! /usr/bin/python -tt
import os
def searchFile(path1,ext1,fileName1):
    pathList = []
    for root, dirs, files in os.walk(path1):
        for file in files:
            if file.endswith(ext1):
               pathList.append(os.path.join(root,file))
    print "-----The file is present under the below path------\n"
    for ele in pathList:
        if fileName1 in ele:
            print ele
def main():
    path = raw_input("Please enter the path you wish to spider. Also make sure that the files/subfolders have the correct permissions.\n")
    ext = raw_input("Enter the extension you wish to search/ find. Eg: For class files enter .class / For text file enter .txt \n")
    fileName = raw_input("Enter the filename without extension. Eg For example.class, input only 'example'\n")
    searchFile(path,ext,fileName)
if __name__ == '__main__':
main()
</code>```

With normal files/ subfolders, it gets the path/ filename correctly however when spidering through the 'jars', python script doesn't return anything.
How can I make the above script scan through the Jars ?

答:
Filename: searchForFiles.py

```<code>import os, zipfile, glob, sys

def main():
    searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see batch file code in second code section)
    listOfFilesInJar = []
    for file in glob.glob("*.jar"):
        archive = zipfile.ZipFile(file, 'r')
        for x in archive.namelist():
            if str(searchFile) in str(x):
                listOfFilesInJar.append(file)

    for something in listOfFilesInJar:
        print("location of "+str(searchFile)+": ",something)

if __name__ == "__main__":
    sys.exit(main())
</code>```

You can easily run this by making a .bat file with the following text (replace "AddWorkflows.class" with the file you are searching for):

(File: CallSearchForFiles.bat)

```<code>@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause
</code>```

You can double-click CallSearchForFiles.bat to easily run it.

Body:
#! /usr/bin/python -tt
import os
def searchFile(path1,ext1,fileName1):
    pathList = []
    for root, dirs, files in os.walk(path1):
        for file in files:
            if file.endswith(ext1):
               pathList.append(os.path.join(root,file))
    print "-----The file is present under the below path------\n"
    for ele in pathList:
        if fileName1 in ele:
            print ele
def main():
    path = raw_input("Please enter the path you wish to spider. Also make sure that the files/subfolders have the correct permissions.\n")
    ext = raw_input("Enter the extension you wish to search/ find. Eg: For class files enter .class / For text file enter .txt \n")
    fileName = raw_input("Enter the filename without extension. Eg For example.class, input only 'example'\n")
    searchFile(path,ext,fileName)
if __name__ == '__main__':
main()

With normal files/ subfolders, it gets the path/ filename correctly however when spidering through the 'jars', python script doesn't return anything.
How can I make the above script scan through the Jars ?

Body:
Filename: searchForFiles.py

import os, zipfile, glob, sys

def main():
    searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see batch file code in second code section)
    listOfFilesInJar = []
    for file in glob.glob("*.jar"):
        archive = zipfile.ZipFile(file, 'r')
        for x in archive.namelist():
            if str(searchFile) in str(x):
                listOfFilesInJar.append(file)

    for something in listOfFilesInJar:
        print("location of "+str(searchFile)+": ",something)

if __name__ == "__main__":
    sys.exit(main())

You can easily run this by making a .bat file with the following text (replace "AddWorkflows.class" with the file you are searching for):

(File: CallSearchForFiles.bat)

@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause

You can double-click CallSearchForFiles.bat to easily run it.


问:
Affinity Propagation for Image Clustering
The link here describes a method for image classification using affinity propagation. I'm confused as to how they got the feature vectors, i.e, the data structure of the images, e.g, arrays?

Additionally, how would I accomplish this given that I can't use Places365 as it's custom data (audio spectrograms)?

Finally, how would I plot the images as they've done in the diagram?

答:
The images are passed through a neural network. The activations of neural network layer for an image is the feature vector. See https://keras.io/applications/ for examples.

Spectrograms can be treated like images.

Sometimes even when domain is very different, the neural network features can extract useful information that can help you with clustering/classification tasks.


问:
JSDoc: Return object structure
How can I tell JSDoc about the structure of an object that is returned. I have found the @return {{field1: type, field2: type, ...}} description syntax and tried it:

```<code>/**
 * Returns a coordinate from a given mouse or touch event
 * @param  {TouchEvent|MouseEvent|jQuery.Event} e
 *         A valid mouse or touch event or a jQuery event wrapping such an
 *         event.
 * @param  {string} [type="page"]
 *         A string representing the type of location that should be
 *         returned. Can be either "page", "client" or "screen".
 * @return {{x: Number, y: Number}}
 *         The location of the event
 */
var getEventLocation = function(e, type) {
    ...

    return {x: xLocation, y: yLocation};
}
</code>```

While this parses successfully, the resulting documentation simply states:

```<code>Returns:
    The location of an event
    Type: Object
</code>```

I am developing an API and need people to know about the object that they will get returned. Is this possible in JSDoc? I am using JSDoc3.3.0-beta1.

答:
An alternative to the suggestions already posted, you can use this format:

```<code>/**
 * Get the connection state.
 *
 * @returns {Object} connection The connection state.
 * @returns {boolean} connection.isConnected Whether the authenticated user is currently connected.
 * @returns {boolean} connection.isPending Whether the authenticated user's connection is currently pending.
 * @returns {Object} connection.error The error object if an error occurred.
 * @returns {string} connection.error.message The error message.
 * @returns {string} connection.error.stack The stack trace of the error.
 */
getConnection () {
  return {
    isConnected: true,
    isPending: false,
    error
  }
}
</code>```

which will give the following documentation output:

```<code>    Get the connection state.

    getConnection(): Object

    Returns
    Object: connection The connection state.
    boolean: connection.isConnected Whether the authenticated user is currently connected.
    boolean: connection.isPending Whether the authenticated users connection is currently pending.
    Object: connection.error The error object if an error occurred.
    string: connection.error.message The error message.
    string: connection.error.stack The stack trace of the error.
</code>```

Title: JSDoc: Return object structure

Body:
How can I tell JSDoc about the structure of an object that is returned. I have found the @return {{field1: type, field2: type, ...}} description syntax and tried it:

/**
 * Returns a coordinate from a given mouse or touch event
 * @param  {TouchEvent|MouseEvent|jQuery.Event} e
 *         A valid mouse or touch event or a jQuery event wrapping such an
 *         event.
 * @param  {string} [type="page"]
 *         A string representing the type of location that should be
 *         returned. Can be either "page", "client" or "screen".
 * @return {{x: Number, y: Number}}
 *         The location of the event
 */
var getEventLocation = function(e, type) {
    ...

    return {x: xLocation, y: yLocation};
}

While this parses successfully, the resulting documentation simply states:

Returns:
    The location of an event
    Type: Object

I am developing an API and need people to know about the object that they will get returned. Is this possible in JSDoc? I am using JSDoc3.3.0-beta1.

Body:
An alternative to the suggestions already posted, you can use this format:

/**
 * Get the connection state.
 *
 * @returns {Object} connection The connection state.
 * @returns {boolean} connection.isConnected Whether the authenticated user is currently connected.
 * @returns {boolean} connection.isPending Whether the authenticated user's connection is currently pending.
 * @returns {Object} connection.error The error object if an error occurred.
 * @returns {string} connection.error.message The error message.
 * @returns {string} connection.error.stack The stack trace of the error.
 */
getConnection () {
  return {
    isConnected: true,
    isPending: false,
    error
  }
}

which will give the following documentation output:

    Get the connection state.

    getConnection(): Object

    Returns
    Object: connection The connection state.
    boolean: connection.isConnected Whether the authenticated user is currently connected.
    boolean: connection.isPending Whether the authenticated users connection is currently pending.
    Object: connection.error The error object if an error occurred.
    string: connection.error.message The error message.
    string: connection.error.stack The stack trace of the error.


问:
Cannot see local class variables while debugging DLL in Visual Studio..?
I'm trying to debug a DLL that I've written in VB.Net. When the external program starts, it loads the DLL and everything runs fine...but I cannot see the class variables in the Locals pane. They show up blank as shown below.

Also, some lines of code generate the error "There is no source code available for the current location", but I think I understand why. Whenever it tries to step into class members of any of the Microsoft DLLs, it would of course have no information for those. But any lines which deal only in code that I've written, it works fine.

This is a COM DLL AddIn for Microsoft Access 2007, but I'm assuming the issue is roughly the same regardless of the type of DLL. The Shared COM Addin Wizard was used to get started, and then customization proceeded from there with satisfactory results...except for the invisible variables in the Locals window.

I'm new to writing & debugging a DLL like this; until now I've only done EXE files. I've researched MSDN, Google, and Stack Overflow, and here are the details that are asked about on other threads...

Visual Studio 2008, .Net 3.0, and Access 2007

Project Properties > Debug > External Program points to MSAccess.exe.

Project configuration is set for Debug.

Optimizations = off.

Generate debug info = Full.

The PDB file is present in the \bin\ folder with the DLL.

Breakpoints are working.

Debug.Print messages are working.

I dug through the registry and found all references to the project, DLL, and its custom UserControl (required since the project creates a CustomTaskPane, and all path paths point to \bin\ folder.

What am I doing wrong?

What am I doing right?

What can I improve?

答:
Ok, answering part of my own question. I think I fixed the error message "There is no source code available for the current location". In the project properties "Enable unmanaged code debugging" was enabled.

With that option disabled, I can now step through the code without error, even if it hits objects for which I have no code. The debugger is acting a little differently too, but I haven't yet pinned it down. I did read up on the differences between managed & unmanaged code, and debugging them in mixed combinations, but while I understand in principle, I don't yet understand in practice.

My local variables are still blank, though.


问:
How to convert parts of a line to uppercase in a file
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

```<code>    # Queue name
    #
    queuename=sp00245b
</code>```

答:
You can also use the sed conversion \U to convert the portions of the matched pattern with the substitution command to uppercase. To covert everything following the '=' sign you could use, e.g.

```<code>sed '/^queuename=/s/=.*$/\U&/' filename
</code>```

To edit the file in-place, include the -i option, e.g.

```<code>sed -i '/^queuename=/s/=.*$/\U&/' filename
</code>```

Example Use/Output

```<code>$ echo "queuename=sp00245b" | sed '/^queuename=/s/=.*$/\U&/'
queuename=SP00245B
</code>```

Body:
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

    # Queue name
    #
    queuename=sp00245b

Body:
You can also use the sed conversion \U to convert the portions of the matched pattern with the substitution command to uppercase. To covert everything following the '=' sign you could use, e.g.

sed '/^queuename=/s/=.*$/\U&/' filename

To edit the file in-place, include the -i option, e.g.

sed -i '/^queuename=/s/=.*$/\U&/' filename

Example Use/Output

$ echo "queuename=sp00245b" | sed '/^queuename=/s/=.*$/\U&/'
queuename=SP00245B


问:
Spring jdbc 'select for update'
I have the following method that I use with Spring JDBC

```<code>public String getState() {
    String stateLink = template.queryForObject(
            "select state_url from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1",
            (result, rowNum) -> {
                return result.getString("state_url");
            });
    return stateLink;
}
</code>```

I can't find an example of how to do a for update with Spring JDBC. I want in_use to be set to true using for update.

I need to use select for update since this application will be used in a multi-threaded fashion. I don't want more than one thread to get the same row and the way to prevent that is by using select for update

I was able to do this with plain JDBC, here is the question I asked how to do it with plain JDBC

select "for update" with JDBC?

Anyone know how this would be done?

答:
This is what I came up with, feel free to recommend improvements</p>

```<code>public String getState() throws SQLException {
    String state = null;

    Connection conn = DataSourceUtils.getConnection(template.getDataSource());
    try {
        conn.setAutoCommit(false);

        String[] colNames = { "id", "state_url", "in_use" };
        String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
                + " from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1 FOR UPDATE";
        System.out.println(query);
        try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                ResultSet rs = stmt.executeQuery(query)) {
            while (rs.next()) {
                // Get the current values, if you need them.
                state = rs.getString(colNames[1]);

                rs.updateBoolean(colNames[2], true);
                rs.updateRow();
                conn.commit();
            }
        }
    } catch (SQLException e) {
        conn.setAutoCommit(true);
        e.printStackTrace();
    } finally {
        conn.setAutoCommit(true);
    }

    return state;
}
</code>```

Title: Spring jdbc 'select for update'

Body:
I have the following method that I use with Spring JDBC

public String getState() {
    String stateLink = template.queryForObject(
            "select state_url from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1",
            (result, rowNum) -> {
                return result.getString("state_url");
            });
    return stateLink;
}

I can't find an example of how to do a for update with Spring JDBC. I want in_use to be set to true using for update.

I need to use select for update since this application will be used in a multi-threaded fashion. I don't want more than one thread to get the same row and the way to prevent that is by using select for update

I was able to do this with plain JDBC, here is the question I asked how to do it with plain JDBC

select "for update" with JDBC?

Anyone know how this would be done?

Body:
This is what I came up with, feel free to recommend improvements

public String getState() throws SQLException {
    String state = null;

    Connection conn = DataSourceUtils.getConnection(template.getDataSource());
    try {
        conn.setAutoCommit(false);

        String[] colNames = { "id", "state_url", "in_use" };
        String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
                + " from state_scrape_queue where in_use = false ORDER BY scrape_timestamp NULLS FIRST LIMIT 1 FOR UPDATE";
        System.out.println(query);
        try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                ResultSet rs = stmt.executeQuery(query)) {
            while (rs.next()) {
                // Get the current values, if you need them.
                state = rs.getString(colNames[1]);

                rs.updateBoolean(colNames[2], true);
                rs.updateRow();
                conn.commit();
            }
        }
    } catch (SQLException e) {
        conn.setAutoCommit(true);
        e.printStackTrace();
    } finally {
        conn.setAutoCommit(true);
    }

    return state;
}


问:
array of callbacks as Promise?
I am working through some old legacy code dealing with network requests using RPC/YUI library.  It essentially creates  tags to handle network requests.  There are no promises for these.Also, because of IE11 support, we cannot use the native Promise object.  Our build process does not utilize any NPM dependencies, so we cannot use any babel related polyfills.

There is a bug I am working on to fix that the argument ignoreError gets overwritten each time another function calls the same function....obviously!  We have multiple functions calling this network request function library.  Sometimes we want to ignore an error, sometimes we do not.

What is the ideal way to store the multiple requests made and their respective error callbacks so the appropriate item is called?

example:

```<code>var rpcUrl,
rpcRetries,
rpcIgnoreError;

// main function that sets some globals:
rpc: function(url, retries, ignoreError) {
  rpcUrl = url;
  rpcRetries = retries;
  rpcIgnoreError = ignoreError;
  this.doRpc();
},
// calls the YUI library to initialize network script:
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      this.callbackError(true);
    },
    timeout: 55000
  });
},
// YUI callback
callbackError: function(retry) {
  if (retry && rpcRetries > 0) {
    rpcRetries = rpcRetries - 1;
    this.doRpc();
  } else {
    // ** how do i know this error handling is for the script which failed?
    if (!rpcIgnoreError) {
      this.populateFormStatus(6);
    }
  }
},
</code>```

now, we have multiple functions calling rpc() such as:

```<code>sendConfig: function() {
  this.rpc(urlForEndpoint, 3, true);
},
sendUser: function() {
  this.rpc(urlForEndpoint, 3, false);
},
sendWidget: function() {
  this.rpc(urlForEndpoint, 3, false);
},
</code>```

I am concerned making an array of callbacks will not guarantee that each item is handled with its respective handler.

I could do something like create a map constant:

```<code>var RPC_ERR_CB = {
    sendConfig: false,
    sendUser: true,
    sendWidget: true
};
</code>```

// and then in the onFailure callback, I can read the src of the script tag:

```<code>...
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      var hasCB = Object.keys(RPC_ERR_CB).some(function(item) {
        return arguments[0].src.indexOf(RPC_ERR_CB[item]) <= 0;
     });
      if (hasCB) {
        this.callbackError(true);
      }
    },
    timeout: 55000
  });
},
</code>```

Hope this makes sense...THANKS!

答: You could pass the values into doRpc, then you can pass it to callbackError or handle it in doRpc (like your example code at the end).  This will prevent the global variable from changing on you.

Title: array of callbacks as Promise?

Body:
I am working through some old legacy code dealing with network requests using RPC/YUI library.  It essentially creates  tags to handle network requests.  There are no promises for these.Also, because of IE11 support, we cannot use the native Promise object.  Our build process does not utilize any NPM dependencies, so we cannot use any babel related polyfills.

There is a bug I am working on to fix that the argument ignoreError gets overwritten each time another function calls the same function....obviously!  We have multiple functions calling this network request function library.  Sometimes we want to ignore an error, sometimes we do not.

What is the ideal way to store the multiple requests made and their respective error callbacks so the appropriate item is called?

example:

var rpcUrl,
rpcRetries,
rpcIgnoreError;

// main function that sets some globals:
rpc: function(url, retries, ignoreError) {
  rpcUrl = url;
  rpcRetries = retries;
  rpcIgnoreError = ignoreError;
  this.doRpc();
},
// calls the YUI library to initialize network script:
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      this.callbackError(true);
    },
    timeout: 55000
  });
},
// YUI callback
callbackError: function(retry) {
  if (retry && rpcRetries > 0) {
    rpcRetries = rpcRetries - 1;
    this.doRpc();
  } else {
    // ** how do i know this error handling is for the script which failed?
    if (!rpcIgnoreError) {
      this.populateFormStatus(6);
    }
  }
},

now, we have multiple functions calling rpc() such as:

sendConfig: function() {
  this.rpc(urlForEndpoint, 3, true);
},
sendUser: function() {
  this.rpc(urlForEndpoint, 3, false);
},
sendWidget: function() {
  this.rpc(urlForEndpoint, 3, false);
},

I am concerned making an array of callbacks will not guarantee that each item is handled with its respective handler.

I could do something like create a map constant:

var RPC_ERR_CB = {
    sendConfig: false,
    sendUser: true,
    sendWidget: true
};

// and then in the onFailure callback, I can read the src of the script tag:

...
doRpc: function() {
  YAHOO.util.Get.script(rpcUrl, {
    onFailure: function() {
      var hasCB = Object.keys(RPC_ERR_CB).some(function(item) {
        return arguments[0].src.indexOf(RPC_ERR_CB[item]) <= 0;
     });
      if (hasCB) {
        this.callbackError(true);
      }
    },
    timeout: 55000
  });
},

Hope this makes sense...THANKS!


问:
iReport not starting using JRE 8
I have downloaded and installed the iReport 4.5 using te Windows installer. But when I try to start the iReport it shows the splash screen but does not start. </p>

<p>My JRE version is 8. </p>

答:
For me, the combination of Stuart Gathman's and Raviath's answer in this thread did the trick in Windows Server 2016 for iReport 5.6.0.

In addition, I added a symlink within C:\program files\java\jre7 to jdk8 like this:

```<code>cmd /c mklink /d "C:\program files\java\jre7\bin" "C:\Program Files\Java\jdk1.8.0_181\bin"
</code>```

because iReport was constantly complaining that it could not find java.exe within C:\program files\java\jre7\bin\ - So I served it the available java.exe (in my case V8.181) under the desired path and it swallowed it gladly.

Title: iReport not starting using JRE 8

Body:
I have downloaded and installed the iReport 4.5 using te Windows installer. But when I try to start the iReport it shows the splash screen but does not start.

My JRE version is 8.

Body:
For me, the combination of Stuart Gathman's and Raviath's answer in this thread did the trick in Windows Server 2016 for iReport 5.6.0.

In addition, I added a symlink within C:\program files\java\jre7 to jdk8 like this:

cmd /c mklink /d "C:\program files\java\jre7\bin" "C:\Program Files\Java\jdk1.8.0_181\bin"

because iReport was constantly complaining that it could not find java.exe within C:\program files\java\jre7\bin\ - So I served it the available java.exe (in my case V8.181) under the desired path and it swallowed it gladly.


问:
Karate API function/keyword to substitute JSON placeholder key with argument passed
In Webservice Testing using Karate API, how do I substitute JSON key with a value I defined in Background?

Background: I am hitting a REST API endpoint through Karate API. This returns me a deep nested JSON. Once I get response, I need to evaluate if response contains my parameter as key and if key's value is not null. Below is my code

```<code>Background:
* def execParam = 'ArgumentProvided'

@MyTestCase
Given url myUrl + '/' + execParam
When method get
Then status 200
And match response.subElement contains {execParam : '#notnull'}

</code>```

With above code, assertions fail with error

expected: {execParam:'#notnull'}, reason: actual value does not contain expected

My expectation is for code to assert {'ArgumentProvided':'#notnull'}. Code currently asserts {execParam:'#notnull'}

I tried to replace execParam with #execParam, $.execParam and #[$.execParam] and none of these substitute the value. So need help substituting the JSON key

答:
For this interesting use case, you can construct the expected JSON on the fly like this:</p>
```<code>* def execParam = 'ArgumentProvided'
* def response = { subElement: { ArgumentProvided: 'foo' } }
* def expected = {}
* expected[execParam] = '#notnull'
* match expected == { ArgumentProvided: '#notnull' }
* match response.subElement contains expected
</code>```

Body:
In Webservice Testing using Karate API, how do I substitute JSON key with a value I defined in Background?

Background: I am hitting a REST API endpoint through Karate API. This returns me a deep nested JSON. Once I get response, I need to evaluate if response contains my parameter as key and if key's value is not null. Below is my code

Background:
* def execParam = 'ArgumentProvided'

@MyTestCase
Given url myUrl + '/' + execParam
When method get
Then status 200
And match response.subElement contains {execParam : '#notnull'}

With above code, assertions fail with error

expected: {execParam:'#notnull'}, reason: actual value does not contain expected

My expectation is for code to assert {'ArgumentProvided':'#notnull'}. Code currently asserts {execParam:'#notnull'}

I tried to replace execParam with #execParam, $.execParam and #[$.execParam] and none of these substitute the value. So need help substituting the JSON key

Body:
For this interesting use case, you can construct the expected JSON on the fly like this:

* def execParam = 'ArgumentProvided'
* def response = { subElement: { ArgumentProvided: 'foo' } }
* def expected = {}
* expected[execParam] = '#notnull'
* match expected == { ArgumentProvided: '#notnull' }
* match response.subElement contains expected


问:
Exclude files from web site publish in Visual Studio
Can I exclude a folder or files when I publish a web site in Visual Studio 2005?  I have various resources that I want to keep at hand in the Solution Explorer, such as alternate config files for various environments, but I don't really want to publish them to the server.  Is there some way to exclude them?  When using other project types, such as a .dll assembly, I can set a file's Build Action property to "None" and its Copy to Output Directory property to "Do not copy".  I cannot find any similar settings for files in a web site.

If the IDE does not offer this feature, does anyone have good technique for handling such files?

答:
I struggled with the same issue and finally pulled the trigger on converting the web site to a web application.  Once I did this, I got all of the IDE benefits such as build action, and it compiled faster to boot (no more validating web site...).

Step 1: Convert your 'web site' to a 'web application'. To convert it I just created a new "web application", blew away all the files it created automatically, and copied and pasted my web site in. This worked fine.  Note that report files will need to have their Build Action set to "Content" instead of "none".

Step 2: Now you can set any files "Build Action" property.

Hope this helps.

OwnerDisplayName: Jim Snyder

ContentLicense: CC BY-SA 2.5


问:
How can I plot a learning curve from a skopt/BayesSearchCV search
I'm having trouble plotting a learning curve from a skopt optimization.  Here is what I tried:

```<code>from skopt.space import Real, Integer, Categorical
from skopt.utils import use_named_args
from skopt import BayesSearchCV
from skopt.plots import plot_convergence

rf = RandomForestRegressor(random_state =7, n_jobs=4)
def RunSKOpt(X_train, y_train):
    hyper_parameters =  {"n_estimators":      (5, 500),
                         "max_depth":         Categorical([3, None]),
                         "min_samples_split": (2, 10),
                         "min_samples_leaf":  (1, 10)
                        }

    search = BayesSearchCV(rf,
                           hyper_parameters,
                           n_iter = 40,
                           n_jobs = 4,
                           cv = 10,
                           verbose = 1,
                           return_train_score = False
    )
    return search

search = RunSKOpt(X_train, y_train)
search.fit(X_train, y_train)

plot_convergence(search)
</code>```

The plot is empty.  Please tell me what I'm doing wrong.

Charles

答:
Directly from this Github Issue Thread: https://github.com/scikit-optimize/scikit-optimize/issues/751

BayesSearchCV was not intended for convergence plotting. You could
  however use the cv_results_ property of the *SearchCV, convert it to
  pandas (should be just creating dataframe out of the cv_results_
  property) and then visualizing estimator performances for different
  iterations. The property is similar to those of GridSearchCV:

And here's an example of doing that:

Body:
I'm having trouble plotting a learning curve from a skopt optimization.  Here is what I tried:

from skopt.space import Real, Integer, Categorical
from skopt.utils import use_named_args
from skopt import BayesSearchCV
from skopt.plots import plot_convergence

rf = RandomForestRegressor(random_state =7, n_jobs=4)
def RunSKOpt(X_train, y_train):
    hyper_parameters =  {"n_estimators":      (5, 500),
                         "max_depth":         Categorical([3, None]),
                         "min_samples_split": (2, 10),
                         "min_samples_leaf":  (1, 10)
                        }

    search = BayesSearchCV(rf,
                           hyper_parameters,
                           n_iter = 40,
                           n_jobs = 4,
                           cv = 10,
                           verbose = 1,
                           return_train_score = False
    )
    return search

search = RunSKOpt(X_train, y_train)
search.fit(X_train, y_train)

plot_convergence(search)

The plot is empty.  Please tell me what I'm doing wrong.

Charles


问:
React Fabric UI remove the Pivot Item
I am using Pivot component in Office Fabric UI, I need to remove PivotItem for some views. Is there any possible way?

etc. I need to remove 'Insert' Pivot with using isComposeMode() in below

```<code>import * as React from "react";
import { Label } from "office-ui-fabric-react/lib/Label";
import { Pivot, PivotItem } from "office-ui-fabric-react/lib/Pivot";
import InsertView from "./InsertView";

export interface PivotProps {}

export interface PivotState {}

class MainNav extends React.Component<PivotProps, PivotState> {
  render() {
    return (
      <div>
        <Pivot>
          <PivotItem headerText="Insert">
            <InsertView />
          </PivotItem>
          <PivotItem headerText="Review">
            <Label>Review</Label>
          </PivotItem>
          <PivotItem headerText="Settings">
            <Label>Settings</Label>
          </PivotItem>
        </Pivot>
      </div>
    );
  }

  isComposeMode = (): boolean => {
    if (Office.context.mailbox.item.displayReplyForm != undefined) {
      return false;
    } else {
      return true;
    }
  };
}

export default MainNav;
</code>```

答:
Array approach above is great, but you can conditionally include items in the array and then filter out “falsy” values using the .filter(Boolean) method. This allows you to include the item only if the condition is true.

import * as React from 'react'
import { Pivot, PivotItem, InsertView, Label } from '.'

export interface PivotProps {
    isComposeMode: boolean
}

class MainNav extends React.Component<PivotProps> {
    public render() {
        const items = [
            this.props.isComposeMode && <PivotItem key="insert" headerText="Insert"><InsertView /></PivotItem>,
            <PivotItem key="review"headerText="Review">Review</PivotItem>,
            <PivotItem key="settings" headerText="Settings">Settings</PivotItem>
        ].filter(Boolean)

        return (
            <Pivot>
                {items}
            </Pivot>
        )
    }
}
```

You should also derive isComposeMode in a parent component and pass it in as a prop. This will make your component more reusable and won’t tie it to your business logic.

Title: React Fabric UI remove the Pivot Item

Body:
I am using Pivot component in Office Fabric UI, I need to remove PivotItem for some views. Is there any possible way?

etc. I need to remove 'Insert' Pivot with using isComposeMode() in below

import * as React from "react";
import { Label } from "office-ui-fabric-react/lib/Label";
import { Pivot, PivotItem } from "office-ui-fabric-react/lib/Pivot";
import InsertView from "./InsertView";

export interface PivotProps {}

export interface PivotState {}

class MainNav extends React.Component<PivotProps, PivotState> {
  render() {
    return (

        <Pivot>
          <PivotItem headerText="Insert">
            <InsertView />
          </PivotItem>
          <PivotItem headerText="Review">
            Review
          </PivotItem>
          <PivotItem headerText="Settings">
            Settings
          </PivotItem>
        </Pivot>

    );
  }

  isComposeMode = (): boolean => {
    if (Office.context.mailbox.item.displayReplyForm != undefined) {
      return false;
    } else {
      return true;
    }
  };
}

export default MainNav;

Body:
Array approach above is great, but you can conditionally include items in the array and then filter out “falsy” values using the .filter(Boolean) method. This allows you to include the item only if the condition is true.

import * as React from 'react'
import { Pivot, PivotItem, InsertView, Label } from '.'

export interface PivotProps {
    isComposeMode: boolean
}

class MainNav extends React.Component<PivotProps> {
    public render() {
        const items = [
            this.props.isComposeMode && <PivotItem key="insert" headerText="Insert"><InsertView /></PivotItem>,
            <PivotItem key="review"headerText="Review"><Label>Review</Label></PivotItem>,
            <PivotItem key="settings" headerText="Settings"><Label>Settings</Label></PivotItem>
        ].filter(Boolean)

        return (
            <Pivot>
                {items}
            </Pivot>
        )
    }
}

You should also derive isComposeMode in a parent component and pass it in as a prop. This will make your component more reusable and won’t tie it to your business logic.


问:
Screenshot from a rendertexture (non-main camera) to fit sprite (in 3D space) exactly - Unity
How do you adjust or otherwise set up a screenshot to have the exact dimensions of a particular sprite that is in 3D space (so, Gameobject with SpriteRenderer).

The render camera is set up directly above the sprite but has some blank space outside the boundaries of the sprite. I'm not sure how to precisely adjust the viewport of the rendercamera.

Here's what the scene looks like. (Actually this is a quick and simplified version of my current scene, to showcase my specific problem) And yes, I'm trying to take a specific screenshot at runtime. The main camera is at an arbitrary angle but the render camera can be centered to the sprite renderer. In other words, the screenshot I am taking looks like the one in the Camera Preview in bottom right corner in the pic below. How do I crop out (or adjust the viewport to exclude) the extra part beyond the size of the sprite renderer?

答:
You can calculate the size of the frustum in world space:

```<code>float frustumHeight = 2.0f * distance * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
float frustrumWidth = frustumHeight * camera.aspect;
</code>```

Then if you know the painting's height and width in world units, you can calculate how big of the center piece of the screen it's occupying:

```<code>float widthPortion = paintingWidth / frustrumWidth;
float heightPortion = paintingHeight / frustrumHeight;
</code>```

Then you know how much of the center of the renderTexture to hide:

```<code>float leftRightCrop = (1f-widthPortion)/2f;
float topBottomCrop = (1f-heightPortion)/2f;
</code>```

So to copy it from your camera's render texture you can do this in OnPostRender:

```<code>RenderTexture currentRT = RenderTexture.active;
RenderTexture.active = Cam.targetTexture;

Cam.Render();

int croppedPixelWidth = widthPortion*camera.pixelWidth;
int croppedPixelHeight = heightPortion*camera.pixelHeight;

int leftPixelPadding = leftRightCrop*camera.pixelWidth;
int bottomPixelPadding = topBottomCrop*camera.pixelHeight;

Texture2D cropped = new Texture2D(croppedPixelWidth, croppedPixelHeight);
cropped.ReadPixels(new Rect(
        leftPixelPadding,
        bottomPixelPadding,
        leftPixelPadding + croppedPixelWidth,
        bottomPixelPadding + croppedPixelHeight), 0, 0);

cropped.Apply();

RenderTexture.active = currentRT;
</code>```

Or as @ina used it,

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class SpritePerfectScreenshot : MonoBehaviour
{

    bool ScreenshotIt;
    float widthPortion; float heightPortion;
    float leftRightCrop; float topBottomCrop;
    Camera camera;

    public void TakeScreencap(Camera c,float distance,float pw,float ph)
    {
        camera = c;c.enabled = true;

        SetItUp(distance, pw, ph);
    }

    void SetItUp(float distance,float paintingWidth,float paintingHeight)
    {
        float frustrumHeight = 2.0f * distance * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
        float frustrumWidth = frustrumHeight * camera.aspect;

          widthPortion =  (paintingWidth / frustrumWidth);
          heightPortion = (paintingHeight / frustrumHeight);

          leftRightCrop =   (1f -  widthPortion) / 2f;
          topBottomCrop =  (1f -  heightPortion) / 2f;

        ScreenshotIt = true;
        print("SetItUp " + distance);
    }

    private void OnPostRender()
    {
        if (ScreenshotIt)
        {
            int croppedPixelWidth =(int) (widthPortion * camera.pixelWidth);
            int croppedPixelHeight =(int) (heightPortion * camera.pixelHeight);

            int leftPixelPadding =(int)( leftRightCrop * camera.pixelWidth);
            int bottomPixelPadding =(int)( topBottomCrop * camera.pixelHeight);

            print(croppedPixelWidth + " " + croppedPixelHeight);

            Texture2D cropped = new Texture2D(croppedPixelWidth, croppedPixelHeight);
            cropped.ReadPixels(new Rect(
        leftPixelPadding,
        bottomPixelPadding,
        leftPixelPadding + croppedPixelWidth,
        bottomPixelPadding + croppedPixelHeight), 0, 0);
            cropped.Apply();

            string uuid = UUID.GetUUID(); string localPath = Application.persistentDataPath + "/" + uuid + ".png";

#if !UNITY_EDITOR
            NativeGallery.SaveImageToGallery(cropped.EncodeToPNG(), "A Beautiful Letter",uuid);
#else
            File.WriteAllBytes(localPath,cropped.EncodeToPNG());
            print(localPath);
#endif

            //TODO server (?)

            ScreenshotIt = false;camera.enabled = false;
        }
    }
}
</code>```

Body:
You can calculate the size of the frustum in world space:

float frustumHeight = 2.0f * distance * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
float frustrumWidth = frustumHeight * camera.aspect;

Then if you know the painting's height and width in world units, you can calculate how big of the center piece of the screen it's occupying:

float widthPortion = paintingWidth / frustrumWidth;
float heightPortion = paintingHeight / frustrumHeight;

Then you know how much of the center of the renderTexture to hide:

float leftRightCrop = (1f-widthPortion)/2f;
float topBottomCrop = (1f-heightPortion)/2f;

So to copy it from your camera's render texture you can do this in OnPostRender:

RenderTexture currentRT = RenderTexture.active;
RenderTexture.active = Cam.targetTexture;

Cam.Render();

int croppedPixelWidth = widthPortion*camera.pixelWidth;
int croppedPixelHeight = heightPortion*camera.pixelHeight;

int leftPixelPadding = leftRightCrop*camera.pixelWidth;
int bottomPixelPadding = topBottomCrop*camera.pixelHeight;

Texture2D cropped = new Texture2D(croppedPixelWidth, croppedPixelHeight);
cropped.ReadPixels(new Rect(
        leftPixelPadding,
        bottomPixelPadding,
        leftPixelPadding + croppedPixelWidth,
        bottomPixelPadding + croppedPixelHeight), 0, 0);

cropped.Apply();

RenderTexture.active = currentRT;

Or as @ina used it,

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class SpritePerfectScreenshot : MonoBehaviour
{

    bool ScreenshotIt;
    float widthPortion; float heightPortion;
    float leftRightCrop; float topBottomCrop;
    Camera camera;

    public void TakeScreencap(Camera c,float distance,float pw,float ph)
    {
        camera = c;c.enabled = true;

        SetItUp(distance, pw, ph);
    }

    void SetItUp(float distance,float paintingWidth,float paintingHeight)
    {
        float frustrumHeight = 2.0f * distance * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
        float frustrumWidth = frustrumHeight * camera.aspect;

          widthPortion =  (paintingWidth / frustrumWidth);
          heightPortion = (paintingHeight / frustrumHeight);

          leftRightCrop =   (1f -  widthPortion) / 2f;
          topBottomCrop =  (1f -  heightPortion) / 2f;

        ScreenshotIt = true;
        print("SetItUp " + distance);
    }

    private void OnPostRender()
    {
        if (ScreenshotIt)
        {
            int croppedPixelWidth =(int) (widthPortion * camera.pixelWidth);
            int croppedPixelHeight =(int) (heightPortion * camera.pixelHeight);

            int leftPixelPadding =(int)( leftRightCrop * camera.pixelWidth);
            int bottomPixelPadding =(int)( topBottomCrop * camera.pixelHeight);

            print(croppedPixelWidth + " " + croppedPixelHeight);

            Texture2D cropped = new Texture2D(croppedPixelWidth, croppedPixelHeight);
            cropped.ReadPixels(new Rect(
        leftPixelPadding,
        bottomPixelPadding,
        leftPixelPadding + croppedPixelWidth,
        bottomPixelPadding + croppedPixelHeight), 0, 0);
            cropped.Apply();

            string uuid = UUID.GetUUID(); string localPath = Application.persistentDataPath + "/" + uuid + ".png";

#if !UNITY_EDITOR
            NativeGallery.SaveImageToGallery(cropped.EncodeToPNG(), "A Beautiful Letter",uuid);
#else
            File.WriteAllBytes(localPath,cropped.EncodeToPNG());
            print(localPath);
#endif

            //TODO server (?)

            ScreenshotIt = false;camera.enabled = false;
        }
    }
}


问:
How to fix "android.enableSeparateAnnotationProcessing is experimental and unsupported" which is logged as a warning?
I added a new option in my gradle.properties file:

android.enableSeparateAnnotationProcessing=true

But I got the following warning from the compiler/builder:

WARNING: The option setting
  android.enableSeparateAnnotationProcessing=true is experimental and
  unsupported.

Also I tried to make it false, but I got the following message:

Gradle may disable incremental compilation as the following annotation
  processors are not incremental: compiler-1.1.1.jar
  (android.arch.persistence.room:compiler:1.1.1), compiler-4.8.0.jar
  (com.github.bumptech.glide:compiler:4.8.0),
  butterknife-compiler-8.6.0.jar
  (com.jakewharton:butterknife-compiler:8.6.0). Consider setting the
  experimental feature flag
  android.enableSeparateAnnotationProcessing=true in the
  gradle.properties file to run annotation processing in a separate task
  and make compilation incremental.

Environment:

JRE 1.8.0_152-release-1136-b06 amd64

JVM OpenJDK 64-Bit Server VM by JetBrains s.r.o

Android Studio 3.2.1 Build #AI-181.5540.7.32.5056338

Gradle 4.10.3

Android Gradle plugin: 3.3.1

Android doc:

When you include this flag, the Android Gradle plugin
  executes the annotation processors in a separate task and allows the
  Java compilation task to run incrementally.
  https://developer.android.com/studio/releases/gradle-plugin

答:
You need to add kapt dependencies for compiler dependency in your app gradle file.

For example: You should add below line in your app gradle file for android lifecycle dependency.

```<code>kapt "androidx.lifecycle:lifecycle-compiler:$lifecycleVersion"
</code>```

Also add apply plugin: 'kotlin-kapt' in your app gradle top level to make it enable.

If you are using dagger you should also add kapt dependency for compiler like shown above.

Body:
You need to add kapt dependencies for compiler dependency in your app gradle file.

For example: You should add below line in your app gradle file for android lifecycle dependency.

kapt "androidx.lifecycle:lifecycle-compiler:$lifecycleVersion"

Also add apply plugin: 'kotlin-kapt' in your app gradle top level to make it enable.

If you are using dagger you should also add kapt dependency for compiler like shown above.