问:
how to integrate whatsapp in ios
hi now i am trying Integrate What's app in our app

i have done already integrate Tweet

:-in this app i create two buttons
one(chooseImagePressed) button is choose the image form local file and then
and then second(tweetButtonPressed) this is post the image to Tweeter

```<code>- (IBAction)tweetButtonPressed:(id)sender
{
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet setInitialText:@"Look at this nice picture!"];

        [tweetSheet addImage:self.imageView.image];

        [self presentViewController:tweetSheet animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:@"please setup Twitter"
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
        [alertView show];
    }
}

- (IBAction)chooseImagePressed:(id)sender
{
    self.pickerController = [[UIImagePickerController alloc] init];

    self.pickerController.delegate = self;
    self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:self.pickerController animated:YES completion:nil];
}

#pragma mark

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info;
{
    self.imageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];

    [self dismissViewControllerAnimated:YES completion:nil];
}
</code>```

Please give me any idea about the how to integrated what's app into our app

Please tell me this is possible or Not

Thanks

答:
I prefer this documented method:</p>

```<code>if let urlString = "https://wa.me/\(whatsappPhoneNumber)/?text=Hi. ".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: urlString),
    UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url)
}
</code>```

Title: how to integrate whatsapp in ios

Body:
hi now i am trying Integrate What's app in our app

i have done already integrate Tweet

:-in this app i create two buttons
one(chooseImagePressed) button is choose the image form local file and then
and then second(tweetButtonPressed) this is post the image to Tweeter

- (IBAction)tweetButtonPressed:(id)sender
{
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet setInitialText:@"Look at this nice picture!"];

        [tweetSheet addImage:self.imageView.image];

        [self presentViewController:tweetSheet animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:@"please setup Twitter"
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
        [alertView show];
    }
}

- (IBAction)chooseImagePressed:(id)sender
{
    self.pickerController = [[UIImagePickerController alloc] init];

    self.pickerController.delegate = self;
    self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:self.pickerController animated:YES completion:nil];
}

#pragma mark

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info;
{
    self.imageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];

    [self dismissViewControllerAnimated:YES completion:nil];
}

Please give me any idea about the how to integrated what's app into our app

Please tell me this is possible or Not

Thanks

Body:
I prefer this documented method:

if let urlString = "https://wa.me/\(whatsappPhoneNumber)/?text=Hi. ".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: urlString),
    UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url)
}


来源: stackexchange

问:
Calculating time 90 minutes prior to due date/time in Objective C (iPhone app)
This is a completely noobish question, but I spent 2 hours yesterday trying to make it work, and I'm obviously missing something very basic.

What I need to do is take input from user of date/time and count back 90 minutes for an alert.

Could someone please post an example calculation, where you have a var that holds user input and a new var that receives the result of this computation? (all done in Objective C for use in an iPhone app) Thank you!

答:
Assuming you have a UIDatePicker, your target date will already be in an NSDate object. If it's coming from another source, you're probably ending up with it in an NSDate object, either from a string via an NSDateFormatter or by some other means.

From an NSDate object, you can get an NSTimeInterval relative to some absolute date. That's a C primitive type (it's a double in practice, but obviously don't code to depend on that) that you can do arithmetic directly on. So you can subtract 90 minutes directly from that. There are then various + dateWithTimeInterval... class methods on NSDate that will allow you to get a date from the result.

ContentLicense: CC BY-SA 3.0


问:
How do I remove the padding inside a div that has a propery of display and a value of inline-block
How do I remove the padding from inside of a div with the display set to "inline-block".

Below is the html and css.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="showExpCusWrap">
  <label for="showExpFrom">From</label>
  <input type="date" name="showExpFrom" id="showExpFrom">
  <label for="showExpTo">To</label>
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
</div></code>```

This is how it looks. Notice the top and bottom padding inside.

I have checked the broswer default styling. It does not set any padding. So, how to remove those? I want all the elements inside the div to appear without any spacing from top or bottom.

答:
I have come to this solution. May be this is the solution you are looking for. To your .showExpCusWrap class I add these lines of CSS and it's work for me.

```<code> /* add the following code*/
  line-height:1;
  font-size:0.9em;
</code>```

As you declare a relative font-size with em value; So to adjust the height of the inline block I took same amount of height with the help of line-height:1;. Here is full code for you.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
  /* add the following code*/
  line-height: 1;
  font-size: 0.9em;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}

* {
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="showExpCusWrap">
  <label for="showExpFrom">From</label>
  <input type="date" name="showExpFrom" id="showExpFrom">
  <label for="showExpTo">To</label>
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I remove the padding from inside of a div with the display set to "inline-block".

Below is the html and css.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}

  From
  <input type="date" name="showExpFrom" id="showExpFrom">
  To
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">

This is how it looks. Notice the top and bottom padding inside.

I have checked the broswer default styling. It does not set any padding. So, how to remove those? I want all the elements inside the div to appear without any spacing from top or bottom.

Body:
I have come to this solution. May be this is the solution you are looking for. To your .showExpCusWrap class I add these lines of CSS and it's work for me.

 /* add the following code*/
  line-height:1;
  font-size:0.9em;

As you declare a relative font-size with em value; So to adjust the height of the inline block I took same amount of height with the help of line-height:1;. Here is full code for you.

.showExpCusWrap {
  background-color: #A8D3FF;
  display: inline-block;
  border: 1px solid #004F9D;
  padding: 0px 10px;
  font-family: Tahoma;
  /* add the following code*/
  line-height: 1;
  font-size: 0.9em;
}

.showExpCusWrap label {
  font-size: 0.9em;
  margin: 0px;
  padding: 0px;
}

.showExpCusWrap input[type="date"] {
  margin: 0px;
  padding: 0px;
}

* {
  box-sizing: border-box;
}

<div class="showExpCusWrap">
  <label for="showExpFrom">From</label>
  <input type="date" name="showExpFrom" id="showExpFrom">
  <label for="showExpTo">To</label>
  <input type="date" name="showExpTo" id="showExpTo">
  <input type="button" name="showExpCus" id="showExpCus" value="Show" class="exp-button-small">
</div>


问:
trouble with Google API's?
I have been running google maps and google places API in my app for about a year now. I woke up today and was not able to use the map which was greyed out, or searches. In the console,

ERROR AUTO COMPLETE Error Domain=com.google.places.ErrorDomain Code=-4 "Operation failed due to an invalid (malformed or missing) API key. See the developer's guide (https://developers.google.com/places/ios-sdk/start) for information on creating and using an API key." UserInfo={NSLocalizedFailureReason=Operation failed due to an invalid (malformed or missing) API key. See the developer's guide (https://developers.google.com/places/ios-sdk/start) for information on creating and using an API key., NSUnderlyingError=0x283e81560 {Error Domain=com.google.places.api.server.ErrorDomain Code=-2 "REQUEST_DENIED" UserInfo={NSLocalizedFailureReason=This API project is not authorized to use this API. Please ensure this API is activated in the Google Developers Console: https://console.developers.google.com/apis/api/places_backend?project=_, NSLocalizedDescription=REQUEST_DENIED}}}

The thing is all of my API's are called in the right place and I have been able to use maps for a while. Why all of a sudden it stops working?

答:
Recently Google announced the new version of Places SDK client and deprecated the previous one. I believe you should migrate to new version asap, because the deprecated version will stop working very soon.

The new Places SDK client requires that you enable Places API web service in your Cloud project. The error message This API project is not authorized to use this API. Please ensure this API is activated in the Google Developers Console: https://console.developers.google.com/apis/api/places_backend?project=_,  refers to the Places API web service.

Double check if the Places API web service is enabled, API key created and billing account configured properly.

The official documentation has the following statement

To use the Places SDK for iOS, you must:

Include an API key with all API requests.

Enable billing on each of your projects.

Enable the Places API service for each of your projects

For further details have a look at migration guide:
https://developers.google.com/places/ios-sdk/client-migration

I hope this helps!

Title: trouble with Google API's?


问:
Opacity CSS that works for all browsers?
Can someone recommend the safest approach for giving an OPACITY VALUE to a DIV TAG using CSS?

Erik

答:
This will work in every browser.

```<code>div {
 -khtml-opacity:.50;
 -moz-opacity:.50;
 -ms-filter:”alpha(opacity=50)”;
  filter:alpha(opacity=50);
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
  opacity:.50;
}
</code>```

Or you can use jQuery and do it in a single line

```<code>$('div').css({opacity:0.5});
</code>```

Check working example at http://jsfiddle.net/397jv/

Body:
This will work in every browser.

div {
 -khtml-opacity:.50;
 -moz-opacity:.50;
 -ms-filter:”alpha(opacity=50)”;
  filter:alpha(opacity=50);
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
  opacity:.50;
}

Or you can use jQuery and do it in a single line

$('div').css({opacity:0.5});

Check working example at http://jsfiddle.net/397jv/


问:
Get all types of a Decorator Object: type of wrapped objects and the type of wrapper object
So, this is my design. AccessDecorator classes have a reference to another Access just like normal Decorator Pattern.

But the problem is when I create an AccessDecorator wrapping a ConcreteAccess and then try to see which type the Access is:

```<code>Access access = new InAllowedAccess();
Access wrapperAccess = new MismatchAccess(access);
if (wrapperAccess instanceof InAllowedAccess)   //this condition could be used to be a predicate for a filtering over an access list for example
    //do something
</code>```

Of course this won't work because wrapperAccess is not of type InAllowedAccess but what I really want to know is all the types of some Access. In this case, the wrapperAccess would be not only of type MismatchAccess but also of type InAllowedAccess

I thought about implementing methods like isInstanceofInAllowed(), isInstanceofOutAllowed(), isInstanceofInDenied() and isinstanceofOutDenied(), isinstanceofMismatch() in Access classes but don't seems a good solution, I don't know...

Otherwise should I create a big hierarchical tree with MismatchAccesses for each 4 types InAllowedMismatchAccess, OutAllowedMismatchAccess, InDeniedMismatchAccess and OutDeniedMismatchAccess? And then, when I develp another decorator?...

Or is there another better design?

How can I know all the types of an Access? Not only the type of the wrapper access but also the type of the wrapped access.

EDIT:
One of my needs is: filter a collection of Accesses by their type - ÌnAllowedAccess, InDeniedAccess, OutAllowedAccess, OutDeniedAccess, MismatchAccess (which is a decorator) and other types of decorators that I might develop

答:
Avoiding type checking is the usually the best way to do things. Unfortunately you haven't given enough context how you are going to use your classes so that I can give an example on how you can use polymorphism and avoid it.

Adding type checking will limit the ability of your system to grow because as new classes are added, these types need to be included in your type checks. Sometimes this can lead to bugs as your code can make assumptions of the number of classes or their types. Here's an example:

Note: I just made this up for illustrational purpose. It's not about having to represent your logic or anything like that.

```<code>public void someMethod(Access access) {

    if(access instance of InAccess) {
        InAccess inAccess = (InAccess)access;
    }
    else {
        OutAccess outAccess = (OutAccess)access;
    }
}
</code>```

When we started our system had two classes that inherit from Access. Assume that we add another Access class to our system. This code will crash on the else because we may pass the new third access type and the cast won't succeed.

Of course this isn't always the case. Sometimes the number of classes that you have won't grow too much. It's possible that you can predict all types that will have.

And of course, since all things can happen in programming, sometimes you do need to know the types of objects you are using.

Let's assume that your system do need to know the type of objects. Here are two solutions:

Add an enum that will represent all types that you have.

public enum AccessType {
        InAccessAllowed,
        InAccessDenied,
        OutAccessDenied,
        // other types
      }

```<code>public interface Access {
   AccessType getType();
   // other stuff
}
</code>```

This way you will use the enum AccessType instead of type casting.

Use interfaces.

Instead of using classes define an interface for each type of Access. Then you will check for the interfaces instead of classes. This way your decorators can implement the same interface as the class it decorates.

```<code>public interface InAllowedAccess { }

public class InAllowedAccessImp implements InAllowedAccess { }

public class InAllowedAccessDecorator implements InAllowedAccess { }
</code>```

I just wan't give an example of an alternative implementations. Since context is lacking in your description, I'll just try to guess how you are going to use your classes and add behavior to them. It's just an idea an nothing more.

Let's assume that your system grant access to users. Users can be given In and Out access and some part of your system need to ask if an access is granted or denied to a specific user so that it can execute a specific logic.

If you don't have any behavior associated with your Access classes you can just use it as a descriptor that will carry the information necessary for other classes to do their jobs.

```<code>public enum PortType { In, Out }
public enum Permissions { Allowed, Denied }

public class Access {
    private PortType mPortType;
    private Permissions mPermissions;

    public Access(PortType portType, Permissons permissions) {
        mPortType = portType;
        mPermissions = permissions;
    }

    public PortType getType() { return mPortType; }
    public Permissions getPermissions() { return mPermissions; }
}
</code>```

If you do have behavior, then you can use polymorphism. Define the behavior in your Access interface and let classes that impelement this interface define the behavior.

Let's say we have messaging system that a user can receive (In) and send (out) messages. These messages go trough a channel. These channels will either accept or reject messages. Here's a way you can use polymorphism instead of type checking.

```<code>public interface MessageChannel {

    public bool canSendMessages(); // out
    public bool canReceiveMessages(); // in

    public void receiveMessage(Message m);
    public void sendMessage(Message m);
}

public class InMessageChannel implements MessageChannel {

    // out messaging is not allowed, cannot send
    public bool canSendMessages() { return false; }

    // In messaging allowed, can receive
    public bool canReceiveMessages() { return true; }

    public void sendMessage(Message m) {
        throw new SendingMessagesIsNotAllowd();
    }
    public void receiveMessage(Message m); {
        // do something with the mssage
    }
}

public class OutMessageChannel implements MessageChannel {

    // out messaging allowed
    public bool canSendMessages() { return true; }

    // In messaging not allowed
    public bool canReceiveMessages() { return false; }

    public void sendMessage(Message m) {
        // send the message
    }

    public void receiveMessage(Message m); {
        throw new ReceivingMessagesIsNotAllowd();
    }
}
</code>```

As you can see each MessageCahnnel has a behavior accosiated with it. It can either send of receive messages if it's allowed or not. This way other classes that use the MessageChannel won't have to do type casting.

Body:
So, this is my design. AccessDecorator classes have a reference to another Access just like normal Decorator Pattern.

But the problem is when I create an AccessDecorator wrapping a ConcreteAccess and then try to see which type the Access is:

Access access = new InAllowedAccess();
Access wrapperAccess = new MismatchAccess(access);
if (wrapperAccess instanceof InAllowedAccess)   //this condition could be used to be a predicate for a filtering over an access list for example
    //do something

Of course this won't work because wrapperAccess is not of type InAllowedAccess but what I really want to know is all the types of some Access. In this case, the wrapperAccess would be not only of type MismatchAccess but also of type InAllowedAccess

I thought about implementing methods like isInstanceofInAllowed(), isInstanceofOutAllowed(), isInstanceofInDenied() and isinstanceofOutDenied(), isinstanceofMismatch() in Access classes but don't seems a good solution, I don't know...

Otherwise should I create a big hierarchical tree with MismatchAccesses for each 4 types InAllowedMismatchAccess, OutAllowedMismatchAccess, InDeniedMismatchAccess and OutDeniedMismatchAccess? And then, when I develp another decorator?...

Or is there another better design?

How can I know all the types of an Access? Not only the type of the wrapper access but also the type of the wrapped access.

EDIT:
One of my needs is: filter a collection of Accesses by their type - ÌnAllowedAccess, InDeniedAccess, OutAllowedAccess, OutDeniedAccess, MismatchAccess (which is a decorator) and other types of decorators that I might develop

Body:
Avoiding type checking is the usually the best way to do things. Unfortunately you haven't given enough context how you are going to use your classes so that I can give an example on how you can use polymorphism and avoid it.

Adding type checking will limit the ability of your system to grow because as new classes are added, these types need to be included in your type checks. Sometimes this can lead to bugs as your code can make assumptions of the number of classes or their types. Here's an example:

Note: I just made this up for illustrational purpose. It's not about having to represent your logic or anything like that.

public void someMethod(Access access) {

    if(access instance of InAccess) {
        InAccess inAccess = (InAccess)access;
    }
    else {
        OutAccess outAccess = (OutAccess)access;
    }
}

When we started our system had two classes that inherit from Access. Assume that we add another Access class to our system. This code will crash on the else because we may pass the new third access type and the cast won't succeed.

Of course this isn't always the case. Sometimes the number of classes that you have won't grow too much. It's possible that you can predict all types that will have.

And of course, since all things can happen in programming, sometimes you do need to know the types of objects you are using.

Let's assume that your system do need to know the type of objects. Here are two solutions:

Add an enum that will represent all types that you have.

public enum AccessType {
        InAccessAllowed,
        InAccessDenied,
        OutAccessDenied,
        // other types
      }

public interface Access {
   AccessType getType();
   // other stuff
}

This way you will use the enum AccessType instead of type casting.

Use interfaces.

Instead of using classes define an interface for each type of Access. Then you will check for the interfaces instead of classes. This way your decorators can implement the same interface as the class it decorates.

public interface InAllowedAccess { }

public class InAllowedAccessImp implements InAllowedAccess { }

public class InAllowedAccessDecorator implements InAllowedAccess { }

I just wan't give an example of an alternative implementations. Since context is lacking in your description, I'll just try to guess how you are going to use your classes and add behavior to them. It's just an idea an nothing more.

Let's assume that your system grant access to users. Users can be given In and Out access and some part of your system need to ask if an access is granted or denied to a specific user so that it can execute a specific logic.

If you don't have any behavior associated with your Access classes you can just use it as a descriptor that will carry the information necessary for other classes to do their jobs.

public enum PortType { In, Out }
public enum Permissions { Allowed, Denied }

public class Access {
    private PortType mPortType;
    private Permissions mPermissions;

    public Access(PortType portType, Permissons permissions) {
        mPortType = portType;
        mPermissions = permissions;
    }

    public PortType getType() { return mPortType; }
    public Permissions getPermissions() { return mPermissions; }
}

If you do have behavior, then you can use polymorphism. Define the behavior in your Access interface and let classes that impelement this interface define the behavior.

Let's say we have messaging system that a user can receive (In) and send (out) messages. These messages go trough a channel. These channels will either accept or reject messages. Here's a way you can use polymorphism instead of type checking.

public interface MessageChannel {

    public bool canSendMessages(); // out
    public bool canReceiveMessages(); // in

    public void receiveMessage(Message m);
    public void sendMessage(Message m);
}

public class InMessageChannel implements MessageChannel {

    // out messaging is not allowed, cannot send
    public bool canSendMessages() { return false; }

    // In messaging allowed, can receive
    public bool canReceiveMessages() { return true; }

    public void sendMessage(Message m) {
        throw new SendingMessagesIsNotAllowd();
    }
    public void receiveMessage(Message m); {
        // do something with the mssage
    }
}

public class OutMessageChannel implements MessageChannel {

    // out messaging allowed
    public bool canSendMessages() { return true; }

    // In messaging not allowed
    public bool canReceiveMessages() { return false; }

    public void sendMessage(Message m) {
        // send the message
    }

    public void receiveMessage(Message m); {
        throw new ReceivingMessagesIsNotAllowd();
    }
}

As you can see each MessageCahnnel has a behavior accosiated with it. It can either send of receive messages if it's allowed or not. This way other classes that use the MessageChannel won't have to do type casting.


问:
Understanding string reversal via slicing
I was looking for a way to print a string backwards, and after a quick search on google, I found this method:

Suppose a is a string variable. This will return the a string backwards:

```<code>a[::-1]
</code>```

Can anyone explain how that works?

答:
the first two bounds default to 0 and the length of the sequence, as before, and a stride of −1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.</p>

```<code>name="ravi"
print(name[::-1]) #ivar
</code>```

Body:
I was looking for a way to print a string backwards, and after a quick search on google, I found this method:

Suppose a is a string variable. This will return the a string backwards:

a[::-1]

Can anyone explain how that works?

Body:
the first two bounds default to 0 and the length of the sequence, as before, and a stride of −1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.

name="ravi"
print(name[::-1]) #ivar


问:
Why is the Java 11 runtime ignoring my jar containing sun.misc classes?
I am trying to upgrade my code base to Java 11. Unfortunately, my code has a dependency on a third-party library that internally uses sun.misc.BASE64Encoder and Decoder. Since the sun.misc package has been removed from the Java 11 JRE it is failing. The owner of that library has not replaced that dependency as yet, so I am stuck with it for a while.

If I had control of the code I would use java.util.BASE64 classes, but as I said these are coming in as a transitive dependency from another library, and I cannot change that.

I thought I would be clever and create a new jar with just those classes, but for some reason, that jar is being ignored.

```<code><dependency>
    <groupId>sun.misc</groupId>
    <artifactId>BASE64</artifactId>
    <version>1.8</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/sun.jar</systemPath>
</dependency>
</code>```

I also tried adding it to the classpath explicitly but still no luck

Is this one of those packages that the JRE prevents you from playing with, or am I missing some module specification, or is this a show stopper?

Here is the output

```<code>java.lang.NoClassDefFoundError: sun/misc/BASE64Encoder
at com.propsco.util.support.PropsLoader.save(PropsLoader.java:478) ~[props-client-2.2.1.jar:na]
</code>```

答:
This answer is written using

```<code>> java --version
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.3+7)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.3+7, mixed mode)
</code>```

First, you create the project that will have the overriden BASE64Encoder. Let's call it sun-misc-override. Under src\main\java create the sun.misc package with BASE64Encoder class.

```<code>package sun.misc;

public class BASE64Encoder {
    public String encode(byte[] aBuffer) {
        return "Fake it until you make it!";
    }
}
</code>```

If you try to compile it, you'll get a sun\misc\BASE64Encoder.java:1: error: package exists in another module: jdk.unsupported error.

That gives us a hint that we need to patch module jdk.unsupported. This is because classes from the original sun.misc package have been moved to the jdk.unsupported module when the module system was rolled out in Java 9 and then over time removed (see JEP-260).

With Maven you can configure your compiler plugin like this:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <release>11</release>
        <compilerArgs>
            <arg>--patch-module</arg>
            <arg>jdk.unsupported=${project.basedir}/src/main/java</arg>
        </compilerArgs>
    </configuration>
</plugin>
</code>```

After com.example:sun-misc-override:1.0.0-SNAPSHOT is built, place the resulting JAR in your "main" project - like you did eg. in a lib directory. I haven't found a way to make it work with a regular Maven dependency.

Now, configure the compiler plugin in your "main" project:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <release>11</release>
        <compilerArgs>
            <arg>--patch-module=jdk.unsupported=${project.basedir}/lib/sun-misc-override-1.0.0-SNAPSHOT.jar</arg>
        </compilerArgs>
    </configuration>
</plugin>
</code>```

(Probably due to MCOMPILER-311 I was getting a NPE when I tried to use

```<code><compilerArgs>
    <arg>--patch-module</arg>
    <arg>jdk.unsupported=${project.basedir}/lib/sun-misc-override-1.0.0-SNAPSHOT.jar</arg>
</compilerArgs>
</code>```

even though the bug was supposed to be fixed with maven-compiler-plugin 3.8.0 and it worked fine in the POM of sun-misc-override.)

Now my "main" project is called j11 and has one class:

```<code>package com.example;

import sun.misc.BASE64Encoder;

public class BASE64EncoderTest {
    public static void main(String[] args) {
        System.out.println("Testing - " + new BASE64Encoder().encode(new byte[0]));
    }
}
</code>```

To run it you need to specify --patch-module again:

```<code>> java --patch-module=jdk.unsupported=lib\sun-misc-override-1.0.0-SNAPSHOT.jar -cp target\j11-1.0.0-SNAPSHOT.jar com.example.BASE64EncoderTest
Testing - Fake it until you make it!
</code>```

Body:
I am trying to upgrade my code base to Java 11. Unfortunately, my code has a dependency on a third-party library that internally uses sun.misc.BASE64Encoder and Decoder. Since the sun.misc package has been removed from the Java 11 JRE it is failing. The owner of that library has not replaced that dependency as yet, so I am stuck with it for a while.

If I had control of the code I would use java.util.BASE64 classes, but as I said these are coming in as a transitive dependency from another library, and I cannot change that.

I thought I would be clever and create a new jar with just those classes, but for some reason, that jar is being ignored.

<dependency>
    <groupId>sun.misc</groupId>
    <artifactId>BASE64</artifactId>
    <version>1.8</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/sun.jar</systemPath>
</dependency>

I also tried adding it to the classpath explicitly but still no luck

Is this one of those packages that the JRE prevents you from playing with, or am I missing some module specification, or is this a show stopper?

Here is the output

java.lang.NoClassDefFoundError: sun/misc/BASE64Encoder
at com.propsco.util.support.PropsLoader.save(PropsLoader.java:478) ~[props-client-2.2.1.jar:na]

Body:
This answer is written using

> java --version
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.3+7)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.3+7, mixed mode)

First, you create the project that will have the overriden BASE64Encoder. Let's call it sun-misc-override. Under src\main\java create the sun.misc package with BASE64Encoder class.

package sun.misc;

public class BASE64Encoder {
    public String encode(byte[] aBuffer) {
        return "Fake it until you make it!";
    }
}

If you try to compile it, you'll get a sun\misc\BASE64Encoder.java:1: error: package exists in another module: jdk.unsupported error.

That gives us a hint that we need to patch module jdk.unsupported. This is because classes from the original sun.misc package have been moved to the jdk.unsupported module when the module system was rolled out in Java 9 and then over time removed (see JEP-260).

With Maven you can configure your compiler plugin like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <release>11</release>
        <compilerArgs>
            <arg>--patch-module</arg>
            <arg>jdk.unsupported=${project.basedir}/src/main/java</arg>
        </compilerArgs>
    </configuration>
</plugin>

After com.example:sun-misc-override:1.0.0-SNAPSHOT is built, place the resulting JAR in your "main" project - like you did eg. in a lib directory. I haven't found a way to make it work with a regular Maven dependency.

Now, configure the compiler plugin in your "main" project:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <release>11</release>
        <compilerArgs>
            <arg>--patch-module=jdk.unsupported=${project.basedir}/lib/sun-misc-override-1.0.0-SNAPSHOT.jar</arg>
        </compilerArgs>
    </configuration>
</plugin>

(Probably due to MCOMPILER-311 I was getting a NPE when I tried to use

<compilerArgs>
    <arg>--patch-module</arg>
    <arg>jdk.unsupported=${project.basedir}/lib/sun-misc-override-1.0.0-SNAPSHOT.jar</arg>
</compilerArgs>

even though the bug was supposed to be fixed with maven-compiler-plugin 3.8.0 and it worked fine in the POM of sun-misc-override.)

Now my "main" project is called j11 and has one class:

package com.example;

import sun.misc.BASE64Encoder;

public class BASE64EncoderTest {
    public static void main(String[] args) {
        System.out.println("Testing - " + new BASE64Encoder().encode(new byte[0]));
    }
}

To run it you need to specify --patch-module again:

> java --patch-module=jdk.unsupported=lib\sun-misc-override-1.0.0-SNAPSHOT.jar -cp target\j11-1.0.0-SNAPSHOT.jar com.example.BASE64EncoderTest
Testing - Fake it until you make it!


问:
Why react-native doesn't render all content when 2 render methods included in it?
I have some content to be rendered conditionally and some fixed content i.e. footer. I dont want to render footer every time when state changes, hence I've added two methods renderContent() and renderFooter to be called in render() method.

Below code, doesn't render both methods.

```<code>'use strict';

import React, { Component } from 'react';
import { Alert, FlatList, View, StyleSheet, Text, Linking, Button } from 'react-native';
import { AsyncStorage } from 'react-native';
import getEnvVars from '../environment';
const { apiUrl } = getEnvVars();
import Moment from 'moment';
import { Ionicons } from '@expo/vector-icons';
import FootBar from '../screens/FootBar';
import { LinesLoader } from 'react-native-indicator';

export default class SubscriptionsToEnd extends Component {
    static navigationOptions = ({ navigation }) => {
        const { state } = navigation;

        return {
            title: `${state.params && state.params.title ? state.params.title : 'Subscriptions Due'}`,
        };
    };

    constructor(props) {
        super(props);
        this.state = {
            isLoaded: false,
            dataSource: [],
            title: 'Subscriptions Due'
        };
    }

    componentDidMount() {
        this._getAllCustomers();
    }

    _getAllCustomers() {
        let url;
        if (this.state.title === 'Subscriptions Due') {
            url = apiUrl + "/customersWithSubscriptionNearToEnd/";
            this.props.navigation.setParams({ title: 'Subscriptions Due' })
        }
        if (this.state.title === 'Customers') {
            url = apiUrl + "/customers/";
            this.props.navigation.setParams({ title: 'Customers' })
        }

        this.setState({ isLoaded: false })

        try {
            AsyncStorage.multiGet(['role', 'jwt']).then((data) => {
                let role = data[0][1];
                let jwt = data[1][1];
                if (role === 'Admin') {
                    fetch(url, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'jwt': jwt
                        },
                    }).then(res => res.json())
                        .then(
                            (result) => {
                                if (result.message != 'Unauthorized user!' && this.state.title === 'Customers') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Subscriptions Due'

                                    });
                                } else if (result.message != 'Unauthorized user!' && this.state.title === 'Subscriptions Due') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Customers'

                                    });
                                } else if (result.message === 'Unauthorized user!') {
                                    this.props.navigation.navigate('Login');
                                }
                            },
                            (error) => {
                                console.log(error);
                                this.setState({
                                    isLoaded: true
                                });
                                this.props.navigation.navigate('Login');
                            }
                        )
                }
            })

        } catch (error) {
            console.log('Error at getting token \n' + error)
        }
    }

    GetGridViewItem(id) {
        Alert.alert(id);
    }

    _logOutAsync = async () => {
        await AsyncStorage.clear();
        this.props.navigation.navigate('Auth');
    };

    _addCustomer() {
        // TBD
    }

    renderContent() {
        if (!this.state.isLoaded) {
            return (
                <View style={styles.loader}>
                    <LinesLoader color='#1d91a5' barWidth={5} barHeight={60} barNumber={5} betweenSpace={5} />
                </View>
            )
        }

        if (this.state.isLoaded) {
            return (
                <View style={styles.container}>
                    <View style={styles.grid}>
                        <FlatList
                            data={this.state.dataSource}
                            renderItem={({ item }) =>
                                <View style={styles.GridViewContainer}>
                                    <Text style={styles.GridViewTextLayout}>
                                        <Text onPress={this.GetGridViewItem.bind(this, item._id)}>
                                            <Text style={styles.Name}>{item.firstname}</Text> <Text style={styles.Name}>{item.lastname}</Text> {"\n"}
                                            <Text>{Moment(item.till_date).format('Do MMM YYYY')} </Text>{"\n\n"}
                                        </Text>
                                        <Text onPress={() => { Linking.openURL('tel:+44' + item.mobile); }}><Ionicons name="md-phone-portrait" size={22} color="#1d91a5" />  {item.mobile}</Text> {"\n\n"}
                                        <Text><Ionicons name="md-mail" size={22} color="#1d91a5" />{item.email}</Text>
                                    </Text>
                                </View>}
                            numColumns={2}
                            keyExtractor={(item, index) => index.toString()}
                        />
                    </View >
                </View>
            )
        };
    }
    renderFooter() {
        return (
            <View style={styles.buttonsContainer}>
                <View style={styles.button}>
                    <Button color='#1d91a5' title={this.state.title} onPress={this._getAllCustomers.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="+Customer" onPress={this._addCustomer.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="Logout" onPress={this._logOutAsync.bind(this)} />
                </View>
            </View>
        );
    }

    render() {
        return (
            this.renderContent(),
            this.renderFooter()
        );
    }

}
</code>```

Above code only renders this.renderFooter() method. If I swap methods in render(), it renders this.renderContent().

Can someone please tell me why it is failing to render both?

答:
I was doing it wrong. Main render() method should be like:

```<code>    render() {
        return (
            <View style={styles.wrapper}>
                {this.renderContent()}
                {this.renderFooter()}
            </View>

        );
    }

</code>```

Body:
I have some content to be rendered conditionally and some fixed content i.e. footer. I dont want to render footer every time when state changes, hence I've added two methods renderContent() and renderFooter to be called in render() method.

Below code, doesn't render both methods.

'use strict';

import React, { Component } from 'react';
import { Alert, FlatList, View, StyleSheet, Text, Linking, Button } from 'react-native';
import { AsyncStorage } from 'react-native';
import getEnvVars from '../environment';
const { apiUrl } = getEnvVars();
import Moment from 'moment';
import { Ionicons } from '@expo/vector-icons';
import FootBar from '../screens/FootBar';
import { LinesLoader } from 'react-native-indicator';

export default class SubscriptionsToEnd extends Component {
    static navigationOptions = ({ navigation }) => {
        const { state } = navigation;

        return {
            title: `${state.params && state.params.title ? state.params.title : 'Subscriptions Due'}`,
        };
    };

    constructor(props) {
        super(props);
        this.state = {
            isLoaded: false,
            dataSource: [],
            title: 'Subscriptions Due'
        };
    }

    componentDidMount() {
        this._getAllCustomers();
    }

    _getAllCustomers() {
        let url;
        if (this.state.title === 'Subscriptions Due') {
            url = apiUrl + "/customersWithSubscriptionNearToEnd/";
            this.props.navigation.setParams({ title: 'Subscriptions Due' })
        }
        if (this.state.title === 'Customers') {
            url = apiUrl + "/customers/";
            this.props.navigation.setParams({ title: 'Customers' })
        }

        this.setState({ isLoaded: false })

        try {
            AsyncStorage.multiGet(['role', 'jwt']).then((data) => {
                let role = data[0][1];
                let jwt = data[1][1];
                if (role === 'Admin') {
                    fetch(url, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'jwt': jwt
                        },
                    }).then(res => res.json())
                        .then(
                            (result) => {
                                if (result.message != 'Unauthorized user!' && this.state.title === 'Customers') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Subscriptions Due'

                                    });
                                } else if (result.message != 'Unauthorized user!' && this.state.title === 'Subscriptions Due') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Customers'

                                    });
                                } else if (result.message === 'Unauthorized user!') {
                                    this.props.navigation.navigate('Login');
                                }
                            },
                            (error) => {
                                console.log(error);
                                this.setState({
                                    isLoaded: true
                                });
                                this.props.navigation.navigate('Login');
                            }
                        )
                }
            })

        } catch (error) {
            console.log('Error at getting token \n' + error)
        }
    }

    GetGridViewItem(id) {
        Alert.alert(id);
    }

    _logOutAsync = async () => {
        await AsyncStorage.clear();
        this.props.navigation.navigate('Auth');
    };

    _addCustomer() {
        // TBD
    }

    renderContent() {
        if (!this.state.isLoaded) {
            return (
                <View style={styles.loader}>
                    <LinesLoader color='#1d91a5' barWidth={5} barHeight={60} barNumber={5} betweenSpace={5} />
                </View>
            )
        }

        if (this.state.isLoaded) {
            return (
                <View style={styles.container}>
                    <View style={styles.grid}>
                        <FlatList
                            data={this.state.dataSource}
                            renderItem={({ item }) =>
                                <View style={styles.GridViewContainer}>
                                    <Text style={styles.GridViewTextLayout}>
                                        <Text onPress={this.GetGridViewItem.bind(this, item._id)}>
                                            <Text style={styles.Name}>{item.firstname}</Text> <Text style={styles.Name}>{item.lastname}</Text> {"\n"}
                                            <Text>{Moment(item.till_date).format('Do MMM YYYY')} </Text>{"\n\n"}
                                        </Text>
                                        <Text onPress={() => { Linking.openURL('tel:+44' + item.mobile); }}><Ionicons name="md-phone-portrait" size={22} color="#1d91a5" />  {item.mobile}</Text> {"\n\n"}
                                        <Text><Ionicons name="md-mail" size={22} color="#1d91a5" />{item.email}</Text>
                                    </Text>
                                </View>}
                            numColumns={2}
                            keyExtractor={(item, index) => index.toString()}
                        />
                    </View >
                </View>
            )
        };
    }
    renderFooter() {
        return (
            <View style={styles.buttonsContainer}>
                <View style={styles.button}>
                    <Button color='#1d91a5' title={this.state.title} onPress={this._getAllCustomers.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="+Customer" onPress={this._addCustomer.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="Logout" onPress={this._logOutAsync.bind(this)} />
                </View>
            </View>
        );
    }

    render() {
        return (
            this.renderContent(),
            this.renderFooter()
        );
    }

}

Above code only renders this.renderFooter() method. If I swap methods in render(), it renders this.renderContent().

Can someone please tell me why it is failing to render both?

Body:
I was doing it wrong. Main render() method should be like:

    render() {
        return (
            <View style={styles.wrapper}>
                {this.renderContent()}
                {this.renderFooter()}
            </View>

        );
    }


问:
jQuery form submit: Any way to know what element triggered the submit?
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

```<code>$('form').submit(function() {
    ...code done here to validate form fields
});
</code>```

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

答:
I asked this same question: How can I get the button that caused the submit from the form submit event?

The only cross-browser solution I could come up with was this:

```<code>$(document).ready(function() {
    $("form").submit(function() {

    var val = $("input[type=submit][clicked=true]").val()

    // DO WORK

});

$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});
</code>```

Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.

Body:
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

$('form').submit(function() {
    ...code done here to validate form fields
});

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

Body:
I asked this same question: How can I get the button that caused the submit from the form submit event?

The only cross-browser solution I could come up with was this:

$(document).ready(function() {
    $("form").submit(function() {

    var val = $("input[type=submit][clicked=true]").val()

    // DO WORK

});

$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.


问:
Check whether string in palindrome : C# code efficiency
I am coming from C background and recently started writing in C# so please don't mind if my question seems somewhat basic. Basically, i want to write a function which will return true if string is palindrome and false if not.

The string may contain characters like space, ',', ':' which i have to ignore. I have written the code as below

```<code>    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int j = s.Length - 1;

        for(int i = 0; i < s.Length/2; i++)
        {
            if(s[i].ToString().Equals(s[j].ToString(),StringComparison.InvariantCultureIgnoreCase))
            {
                j--;
            }
            else
            {
                return false;
            }
        }
        return true;

    }
</code>```

where the function will be invoked with the following string

```<code>string s = "A man, a plan, a canal: Panama";
</code>```

I read in the documentation that in C#, string are immutable so each time i do a operation like replace or ToString, a new copy is getting created.

So i wanted to check that
i).  Is this code efficient?
ii). If not, how to make it more efficient.

答:
This would be more readable approach for the Plaindrome detection comparing to the for loop you have written:

A short approach but not necessary efficient due to Array.Reverse which Reverses the order of the elements :

```<code>static bool IsPalindrome(string s)
{
    s = s.Replace(" ", "");
    s = s.Replace(",", "");
    s = s.Replace(":", "");

    char[] array = s.ToCharArray();
    Array.Reverse(array);
    string backwards = new string(array);

    return s == backwards;
}
</code>```

A more efficient approach which requires more lines of coding would be :

```<code>    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int i = 0;
        int j = s.Length - 1;

        while (i < j)
        {
            if (s[i].ToString().ToLower() != s[j].ToString().ToLower())
                return false;

            i++;
            j--;
        }
        return true;
    }
</code>```

Another approach similar to the 2nd one but without the needs of converting the char into String for comparison:

```<code>    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int i = 0;
        int j = s.Length - 1;

        while (i < j)
        {

            if (!char.ToLower(s[i]).Equals(char.ToLower(s[j])))
                return false;

            i++;
            j--;
        }
        return true;
    }
</code>```

Body:
I am coming from C background and recently started writing in C# so please don't mind if my question seems somewhat basic. Basically, i want to write a function which will return true if string is palindrome and false if not.

The string may contain characters like space, ',', ':' which i have to ignore. I have written the code as below

    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int j = s.Length - 1;

        for(int i = 0; i < s.Length/2; i++)
        {
            if(s[i].ToString().Equals(s[j].ToString(),StringComparison.InvariantCultureIgnoreCase))
            {
                j--;
            }
            else
            {
                return false;
            }
        }
        return true;

    }

where the function will be invoked with the following string

string s = "A man, a plan, a canal: Panama";

I read in the documentation that in C#, string are immutable so each time i do a operation like replace or ToString, a new copy is getting created.

So i wanted to check that
i).  Is this code efficient?
ii). If not, how to make it more efficient.

Body:
This would be more readable approach for the Plaindrome detection comparing to the for loop you have written:

A short approach but not necessary efficient due to Array.Reverse which Reverses the order of the elements :

static bool IsPalindrome(string s)
{
    s = s.Replace(" ", "");
    s = s.Replace(",", "");
    s = s.Replace(":", "");

    char[] array = s.ToCharArray();
    Array.Reverse(array);
    string backwards = new string(array);

    return s == backwards;
}

A more efficient approach which requires more lines of coding would be :

    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int i = 0;
        int j = s.Length - 1;

        while (i < j)
        {
            if (s[i].ToString().ToLower() != s[j].ToString().ToLower())
                return false;

            i++;
            j--;
        }
        return true;
    }

Another approach similar to the 2nd one but without the needs of converting the char into String for comparison:

    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int i = 0;
        int j = s.Length - 1;

        while (i < j)
        {

            if (!char.ToLower(s[i]).Equals(char.ToLower(s[j])))
                return false;

            i++;
            j--;
        }
        return true;
    }


问:
Flutter apk/ipa size vs React Native apk/ipa size
React Native APK size for a hello world example is around 20M (in recent versions) because of support different hardware architectures (ARMv7, ARMv8, X86, etc) while Flutter APK size for same application is around 7M.

What's the reason for the difference in size? Do Flutter support all hardware architecture?

答:
So Junius answer is correct but I don't believe covers the reason why. So Flutter compiles to 100% native code, where RN uses a combination of native code and JavaScript communicating across a bridge.

That is why Flutter does not need to add the JavaScript core thus, the size is smaller. But anyway, as your app grows, the JS part will always be around the same size.


问:
parsing a JSON string Pyspark dataframe column that has string of array in one of the columns
I am trying to read a JSON file and parse 'jsonString' and the underlying fields which includes array into a pyspark dataframe.

Here is the contents of json file.

```<code>[{"jsonString": "{\"uid\":\"value1\",\"adUsername\":\"value3\",\"courseCertifications\":[{\"uid\":\"value2\",\"courseType\":\"TRAINING\"},{\"uid\":\"TEST\",\"courseType\":\"TRAINING\"}],\"modifiedBy\":\"value4\"}","transactionId": "value5", "tableName": "X"},
 {"jsonString": "{\"uid\":\"value11\",\"adUsername\":\"value13\",\"modifiedBy\":\"value14\"}","transactionId": "value15", "tableName": "X1"},
 {"jsonString": "{\"uid\":\"value21\",\"adUsername\":\"value23\",\"modifiedBy\":\"value24\"}","transactionId": "value25", "tableName": "X2"}]
</code>```

I am able to parse contents of string 'jsonString' and select required columns using the below logic

```<code>df = spark.read.json('path.json',multiLine=True)
df = df.withColumn('courseCertifications', explode(array(get_json_object(df['jsonString'],'$.courseCertifications'))))

</code>```

Now my end goal is to parse field "courseType" from "courseCertifications" and create one row per instance.

I am using below logic to get "courseType"

```<code>df = df.withColumn('new',get_json_object(df.courseCertifications, '$[*].courseType'))
</code>```

I am able to get the contents of "courseType" but as a string as shown below

```<code>[Row(new=u'["TRAINING","TRAINING"]')]
</code>```

My end goal is to create a dataframe with columns transactionId, jsonString.uid, jsonString.adUsername, jsonString.courseCertifications.uid, jsonString.courseCertifications.courseType

I need to retain all the rows and create multiple rows one per array instances of courseCertifications.uid/courseCertifications.courseType.

答:
An elegant manner to resolve your question is creating the schema of the json string and then parse it using from_json function

import pyspark.sql.functions as f
from pyspark.shell import spark
from pyspark.sql.types import ArrayType, StringType, StructType, StructField

df = spark.read.json('your_path', multiLine=True)
schema = StructType([
    StructField('uid', StringType()),
    StructField('adUsername', StringType()),
    StructField('modifiedBy', StringType()),
    StructField('courseCertifications', ArrayType(
        StructType([
            StructField('uid', StringType()),
            StructField('courseType', StringType())
        ])
    ))
])

df = df \
    .withColumn('tmp', f.from_json(df.jsonString, schema)) \
    .withColumn('adUsername', f.col('tmp').adUsername) \
    .withColumn('uid', f.col('tmp').uid) \
    .withColumn('modifiedBy', f.col('tmp').modifiedBy) \
    .withColumn('tmp', f.explode(f.col('tmp').courseCertifications)) \
    .withColumn('course_uid', f.col('tmp').uid) \
    .withColumn('course_type', f.col('tmp').courseType) \
    .drop('jsonString', 'tmp')
df.show()
```

<p>Output:</p>

```+-------------+------+----------+----------+----------+-----------+
|transactionId|uid   |adUsername|modifiedBy|course_uid|course_type|
+-------------+------+----------+----------+----------+-----------+
|value5       |value1|value3    |value4    |value2    |TRAINING   |
|value5       |value1|value3    |value4    |TEST      |TRAINING   |
+-------------+------+----------+----------+----------+-----------+
```

Body:
I am trying to read a JSON file and parse 'jsonString' and the underlying fields which includes array into a pyspark dataframe.

Here is the contents of json file.

[{"jsonString": "{\"uid\":\"value1\",\"adUsername\":\"value3\",\"courseCertifications\":[{\"uid\":\"value2\",\"courseType\":\"TRAINING\"},{\"uid\":\"TEST\",\"courseType\":\"TRAINING\"}],\"modifiedBy\":\"value4\"}","transactionId": "value5", "tableName": "X"},
 {"jsonString": "{\"uid\":\"value11\",\"adUsername\":\"value13\",\"modifiedBy\":\"value14\"}","transactionId": "value15", "tableName": "X1"},
 {"jsonString": "{\"uid\":\"value21\",\"adUsername\":\"value23\",\"modifiedBy\":\"value24\"}","transactionId": "value25", "tableName": "X2"}]

I am able to parse contents of string 'jsonString' and select required columns using the below logic

df = spark.read.json('path.json',multiLine=True)
df = df.withColumn('courseCertifications', explode(array(get_json_object(df['jsonString'],'$.courseCertifications'))))

Now my end goal is to parse field "courseType" from "courseCertifications" and create one row per instance.

I am using below logic to get "courseType"

df = df.withColumn('new',get_json_object(df.courseCertifications, '$[*].courseType'))

I am able to get the contents of "courseType" but as a string as shown below

[Row(new=u'["TRAINING","TRAINING"]')]

My end goal is to create a dataframe with columns transactionId, jsonString.uid, jsonString.adUsername, jsonString.courseCertifications.uid, jsonString.courseCertifications.courseType

I need to retain all the rows and create multiple rows one per array instances of courseCertifications.uid/courseCertifications.courseType.

Body:
An elegant manner to resolve your question is creating the schema of the json string and then parse it using from_json function

import pyspark.sql.functions as f
from pyspark.shell import spark
from pyspark.sql.types import ArrayType, StringType, StructType, StructField

df = spark.read.json('your_path', multiLine=True)
schema = StructType([
    StructField('uid', StringType()),
    StructField('adUsername', StringType()),
    StructField('modifiedBy', StringType()),
    StructField('courseCertifications', ArrayType(
        StructType([
            StructField('uid', StringType()),
            StructField('courseType', StringType())
        ])
    ))
])

df = df \
    .withColumn('tmp', f.from_json(df.jsonString, schema)) \
    .withColumn('adUsername', f.col('tmp').adUsername) \
    .withColumn('uid', f.col('tmp').uid) \
    .withColumn('modifiedBy', f.col('tmp').modifiedBy) \
    .withColumn('tmp', f.explode(f.col('tmp').courseCertifications)) \
    .withColumn('course_uid', f.col('tmp').uid) \
    .withColumn('course_type', f.col('tmp').courseType) \
    .drop('jsonString', 'tmp')
df.show()

Output:

+-------------+------+----------+----------+----------+-----------+
|transactionId|uid   |adUsername|modifiedBy|course_uid|course_type|
+-------------+------+----------+----------+----------+-----------+
|value5       |value1|value3    |value4    |value2    |TRAINING   |
|value5       |value1|value3    |value4    |TEST      |TRAINING   |
+-------------+------+----------+----------+----------+-----------+


问:
Android Java - using intent to pass value to second activity
I'm writing an android app that tracks your weight and BMI. In order to update or set the two values for the first time, there is a second activity that allows me to input the values that should then pass to the first activity.

I've tried to achieve this in a few ways, the closest I got is the code below:

Second Activity: (UpdateProgressActivity.java)

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_body_progress);

    Intent intentWeight = getIntent();
    String WeightText = intentWeight.getStringExtra(EXTRA_MESSAGE);
    TextView messageWeight = findViewById(R.id.weight);
    messageWeight.setText(WeightText);

    Intent intentBMI = getIntent();
    String BMIText = intentBMI.getStringExtra(EXTRA_MESSAGE);
    TextView messageBMI = findViewById(R.id.bmi);
    messageBMI.setText(BMIText);

    updateButton = findViewById(R.id.updateBodyProgress);
    updateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openActivityUpdateProgress();
        }
    });

}
</code>```

First Activity: (BodyProgressActivity.java)

```<code>public class UpdateProgressActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_update_progress);

    Button confirmProgress;
    confirmProgress = findViewById(R.id.confirmBodyStatus);
    confirmProgress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            returnToActivityProgress();
        }
    });

}

protected void returnToActivityProgress() {
    Intent intent = new Intent(this, BodyProgressActivity.class);
    startActivity(intent);
}

public void createStatus(View view) {
    EditText messageWeight = findViewById(R.id.textNewWeight);
    String textWeight = messageWeight.getText().toString();
    Intent intentWeight = new Intent(Intent.ACTION_SEND); intentWeight.setType("text/plain");
    intentWeight.putExtra(Intent.EXTRA_TEXT, textWeight);
    String textWeigthTemp = getString(R.string.currentWeight);
    Intent chosenIntentWeight = Intent.createChooser(intentWeight, textWeigthTemp);
    startActivity(chosenIntentWeight);

    EditText messageBMI = findViewById(R.id.textNewWeight);
    String textBMI = messageBMI.getText().toString();
    Intent intentBMI = new Intent(Intent.ACTION_SEND); intentBMI.setType("text/plain");
    intentWeight.putExtra(Intent.EXTRA_TEXT, textBMI);
    String textBMITemp = getString(R.string.currentBMI);
    Intent chosenIntentBMI = Intent.createChooser(intentWeight, textBMITemp);
    startActivity(chosenIntentBMI);
}
</code>```

}

I'm getting the values from "textNewWeight" and "textNewBMI" from the second activity and must pass them to "weight" and "bmi" on the first activity.
What I'm getting in the first activity is just blank.

答:
In the first activity. Use this code. We are using putExtra method to send the data to next activity through key and value. Key is the 1st parameter and value is the 2nd parameter. Key name can be your choice and it is used to retrieve the data in the 2nd activity. Value is the data which you want ti send to next activity.

```<code>    Intent i=new Intent(firstactivity.this,secondactivity.class);
    String weight=messageWeight.getText().toString();
    i.putExtra(“weight”,weight);
    startActivity(i);
</code>```

In the second activity,use this to recieve the data.

```<code>   Bundle b=getIntent().getExtras();
   String recievedWeight=b.getString(“weight”);
</code>```

the parameter name in the b.getString(“”) must be same as which you have declared in the 1st activity.

Body:
I'm writing an android app that tracks your weight and BMI. In order to update or set the two values for the first time, there is a second activity that allows me to input the values that should then pass to the first activity.

I've tried to achieve this in a few ways, the closest I got is the code below:

Second Activity: (UpdateProgressActivity.java)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_body_progress);

    Intent intentWeight = getIntent();
    String WeightText = intentWeight.getStringExtra(EXTRA_MESSAGE);
    TextView messageWeight = findViewById(R.id.weight);
    messageWeight.setText(WeightText);

    Intent intentBMI = getIntent();
    String BMIText = intentBMI.getStringExtra(EXTRA_MESSAGE);
    TextView messageBMI = findViewById(R.id.bmi);
    messageBMI.setText(BMIText);

    updateButton = findViewById(R.id.updateBodyProgress);
    updateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openActivityUpdateProgress();
        }
    });

}

First Activity: (BodyProgressActivity.java)

public class UpdateProgressActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_update_progress);

    Button confirmProgress;
    confirmProgress = findViewById(R.id.confirmBodyStatus);
    confirmProgress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            returnToActivityProgress();
        }
    });

}

protected void returnToActivityProgress() {
    Intent intent = new Intent(this, BodyProgressActivity.class);
    startActivity(intent);
}

public void createStatus(View view) {
    EditText messageWeight = findViewById(R.id.textNewWeight);
    String textWeight = messageWeight.getText().toString();
    Intent intentWeight = new Intent(Intent.ACTION_SEND); intentWeight.setType("text/plain");
    intentWeight.putExtra(Intent.EXTRA_TEXT, textWeight);
    String textWeigthTemp = getString(R.string.currentWeight);
    Intent chosenIntentWeight = Intent.createChooser(intentWeight, textWeigthTemp);
    startActivity(chosenIntentWeight);

    EditText messageBMI = findViewById(R.id.textNewWeight);
    String textBMI = messageBMI.getText().toString();
    Intent intentBMI = new Intent(Intent.ACTION_SEND); intentBMI.setType("text/plain");
    intentWeight.putExtra(Intent.EXTRA_TEXT, textBMI);
    String textBMITemp = getString(R.string.currentBMI);
    Intent chosenIntentBMI = Intent.createChooser(intentWeight, textBMITemp);
    startActivity(chosenIntentBMI);
}

}

I'm getting the values from "textNewWeight" and "textNewBMI" from the second activity and must pass them to "weight" and "bmi" on the first activity.
What I'm getting in the first activity is just blank.

Body:
In the first activity. Use this code. We are using putExtra method to send the data to next activity through key and value. Key is the 1st parameter and value is the 2nd parameter. Key name can be your choice and it is used to retrieve the data in the 2nd activity. Value is the data which you want ti send to next activity.

    Intent i=new Intent(firstactivity.this,secondactivity.class);
    String weight=messageWeight.getText().toString();
    i.putExtra(“weight”,weight);
    startActivity(i);

In the second activity,use this to recieve the data.

   Bundle b=getIntent().getExtras();
   String recievedWeight=b.getString(“weight”);

the parameter name in the b.getString(“”) must be same as which you have declared in the 1st activity.


问:
How to unmarshall YAML v3 with full access to node
I'm trying to learn to use YAML v3 unmarshaling with full access to the Node in a complex embedded struct.

The announcement post explains how to use yaml.Node, but doesn't give a serious example. And the documentation also doesn't show working with the Node. The primary purpose seems to be the excellent preservation of comments in YAML files.

For example, working with an extension of the announcement article, I have

package main

import(
    "fmt"
    "gopkg.in/yaml.v3"
    "os"
)

func main() {

    type Person struct {
        Name    string
        Address yaml.Node
    }

    data := `
name: John Doe
address:
    street: 123 E 3rd St # street is like an avenue
    city: Denver  # A city might be a town as well
    state: CO  # A state might be a province or administrative unit
    zip: 81526 # zip might be "postal_code"
`

    var person Person
    err := yaml.Unmarshal([]byte(data), &person)
    if (err != nil) {
        fmt.Printf("Failed to unmarshall: %v", err)
        os.Exit(1)
    }
    fmt.Printf("Marshalled person=%v", person)

}
```

But if I try to use the address items, I find them each listed as an array of Content inside the node; there's no actual useful information there. The comments are in there, but it's not clear what they're associated with.

Modify existing yaml file and add new data and comments also deals with the same territory, but doesn't show navigating the structure after unmarshalling into the struct.

How can I navigate the "Address" node once unmarshalled, and preserve the comments on marshalling again?

答:
You have to declare the complete struct instead of using yaml.Node

```<code>package main

import (
    "fmt"
    "gopkg.in/yaml.v3"
    "os"
)

func main() {
    type Address struct {
        Street string
        City   string
        State  string
        Zip    string
    }
    type Person struct {
        Name    string
        Address Address
    }

data := `
    name: John Doe
    address:
        street: 123 E 3rd St
        city: Denver
        state: CO
        zip: 81526
    `

    var person Person
    err := yaml.Unmarshal([]byte(data), &person)
    if (err != nil) {
        fmt.Printf("Failed to unmarshall: %v", err)
        os.Exit(1)
    }
    fmt.Printf("Marshalled person=%v", person)
}
</code>```

yaml.Node seems like an intermediate representation.
It has to be decoded to get the values.

```<code>package main

import (
    "fmt"
    "gopkg.in/yaml.v3"
    "os"
)

func main() {
    type Address struct {
        Street string
        City   string
        State  string
        Zip    string
    }
type Person struct {
    Name    string
    Address yaml.Node
}

data := `
name: John Doe
address:
    street: 123 E 3rd St
    city: Denver
    state: CO
    zip: 81526
`

var person Person
err := yaml.Unmarshal([]byte(data), &person)
if (err != nil) {
    fmt.Printf("Failed to unmarshall: %v", err)
    os.Exit(1)
}
address := &Address{}
_ = person.Address.Decode(address)
fmt.Printf("Marshalled person=%v\n %v", person, *address)

}
</code>```

Body:
I'm trying to learn to use YAML v3 unmarshaling with full access to the Node in a complex embedded struct.

The announcement post explains how to use yaml.Node, but doesn't give a serious example. And the documentation also doesn't show working with the Node. The primary purpose seems to be the excellent preservation of comments in YAML files.

For example, working with an extension of the announcement article, I have

package main

import(
    "fmt"
    "gopkg.in/yaml.v3"
    "os"
)

func main() {

    type Person struct {
        Name    string
        Address yaml.Node
    }

    data := `
name: John Doe
address:
    street: 123 E 3rd St # street is like an avenue
    city: Denver  # A city might be a town as well
    state: CO  # A state might be a province or administrative unit
    zip: 81526 # zip might be "postal_code"
`

    var person Person
    err := yaml.Unmarshal([]byte(data), &person)
    if (err != nil) {
        fmt.Printf("Failed to unmarshall: %v", err)
        os.Exit(1)
    }
    fmt.Printf("Marshalled person=%v", person)

}

But if I try to use the address items, I find them each listed as an array of Content inside the node; there's no actual useful information there. The comments are in there, but it's not clear what they're associated with.

Modify existing yaml file and add new data and comments also deals with the same territory, but doesn't show navigating the structure after unmarshalling into the struct.

How can I navigate the "Address" node once unmarshalled, and preserve the comments on marshalling again?

Body:
You have to declare the complete struct instead of using yaml.Node

package main

import (
    "fmt"
    "gopkg.in/yaml.v3"
    "os"
)

func main() {
    type Address struct {
        Street string
        City   string
        State  string
        Zip    string
    }
    type Person struct {
        Name    string
        Address Address
    }

data := `
    name: John Doe
    address:
        street: 123 E 3rd St
        city: Denver
        state: CO
        zip: 81526
    `

    var person Person
    err := yaml.Unmarshal([]byte(data), &person)
    if (err != nil) {
        fmt.Printf("Failed to unmarshall: %v", err)
        os.Exit(1)
    }
    fmt.Printf("Marshalled person=%v", person)
}

yaml.Node seems like an intermediate representation.
It has to be decoded to get the values.

package main

import (
    "fmt"
    "gopkg.in/yaml.v3"
    "os"
)

func main() {
    type Address struct {
        Street string
        City   string
        State  string
        Zip    string
    }
type Person struct {
    Name    string
    Address yaml.Node
}

data := `
name: John Doe
address:
    street: 123 E 3rd St
    city: Denver
    state: CO
    zip: 81526
`

var person Person
err := yaml.Unmarshal([]byte(data), &person)
if (err != nil) {
    fmt.Printf("Failed to unmarshall: %v", err)
    os.Exit(1)
}
address := &Address{}
_ = person.Address.Decode(address)
fmt.Printf("Marshalled person=%v\n %v", person, *address)

}


问:
How should I use Powershell to timestamp pings with 24-hour time?
I need to ping things in Windows and know what time pings were received or missed; the timestamps should reflect 24-hour time (instead of an AM/PM suffix).

How can I do this in Powershell?

答:
You can timestamp pings wth a foreach() loop; Get-Date can take a format string:

```<code>C:\> powershell
PS C:\> ping.exe -t 4.2.2.2 | Foreach{"{0} - {1}" -f (Get-Date -f "yyyyMMdd HH:mm:ss"),$_}
20190601 14:33:03 -
20190601 14:33:03 - Pinging 4.2.2.2 with 32 bytes of data:
20190601 14:33:03 - Reply from 4.2.2.2: bytes=32 time=70ms TTL=123
20190601 14:33:04 - Reply from 4.2.2.2: bytes=32 time=71ms TTL=123
20190601 14:33:05 - Reply from 4.2.2.2: bytes=32 time=70ms TTL=123
</code>```

Body:
You can timestamp pings wth a foreach() loop; Get-Date can take a format string:

C:\> powershell
PS C:\> ping.exe -t 4.2.2.2 | Foreach{"{0} - {1}" -f (Get-Date -f "yyyyMMdd HH:mm:ss"),$_}
20190601 14:33:03 -
20190601 14:33:03 - Pinging 4.2.2.2 with 32 bytes of data:
20190601 14:33:03 - Reply from 4.2.2.2: bytes=32 time=70ms TTL=123
20190601 14:33:04 - Reply from 4.2.2.2: bytes=32 time=71ms TTL=123
20190601 14:33:05 - Reply from 4.2.2.2: bytes=32 time=70ms TTL=123


问:
not working converting date factor to datetime
I imported txt file that has date in it and is has this format 1/25/2019 2:15:19 PM. How do I convert it to numeric date as 1-25-2019 2:15:19

I used

```<code>transform(date_loaded=as.POSIXct(date_loaded, format="%d/%m/%Y T %H:%M:%S"))
</code>```

答:
Use %I for the hour and %p for the AM/PM as shown.  This is vectorized and no packages are used.

```<code>as.POSIXct(factor("1/25/2019 2:15:19 PM"), format = "%m/%d/%Y %I:%M:%S %p")
## [1] "2019-01-25 14:15:19 EST"
</code>```

See ?strptime for more information.

Body:
I imported txt file that has date in it and is has this format 1/25/2019 2:15:19 PM. How do I convert it to numeric date as 1-25-2019 2:15:19

I used

transform(date_loaded=as.POSIXct(date_loaded, format="%d/%m/%Y T %H:%M:%S"))

Body:
Use %I for the hour and %p for the AM/PM as shown.  This is vectorized and no packages are used.

as.POSIXct(factor("1/25/2019 2:15:19 PM"), format = "%m/%d/%Y %I:%M:%S %p")
## [1] "2019-01-25 14:15:19 EST"

See ?strptime for more information.


问:
Trying to train a network outputs: Negative dimension size caused by subtracting 2 from 1 for max_pooling2d
Trying to train a convolutional neural network on a sample dataset with shape (256, 256, 3) gives me a ValueError.

I've checked the shape of my data (it's already in channels last, like tensorflow wants it). I've tried using the same code as other people but it doesn't work. I've gone through my dataset to see if the format of the data was correct, and I didn't seem to find any errors.

The code for my CNN is the following:

```<code>X = pickle.load(open("X.pickle", "rb")) # Shape (256, 256, 3)
y = pickle.load(open("y.pickle", "rb")) # The labels

X = X / 255.0 # Normalizing the data

model = Sequential()
model.add(Conv2D(64, (3,3), input_shape=(256, 256, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))

model.add(Dense(1))
model.add(Activation("sigmoid"))

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

model.fit(X, y, batch_size=32, validation_split=0.1)
</code>```

I expected the network to run smoothly, but it outputed the following (not gonna post the whole error log because it's too long):

```<code>File "neuralnet.py", line 18, in <module>
    model.add(MaxPooling2D(pool_size=(2,2)))

ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,64,128,1].
</code>```

Edit
Posting my keras.json file:

```<code>{
    "epsilon": 1e-07,
    "floatx": "float32",
    "image_data_format": "channels_last",
    "backend": "tensorflow"
}
</code>```

It previously was on data_format channels_first and backend theano. I've changed that, but I have to say that I'm using the tensorflow implementation of Keras directly.

Changing to channels_last and backend tensorflow has changed the output of the console, now it gives this error on the model.fit line:

```<code>ValueError: You are passing a target array of shape (8118, 1) while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:
```
from keras.utils import to_categorical
y_binary = to_categorical(y_int)
```

Alternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets.
</code>```

答:
To solve your last problem, you have this solution.

First, change the loss function to "binary_crossentropy" instead of "categorical_crossentropy". (since you have two classes I assume, with the sigmoid activation), provided that your data is one-hot encoded.

If you do not want to one-hot-encode your data (this is to transform 0 and 1 into [1,0] and [0,1]), you may use "sparse_categorical_crossentropy", just like the error suggests.

Body:
Trying to train a convolutional neural network on a sample dataset with shape (256, 256, 3) gives me a ValueError.

I've checked the shape of my data (it's already in channels last, like tensorflow wants it). I've tried using the same code as other people but it doesn't work. I've gone through my dataset to see if the format of the data was correct, and I didn't seem to find any errors.

The code for my CNN is the following:

X = pickle.load(open("X.pickle", "rb")) # Shape (256, 256, 3)
y = pickle.load(open("y.pickle", "rb")) # The labels

X = X / 255.0 # Normalizing the data

model = Sequential()
model.add(Conv2D(64, (3,3), input_shape=(256, 256, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))

model.add(Dense(1))
model.add(Activation("sigmoid"))

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

model.fit(X, y, batch_size=32, validation_split=0.1)

I expected the network to run smoothly, but it outputed the following (not gonna post the whole error log because it's too long):

File "neuralnet.py", line 18, in <module>
    model.add(MaxPooling2D(pool_size=(2,2)))

ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,64,128,1].

Edit
Posting my keras.json file:

{
    "epsilon": 1e-07,
    "floatx": "float32",
    "image_data_format": "channels_last",
    "backend": "tensorflow"
}

It previously was on data_format channels_first and backend theano. I've changed that, but I have to say that I'm using the tensorflow implementation of Keras directly.

Changing to channels_last and backend tensorflow has changed the output of the console, now it gives this error on the model.fit line:

ValueError: You are passing a target array of shape (8118, 1) while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:
```
from keras.utils import to_categorical
y_binary = to_categorical(y_int)
```

Alternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets.


问:
Delphi Library Memory Manager Strange
I got an error from DLL that compiled from Delphi using in c++ run in multithread

Delphi (Architect 10.3 Version 26.0.32429.4364) Library Code

```<code>library Project1;

uses
  System.SysUtils,
  System.Classes;

{$R *.res}

procedure __test(size: integer); cdecl;
var
  data : AnsiString;
begin
  SetLength(data, size);
end;

exports
  __test;

begin
end.
</code>```

C++ (Viausl Studio 2019) Load Library And Using Multithread

```<code>// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <Windows.h>
#include <thread>

typedef void(__cdecl *functest)(int);

HINSTANCE hInst = nullptr;

functest test;

void thread_loop() {
    while (1) {
        test(10);
    }
}

int main()
{
    hInst = LoadLibraryA("Project1.dll");

    if (!hInst) {
        return 0;
    }

    test = (functest)GetProcAddress(hInst, "__test");

    if (!test) {
        return 0;
    }

    std::thread t1(thread_loop);
    std::thread t2(thread_loop);

    return 1;
</code>```

I got an exception but it should not get any exception because that is procedure variable which was not shared

答:
Set IsMultiThread to True in your Delphi DLL's main block. Delphi's default memory manager assumes single-threaded mode by default.

```<code>begin
  IsMultiThread := True;
end.
</code>```

Title: Delphi Library Memory Manager Strange

Body:
I got an error from DLL that compiled from Delphi using in c++ run in multithread

Delphi (Architect 10.3 Version 26.0.32429.4364) Library Code

library Project1;

uses
  System.SysUtils,
  System.Classes;

{$R *.res}

procedure __test(size: integer); cdecl;
var
  data : AnsiString;
begin
  SetLength(data, size);
end;

exports
  __test;

begin
end.

C++ (Viausl Studio 2019) Load Library And Using Multithread

// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <Windows.h>
#include <thread>

typedef void(__cdecl *functest)(int);

HINSTANCE hInst = nullptr;

functest test;

void thread_loop() {
    while (1) {
        test(10);
    }
}

int main()
{
    hInst = LoadLibraryA("Project1.dll");

    if (!hInst) {
        return 0;
    }

    test = (functest)GetProcAddress(hInst, "__test");

    if (!test) {
        return 0;
    }

    std::thread t1(thread_loop);
    std::thread t2(thread_loop);

    return 1;

I got an exception but it should not get any exception because that is procedure variable which was not shared

Body:
Set IsMultiThread to True in your Delphi DLL's main block. Delphi's default memory manager assumes single-threaded mode by default.

begin
  IsMultiThread := True;
end.


问:
Array of pointers - memory allocation
I'm new into array of pointers (putting functions into array) and allocating memory for it using malloc. Can you help me with this piece of code? Have functions: int comp_int(int a, int b); int comp_int_abs(int a, int b); int comp_int_length(int a, int b); int comp_int_digits_sum(int a, int b);
and would like to put pointers to these functions in array of pointers. Firstly would like to dynamically allocate memory for the array and put functions' pointers into it. Stuck in this place, what am I doing wrong?

```<code>int (**funcs)(int, int) = malloc(4*sizeof(int));

if(!*funcs)
{
    printf("Failed to allocate memory");
    return 8;
}

*funcs={add_int, sub_int, div_int, mul_int};
</code>```

答:
First off, why allocate dynamic memory?

If you use a normal array, things get a bit simpler:

```<code>int (*funcs[])(int, int) = {
    comp_int,
    comp_int_abs,
    comp_int_length,
    comp_int_digits_sum,
};
</code>```

If you want to use dynamic allocation, there are a few things to look out for.

```<code>int (**funcs)(int, int) = malloc(4 * sizeof *funcs);
</code>```

First we need to allocate the right amount of memory. By multiplying with the size of the dereferenced pointer, we don't have to worry about the element type of the dynamic array. (But if we wanted to write the type manually, it would be sizeof (int (*)(int, int)), not sizeof (int) as in your code; the elements of our array are pointers to functions, not integers.)

Then we check for allocation failure:

```<code>if (!funcs) {
</code>```

Note: We check the pointer itself (funcs), not the first element of the dynamic array (which may not exist!) as in your code (*funcs). If malloc fails and returns NULL, then !*funcs will try to dereference a null pointer, which will most likely crash your program.

```<code>    fprintf(stderr, "Failed to allocate memory\n");
</code>```

Error messages go to stderr, not stdout. Lines are terminated by '\n'.

```<code>    return 8;
}
</code>```

Since we don't have a real array here, we can't use initialization syntax. In particular, = { is not valid in assignment expressions.

The most straightforward solution is to assign the elements manually:

```<code>funcs[0] = comp_int;
funcs[1] = comp_int_abs;
funcs[2] = comp_int_length;
funcs[3] = comp_int_digits_sum;
</code>```

It's a bit error prone because we have to specify every index manually. However, we can combine this with the "normal array" code from above:

```<code>int (*const funcs_init[])(int, int) = {
    comp_int,
    comp_int_abs,
    comp_int_length,
    comp_int_digits_sum,
};

int (**funcs)(int, int) = malloc(sizeof funcs_init);
if (!funcs) { ... }

memcpy(funcs, funcs_init, sizeof funcs_init);
</code>```

We just initialize our array as usual (here called funcs_init), then copy the contents into our dynamically allocated memory using memcpy.

Title: Array of pointers - memory allocation

Body:
I'm new into array of pointers (putting functions into array) and allocating memory for it using malloc. Can you help me with this piece of code? Have functions: int comp_int(int a, int b); int comp_int_abs(int a, int b); int comp_int_length(int a, int b); int comp_int_digits_sum(int a, int b);
and would like to put pointers to these functions in array of pointers. Firstly would like to dynamically allocate memory for the array and put functions' pointers into it. Stuck in this place, what am I doing wrong?

int (**funcs)(int, int) = malloc(4*sizeof(int));

if(!*funcs)
{
    printf("Failed to allocate memory");
    return 8;
}

*funcs={add_int, sub_int, div_int, mul_int};

Body:
First off, why allocate dynamic memory?

If you use a normal array, things get a bit simpler:

int (*funcs[])(int, int) = {
    comp_int,
    comp_int_abs,
    comp_int_length,
    comp_int_digits_sum,
};

If you want to use dynamic allocation, there are a few things to look out for.

int (**funcs)(int, int) = malloc(4 * sizeof *funcs);

First we need to allocate the right amount of memory. By multiplying with the size of the dereferenced pointer, we don't have to worry about the element type of the dynamic array. (But if we wanted to write the type manually, it would be sizeof (int (*)(int, int)), not sizeof (int) as in your code; the elements of our array are pointers to functions, not integers.)

Then we check for allocation failure:

if (!funcs) {

Note: We check the pointer itself (funcs), not the first element of the dynamic array (which may not exist!) as in your code (*funcs). If malloc fails and returns NULL, then !*funcs will try to dereference a null pointer, which will most likely crash your program.

    fprintf(stderr, "Failed to allocate memory\n");

Error messages go to stderr, not stdout. Lines are terminated by '\n'.

    return 8;
}

Since we don't have a real array here, we can't use initialization syntax. In particular, = { is not valid in assignment expressions.

The most straightforward solution is to assign the elements manually:

funcs[0] = comp_int;
funcs[1] = comp_int_abs;
funcs[2] = comp_int_length;
funcs[3] = comp_int_digits_sum;

It's a bit error prone because we have to specify every index manually. However, we can combine this with the "normal array" code from above:

int (*const funcs_init[])(int, int) = {
    comp_int,
    comp_int_abs,
    comp_int_length,
    comp_int_digits_sum,
};

int (**funcs)(int, int) = malloc(sizeof funcs_init);
if (!funcs) { ... }

memcpy(funcs, funcs_init, sizeof funcs_init);

We just initialize our array as usual (here called funcs_init), then copy the contents into our dynamically allocated memory using memcpy.