问:
Content Alignment For Custom Control
I'm writing my own library of controls. I'm working on the check box control and one of the final things that I need help on is drawing the check box in relation to the text. I have a ContentAlignment property that can change where the text appears in the control, but I'm not sure how to adjust the check box in relation to that because I don't know how to get the location of the text in the control.

```<code>    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics canvas = e.Graphics;
        canvas.SmoothingMode = SmoothingMode.HighQuality;
        int x = 0;
        int y = (int)(canvas.MeasureString(this.Text, this.Font).Height - 12) / 2;
        switch (this.Style)
        {
            case E.CheckBoxStyle.Check:
                canvas.DrawRectangle(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                    canvas.DrawString("√", new Font("serif", 7f, FontStyle.Bold), Brushes.Black, 1f, 3f);
                break;
            case E.CheckBoxStyle.Round:
                canvas.DrawEllipse(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                {
                    Rectangle region = new Rectangle(x + 1, y + 1, 10, 10);
                    canvas.FillEllipse(Functions.CreateGradient(region, this.FillColor, 90), region);
                }
                break;
            case E.CheckBoxStyle.Square:
                canvas.DrawRectangle(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                {
                    Rectangle region = new Rectangle(x + 1, y + 1, 10, 10);
                    canvas.FillRectangle(Functions.CreateGradient(region, this.FillColor, 90), region);
                }
                break;
        }
        if (!this.AutomaticSize)
        {
            StringFormat format = new StringFormat();
            switch (this.Alignment)
            {
                case ContentAlignment.TopRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.TopLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.TopCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.MiddleLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.MiddleCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.BottomRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Far;
                    break;
                case ContentAlignment.BottomLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Far;
                    break;
                case ContentAlignment.BottomCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Far;
                    break;
            }
            canvas.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), ClientRectangle, format);
        }
        else
        {
            canvas.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), 14f, 0f);
            Size newSize = Size.Round(canvas.MeasureString(this.Text, this.Font));
            this.Size = new Size(newSize.Width + 14, newSize.Height);
        }
    }
</code>```

One solution is to take away the property completely, I suppose. But that's not ideal. Another, I thought make a rectangle that contains the check box as well as the text and to move that rectangle accordingly but I don't know how to implement that. Thanks for any help! Here's a picture that might help show the problem:

答:
Instead of any of the excessive code used for the switch statement you can use this extension I wrote:

```<code>public static Point AlignDrawingPoint(this Graphics g, Size objectSize, Rectangle clientRectangle, ContentAlignment alignment)
{
    int margin = 4;
    Point center = new Point((clientRectangle.Width >> 1) - (objectSize.Width >> 1), (clientRectangle.Height >> 1) - (objectSize.Height >> 1));
    int rightMargin = clientRectangle.Width - (objectSize.Width + margin);
    int bottomMargin = clientRectangle.Height - (objectSize.Height + margin);
    Point p = Point.Empty;
    switch (alignment)
    {
        case ContentAlignment.TopLeft:
            p = new Point(margin, margin);
            break;
        case ContentAlignment.TopCenter:
            p = new Point(center.X, margin);
            break;
        case ContentAlignment.TopRight:
            p = new Point(rightMargin, margin);
            break;
        case ContentAlignment.MiddleLeft:
            p = new Point(margin, center.Y);
            break;
        case ContentAlignment.MiddleCenter:
            p = new Point(center.X, center.Y);
            break;
        case ContentAlignment.MiddleRight:
            p = new Point(rightMargin, center.Y);
            break;
        case ContentAlignment.BottomLeft:
            p = new Point(margin, bottomMargin);
            break;
        case ContentAlignment.BottomCenter:
            p = new Point(center.X, bottomMargin);
            break;
        case ContentAlignment.BottomRight:
            p = new Point(rightMargin, bottomMargin);
            break;
    }
    p.Offset(clientRectangle.X, clientRectangle.Y);
    return p;
}
</code>```

You can use this extension not just for drawing strings, you can use this extension when needing to align anything you need to draw within a rectangle.

But in your case you would do something like this:

```<code>g.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), AlignDrawingPoint(g.MeasureString(this.Text, this.Font).ToSize(), this.ClientRectangle, this.TextAlign));
</code>```

Title: Content Alignment For Custom Control

Body:
I'm writing my own library of controls. I'm working on the check box control and one of the final things that I need help on is drawing the check box in relation to the text. I have a ContentAlignment property that can change where the text appears in the control, but I'm not sure how to adjust the check box in relation to that because I don't know how to get the location of the text in the control.

    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics canvas = e.Graphics;
        canvas.SmoothingMode = SmoothingMode.HighQuality;
        int x = 0;
        int y = (int)(canvas.MeasureString(this.Text, this.Font).Height - 12) / 2;
        switch (this.Style)
        {
            case E.CheckBoxStyle.Check:
                canvas.DrawRectangle(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                    canvas.DrawString("√", new Font("serif", 7f, FontStyle.Bold), Brushes.Black, 1f, 3f);
                break;
            case E.CheckBoxStyle.Round:
                canvas.DrawEllipse(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                {
                    Rectangle region = new Rectangle(x + 1, y + 1, 10, 10);
                    canvas.FillEllipse(Functions.CreateGradient(region, this.FillColor, 90), region);
                }
                break;
            case E.CheckBoxStyle.Square:
                canvas.DrawRectangle(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                {
                    Rectangle region = new Rectangle(x + 1, y + 1, 10, 10);
                    canvas.FillRectangle(Functions.CreateGradient(region, this.FillColor, 90), region);
                }
                break;
        }
        if (!this.AutomaticSize)
        {
            StringFormat format = new StringFormat();
            switch (this.Alignment)
            {
                case ContentAlignment.TopRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.TopLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.TopCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.MiddleLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.MiddleCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.BottomRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Far;
                    break;
                case ContentAlignment.BottomLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Far;
                    break;
                case ContentAlignment.BottomCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Far;
                    break;
            }
            canvas.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), ClientRectangle, format);
        }
        else
        {
            canvas.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), 14f, 0f);
            Size newSize = Size.Round(canvas.MeasureString(this.Text, this.Font));
            this.Size = new Size(newSize.Width + 14, newSize.Height);
        }
    }

One solution is to take away the property completely, I suppose. But that's not ideal. Another, I thought make a rectangle that contains the check box as well as the text and to move that rectangle accordingly but I don't know how to implement that. Thanks for any help! Here's a picture that might help show the problem:

Body:
Instead of any of the excessive code used for the switch statement you can use this extension I wrote:

public static Point AlignDrawingPoint(this Graphics g, Size objectSize, Rectangle clientRectangle, ContentAlignment alignment)
{
    int margin = 4;
    Point center = new Point((clientRectangle.Width >> 1) - (objectSize.Width >> 1), (clientRectangle.Height >> 1) - (objectSize.Height >> 1));
    int rightMargin = clientRectangle.Width - (objectSize.Width + margin);
    int bottomMargin = clientRectangle.Height - (objectSize.Height + margin);
    Point p = Point.Empty;
    switch (alignment)
    {
        case ContentAlignment.TopLeft:
            p = new Point(margin, margin);
            break;
        case ContentAlignment.TopCenter:
            p = new Point(center.X, margin);
            break;
        case ContentAlignment.TopRight:
            p = new Point(rightMargin, margin);
            break;
        case ContentAlignment.MiddleLeft:
            p = new Point(margin, center.Y);
            break;
        case ContentAlignment.MiddleCenter:
            p = new Point(center.X, center.Y);
            break;
        case ContentAlignment.MiddleRight:
            p = new Point(rightMargin, center.Y);
            break;
        case ContentAlignment.BottomLeft:
            p = new Point(margin, bottomMargin);
            break;
        case ContentAlignment.BottomCenter:
            p = new Point(center.X, bottomMargin);
            break;
        case ContentAlignment.BottomRight:
            p = new Point(rightMargin, bottomMargin);
            break;
    }
    p.Offset(clientRectangle.X, clientRectangle.Y);
    return p;
}

You can use this extension not just for drawing strings, you can use this extension when needing to align anything you need to draw within a rectangle.

But in your case you would do something like this:

g.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), AlignDrawingPoint(g.MeasureString(this.Text, this.Font).ToSize(), this.ClientRectangle, this.TextAlign));


来源: stackexchange

问:
How do I find my ftp credentials on my free wordpress site?
I want to download my files via filezilla and upload to github, but I cannot find my ftp credentials anywhere in the wordpress admin. I created the site on wordpress and have done nothing with hosting thus far.</p>

答:
Read https://en.support.wordpress.com/ftp-access/ at wordpress.com

We do not allow FTP (File Transfer Protocol) access to any
  WordPress.com blogs.

See the link above for alternatives to using FTP with .com sites.

Also, read https://en.support.wordpress.com/com-vs-org/ for the differences between .com and self-hosted .org sites. You may find you want to self-host a WordPress site in order to use more capabilities of WordPress beyond the free .com version.

ContentLicense: CC BY-SA 3.0


问:
Modal not popping up on link click
I need to pop up a modal dialog on clicking a link. I have scanned related questions and followed similar instructions,however, none of the solutions seem to work.
Picture below is how my page looks like. Clicking on "Update" should open a modal window.

Here is my EJS file.

<!DOCTYPE html>

  <meta charset="UTF8">

  <link href="javascripts/frontend.js">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
  <link href="/stylesheets/userlist.css" rel="stylesheet">
  <link href='//fonts.googleapis.com/css?family=Amatic SC' rel='stylesheet'>
  <link href='//fonts.googleapis.com/css?family=NTR' rel='stylesheet'>

  <title>Userlist</title>

FORM

      <form action="/users/add_user" class="form-horizontal" id="user_form" method="post" name="user_form">
        <fieldset>

            Name :

              <input class="form-control input-md" id="nameinput" name="name" onfocus="if (this.value=='Name') this.value='';" placeholder="Enter Username" type="text" value="Name">

            Age :

              <input class="form-control input-md" id="ageinput" name="age" placeholder="Enter Age" type="number">

              <button class="btn btn-success" id="singlebutton" type="submit">Add User</button>

        </fieldset>
      </form>

USERS

          <%for(var i=0; i<userlist.length; i++) {%>

                <button aria-label="Close" class="close" data-dismiss="modal" type="button">×</button>

Edit :

                HEY!!

                <button class="btn btn-default" data-dismiss="modal" type="button">Close</button> <button class="btn btn-primary" type="button">Save changes</button>

          <%= userlist[i].name %>:
            <%= userlist[i].age %> " href="#" id="delete" title="Delete this User">Delete || ">Update

        <%} %>

```

I am using bootstrap 3.2.0 and have included jquery before bootstrap.

答:
Please try to put the dependencies after the  tag and before the  like below example. the reason is jquery or javascripts must see the elements that you are targeting, so the hierarchy is elements first before javascript functionality.

```<code></body>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" type="text/javascript"></script>

<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript"></script>

</html>
</code>```

Title: Modal not popping up on link click

Body:
I need to pop up a modal dialog on clicking a link. I have scanned related questions and followed similar instructions,however, none of the solutions seem to work.
Picture below is how my page looks like. Clicking on "Update" should open a modal window.

Here is my EJS file.

<!DOCTYPE html>

  <meta charset="UTF8">

  <link href="javascripts/frontend.js">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
  <link href="/stylesheets/userlist.css" rel="stylesheet">
  <link href='//fonts.googleapis.com/css?family=Amatic SC' rel='stylesheet'>
  <link href='//fonts.googleapis.com/css?family=NTR' rel='stylesheet'>

  <title>Userlist</title>

FORM

      <form action="/users/add_user" class="form-horizontal" id="user_form" method="post" name="user_form">
        <fieldset>

            Name :

              <input class="form-control input-md" id="nameinput" name="name" onfocus="if (this.value=='Name') this.value='';" placeholder="Enter Username" type="text" value="Name">

            Age :

              <input class="form-control input-md" id="ageinput" name="age" placeholder="Enter Age" type="number">

              <button class="btn btn-success" id="singlebutton" type="submit">Add User</button>

        </fieldset>
      </form>

USERS

          <%for(var i=0; i<userlist.length; i++) {%>

                <button aria-label="Close" class="close" data-dismiss="modal" type="button">×</button>

Edit :

                HEY!!

                <button class="btn btn-default" data-dismiss="modal" type="button">Close</button> <button class="btn btn-primary" type="button">Save changes</button>

          <%= userlist[i].name %>:
            <%= userlist[i].age %> <a class="delete_user" data-id="<%= userlist[i]._id %>" href="#" id="delete" title="Delete this User">Delete || <a href="#openModal" class="update_user" data-target="#openModal" data-toggle="modal" id="update" title="Update user info"
                data-id="<%= userlist[i]._id %>">Update

        <%} %>

I am using bootstrap 3.2.0 and have included jquery before bootstrap.

Body:
Please try to put the dependencies after the </body> tag and before the </html> like below example. the reason is jquery or javascripts must see the elements that you are targeting, so the hierarchy is elements first before javascript functionality.

</body>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" type="text/javascript"></script>

<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript"></script>

</html>


问:
How to use *ngFor on a JSON data in Angular?
I am trying to create a dymanic table with rows and columns defined as a array and JSON object. I am able to build the column headers dynamically. But the rows are not getting rendered. I am coming from angularjs 1.x background and new to angular.

Please help we understand the problem. Here is the plunker https://plnkr.co/edit/BG22Z1videTlzU3SrjcT?p=preview

```<code><table class="table">
            <thead>
                <tr>
                    <th *ngFor="let column of columnNames">
                        {{column}}
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let userDate of userDateObj">
                    <td>{{userDate.name}}</td>
                    <td>{{patientData.dob}}</td>
                </tr>
            </tbody>
        </table>
</code>```

答: To use *ngFor that object needs to be an array. If it's not an array then you can use a pipe to convert into an array.</p>

Body:
I am trying to create a dymanic table with rows and columns defined as a array and JSON object. I am able to build the column headers dynamically. But the rows are not getting rendered. I am coming from angularjs 1.x background and new to angular.

Please help we understand the problem. Here is the plunker https://plnkr.co/edit/BG22Z1videTlzU3SrjcT?p=preview

                        {{column}}

                    {{userDate.name}}
                    {{patientData.dob}}


问:
condense an if/else if statement using logical operators with javascript
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

```<code>$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };
</code>```

答:
Given the updated code that the OP has provided, a single statement will now suffice for $scope.setOperand(), as follows:

```<code>$scope.setOperand = function (operandEntered) {
          $scope.operator
          ? $scope.rightOperand += operandEntered
          : $scope.leftOperand += operandEntered;
    };
</code>```

The simple ternary addresses the original concern of the OP; see deno here.

I was unable to get the "C" button to clear the display which may be due to the way things are configured at codepen.io where location.reload() is perhaps not permissible there.  So, I recoded that button, as follows:

```<code>$scope.setClear = function (a) {

          $scope.leftOperand = "";
          $scope.operator = "";
          $scope.rightOperand = "";
          $scope.answer = "";

    };
</code>```

See demo here.

Now the displays clears and without any wait for a page reload.  Another change I made is as follows:

```<code>if (answer % 1 !== 0)
</code>```

This ensures that only floating point values display as decimals.  Now 1 + 2 equals 3 instead of 3.00.  (Consulted this resource: How do I check that a number is float or integer?)

Body:
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };

Body:
Given the updated code that the OP has provided, a single statement will now suffice for $scope.setOperand(), as follows:

$scope.setOperand = function (operandEntered) {
          $scope.operator
          ? $scope.rightOperand += operandEntered
          : $scope.leftOperand += operandEntered;
    };

The simple ternary addresses the original concern of the OP; see deno here.

I was unable to get the "C" button to clear the display which may be due to the way things are configured at codepen.io where location.reload() is perhaps not permissible there.  So, I recoded that button, as follows:

$scope.setClear = function (a) {

          $scope.leftOperand = "";
          $scope.operator = "";
          $scope.rightOperand = "";
          $scope.answer = "";

    };

See demo here.

Now the displays clears and without any wait for a page reload.  Another change I made is as follows:

if (answer % 1 !== 0)

This ensures that only floating point values display as decimals.  Now 1 + 2 equals 3 instead of 3.00.  (Consulted this resource: How do I check that a number is float or integer?)


问:
Cannot add server glassfish 4.1.2 in netbeans 8.1
When trying to add Glassfish 4.1.2 server in Netbeans 8.1 IDE, I'm getting the following error message:

"Not a valid GlassFish Server installation"

JDK 1.7.0_67 on Windows XP used.

答:
Try the following:

Remove any existing GlassFish 4.1.2 instance.

Exit NetBeans.

Rename console-core:
cd glassfish412/glassfish/lib/install/applications/__admingui/WEB-INF/lib/
mv console-core-4.1.2.jar console-core-4.1.jar

Start NetBeans.

Add GlassFish 4.1.2 Server Instance back into NetBeans (detected as 4.1).

Rename console-core to its original name:
cd glassfish412/glassfish/lib/install/applications/__admingui/WEB-INF/lib/
mv console-core-4.1.jar console-core-4.1.2.jar


问:
Showing a UIAlertAction based on UNUserNotification iOS not working as expected
I have been at this for hours, and supposedly I have everything acting as it should be, but it is not calling my userNotificationCenter:(UNUserNotificationCenter *)center
      willPresentNotification:(UNNotification *)notification
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions options)) method when notification goes off within the app, nothing happens at all.

The app gives a notification as expected when not in the app, but nothing while in.

Here is my code, if you can see something I'm doing wrong, please tell me.

Class NotificationDelegate.h:

```<code>#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@interface NotificationDelegate : UNUserNotificationCenter <UNUserNotificationCenterDelegate>

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
   willPresentNotification:(UNNotification *)notification
     withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler;

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
     withCompletionHandler:(void (^)())completionHandler;

@end
</code>```

NotificationDelegate.m:

```<code>#import "NotificationDelegate.h"

@implementation NotificationDelegate

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
      willPresentNotification:(UNNotification *)notification
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    NSLog(@"User Info : %@",notification.request.content.userInfo);
    [self sendMessage:[UIApplication sharedApplication] message:notification.request.content];
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

- (void) sendMessage:(UIApplication *)application message:(UNNotificationContent *)content{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:content.title
                                                   message:content.body
                                                     preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Go Away!" style:UIAlertActionStyleDefault handler:nil];

    [ac addAction:action];

    dispatch_async(dispatch_get_main_queue(), ^{
        [application.keyWindow.rootViewController presentViewController:ac animated:YES completion:nil];
    });
}

//Called to let your app know which action was selected by the user for a given notification.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
        withCompletionHandler:(void(^)())completionHandler{
    NSLog(@"User Info : %@",response.notification.request.content.userInfo);
}

@end
</code>```

AppDelegate.h:

```<code>#import <UIKit/UIKit.h>
#import "NotificationDelegate.h"
@import UserNotifications;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UNUserNotificationCenter *center;

@property (strong, nonatomic) NotificationDelegate *ncdel;

@property (strong, nonatomic) UIWindow *window;

@end
</code>```

AppDelegate.m:

```<code>#import "AppDelegate.h"
@import UserNotifications;

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.center = [UNUserNotificationCenter currentNotificationCenter];
    self.center.delegate = self.ncdel;
    return YES;
}
</code>```

ViewController.m:

```<code>#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.pvHelper = [[PickerViewHelperViewController alloc] init];
    self.pickerView.dataSource = self.pvHelper;
    self.pickerView.delegate = self.pvHelper;
    self.pvHelper.answer = [NSNumber numberWithInteger:10];

}

- (void) requestPermission{
    UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge;
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:options
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!granted) {
                                  NSLog(@"Something went wrong");
                              }
                          }];
}

- (void) createNotification:(NSNumber *)time{
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Alarming, isn't it?" arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Listen to me my love" arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    content.badge = [NSNumber numberWithInteger:99];

    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:[time integerValue]
                                                                                repeats:NO];

    //Note: Calling addNotificationRequest with the same identifier string will replace the existing notification. If you want to schedule multiple requests use a different identifier each time.
    NSString *identifier = @"Alarm Triggered";
    UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:req withCompletionHandler:^(NSError * _Nullable error) {
        if(error != nil){
            NSLog(@"Something went wrong: %@", error);
        }
        else{
            NSLog(@"I have requested the Notification be made");
        }

    }];

}

- (IBAction)buttonTappedSetAlarm:(id)sender {
    [self requestPermission];

    [self createNotification: [[self pvHelper] answer]];
}
</code>```

It doesn't matter much to this but my single view app just has a picker for 10,20,30...60 seconds,minutes,hours, and I do the math to get the time for the requests.

So like I said, the request work outside the application as expected, but with the app in the foreground, nothing occurs, and it's really bothering me.

Any help would be greatly appreciated.

答:
I figured out how to do it.

I got rid of trying to implement the UNUserNotificationCenterDelegate in another class and just did it in my View Controller:

```<code>#import <UIKit/UIKit.h>
#import "PickerViewHelperViewController.h"
@import UserNotifications;

@interface ViewController : UIViewController <UNUserNotificationCenterDelegate>

@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;

@property (strong, nonatomic) PickerViewHelperViewController *pvHelper;

// Two methods needed to implement from the UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler;

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler;

@end
</code>```

and then just had the accompanying code within my .m file to present a local notification.

```<code>- (void) sendMessage:(UIApplication *)application title:(NSString *)title message:(NSString *)message{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:title
                                                                message:message
                                                         preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Go Away!" style:UIAlertActionStyleDefault handler:nil];

    [ac addAction:action];

    dispatch_async(dispatch_get_main_queue(), ^{
        [application.keyWindow.rootViewController presentViewController:ac animated:YES completion:^{
            application.applicationIconBadgeNumber = 0;
        }];
    });
}

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
      willPresentNotification:(UNNotification *)notification
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    NSLog(@"User Info : %@",notification.request.content.userInfo);
    [self sendMessage:[UIApplication sharedApplication] title:@"local notification within App" message:notification.request.content.body];
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionBadge);
}

//Called when a notification is delivered to a background app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
        withCompletionHandler:(void(^)())completionHandler{
    NSLog(@"User Info : %@",response.notification.request.content.userInfo);
    [self sendMessage:[UIApplication sharedApplication]
                title:@"I habe been opened from outside the App"
              message:response.notification.request.content.body];
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}
</code>```

my create notification and ask for permission methods above remained unchanged in the code.

This allowed for a local notification to appear within the app and for a notification to appear if the app was opened via the notification.

Body:
I have been at this for hours, and supposedly I have everything acting as it should be, but it is not calling my userNotificationCenter:(UNUserNotificationCenter *)center
      willPresentNotification:(UNNotification *)notification
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions options)) method when notification goes off within the app, nothing happens at all.

The app gives a notification as expected when not in the app, but nothing while in.

Here is my code, if you can see something I'm doing wrong, please tell me.

Class NotificationDelegate.h:

#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@interface NotificationDelegate : UNUserNotificationCenter <UNUserNotificationCenterDelegate>

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
   willPresentNotification:(UNNotification *)notification
     withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler;

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
     withCompletionHandler:(void (^)())completionHandler;

@end

NotificationDelegate.m:

#import "NotificationDelegate.h"

@implementation NotificationDelegate

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
      willPresentNotification:(UNNotification *)notification
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    NSLog(@"User Info : %@",notification.request.content.userInfo);
    [self sendMessage:[UIApplication sharedApplication] message:notification.request.content];
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

- (void) sendMessage:(UIApplication *)application message:(UNNotificationContent *)content{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:content.title
                                                   message:content.body
                                                     preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Go Away!" style:UIAlertActionStyleDefault handler:nil];

    [ac addAction:action];

    dispatch_async(dispatch_get_main_queue(), ^{
        [application.keyWindow.rootViewController presentViewController:ac animated:YES completion:nil];
    });
}

//Called to let your app know which action was selected by the user for a given notification.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
        withCompletionHandler:(void(^)())completionHandler{
    NSLog(@"User Info : %@",response.notification.request.content.userInfo);
}

@end

AppDelegate.h:

#import <UIKit/UIKit.h>
#import "NotificationDelegate.h"
@import UserNotifications;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UNUserNotificationCenter *center;

@property (strong, nonatomic) NotificationDelegate *ncdel;

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m:

#import "AppDelegate.h"
@import UserNotifications;

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.center = [UNUserNotificationCenter currentNotificationCenter];
    self.center.delegate = self.ncdel;
    return YES;
}

ViewController.m:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.pvHelper = [[PickerViewHelperViewController alloc] init];
    self.pickerView.dataSource = self.pvHelper;
    self.pickerView.delegate = self.pvHelper;
    self.pvHelper.answer = [NSNumber numberWithInteger:10];

}

- (void) requestPermission{
    UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge;
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:options
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!granted) {
                                  NSLog(@"Something went wrong");
                              }
                          }];
}

- (void) createNotification:(NSNumber *)time{
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Alarming, isn't it?" arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Listen to me my love" arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    content.badge = [NSNumber numberWithInteger:99];

    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:[time integerValue]
                                                                                repeats:NO];

    //Note: Calling addNotificationRequest with the same identifier string will replace the existing notification. If you want to schedule multiple requests use a different identifier each time.
    NSString *identifier = @"Alarm Triggered";
    UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:req withCompletionHandler:^(NSError * _Nullable error) {
        if(error != nil){
            NSLog(@"Something went wrong: %@", error);
        }
        else{
            NSLog(@"I have requested the Notification be made");
        }

    }];

}

- (IBAction)buttonTappedSetAlarm:(id)sender {
    [self requestPermission];

    [self createNotification: [[self pvHelper] answer]];
}

It doesn't matter much to this but my single view app just has a picker for 10,20,30...60 seconds,minutes,hours, and I do the math to get the time for the requests.

So like I said, the request work outside the application as expected, but with the app in the foreground, nothing occurs, and it's really bothering me.

Any help would be greatly appreciated.

Body:
I figured out how to do it.

I got rid of trying to implement the UNUserNotificationCenterDelegate in another class and just did it in my View Controller:

#import <UIKit/UIKit.h>
#import "PickerViewHelperViewController.h"
@import UserNotifications;

@interface ViewController : UIViewController <UNUserNotificationCenterDelegate>

@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;

@property (strong, nonatomic) PickerViewHelperViewController *pvHelper;

// Two methods needed to implement from the UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler;

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler;

@end

and then just had the accompanying code within my .m file to present a local notification.

- (void) sendMessage:(UIApplication *)application title:(NSString *)title message:(NSString *)message{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:title
                                                                message:message
                                                         preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Go Away!" style:UIAlertActionStyleDefault handler:nil];

    [ac addAction:action];

    dispatch_async(dispatch_get_main_queue(), ^{
        [application.keyWindow.rootViewController presentViewController:ac animated:YES completion:^{
            application.applicationIconBadgeNumber = 0;
        }];
    });
}

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
      willPresentNotification:(UNNotification *)notification
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    NSLog(@"User Info : %@",notification.request.content.userInfo);
    [self sendMessage:[UIApplication sharedApplication] title:@"local notification within App" message:notification.request.content.body];
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionBadge);
}

//Called when a notification is delivered to a background app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
        withCompletionHandler:(void(^)())completionHandler{
    NSLog(@"User Info : %@",response.notification.request.content.userInfo);
    [self sendMessage:[UIApplication sharedApplication]
                title:@"I habe been opened from outside the App"
              message:response.notification.request.content.body];
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

my create notification and ask for permission methods above remained unchanged in the code.

This allowed for a local notification to appear within the app and for a notification to appear if the app was opened via the notification.


问:
Identify hidden non-UTF8 encoded characters
I am working in postgreSQL database and I have text column which in various languages like russian, chineses, korean, english etc. Although our application handles these languages well, we are having a issue dealing with non-UTF-8 characters.

For example, if you see the image from notepad++ where I have done Encoding > Encode in UTF-8, it neatly shows all the non-recognizable characters.

However, we are facing issue marking such records as non-process-able in postgres. Something like a flag should also do but I am trying something like below but it flags the valid russian records as well whereas notepad++ explicitly shows the hidden/non-UTF-8 characters.

Notepad++

Weird thing about these characters are that they do not show up regular select query but when I convert them to "UTF-8", those show up like below.

Database

Tried something like this (below query) but it does not seem to work i.e give me the desired output. Expectation is to set a flag to such records which have invalid hidden HTML references but not lose the valid text like the valid russian sentence in the snapshot. Should be able to distinctly identify only such texts.

```<code>select text, text ~ '[^[:ascii:]]', text ~ '^[\x00-\x7F]*$'
from sample_data;
</code>```

Sample Data -

"Я не наркоман. Это у меня всегда, когда мне афигитительно. А если серьёзно, это интересно,…"

"Ya le dieron amor a la foto de instagram de mi #UberCALAVERITA?"

"Executive Admininstrative Assistant in Toronto, ON for a Group"

"Сегодня валютные стратеги BMO обновили прогнозы по основным валютам на ближайшие пять кварталов (на конец периода):  читать далее…"

"Flicitations  Gestion d'actifs pour 6 Trophes #FundGradeA+2016 de fonds communs de placement :"

答:
This answer might help you go back to fix problems. It doesn't directly help you to go forward in the direction you are asking about.

Looking at Flicitations and F\302\202licitations, the escapes look like octal, which is possibly a presentation choice of your "IDE" and/or the convert_to function. From octal, \302\202 is 0xC2 0x82, decoding as UTF-8 gives U+0082. In Unicode, that's a control character, in ISO 8859-1 it's a non-character, either might explain why some renderings make it invisible or take no space.

Now, Google tells me that Flicitations is almost like a French word,  Félicitations. So, perhaps there is a character set and encoding where é is encoded as 0x82. Wikipedia helps here—Indeed there is: IBM850, which has been used for some French text.

So, it seems that someone has mishandled the user's text, causing data loss. The fundamental rule of text encoding is that text bytes must be read with the same encoding they were written with. Don't guess; Ask, or reference a standard, specification, documentation, or convention. Maybe you can go back and find the misbehaving process/code—at least that would prevent future data loss.

"Dealing with non-UTF-8 characters": There aren't really any non-UTF-8 characters. UTF-8 is an encoding of the Unicode character set. There are areas with exceptions but, practically speaking, Unicode has all characters, and UTF-8 can encode them all. So, if you think there are non-UTF-8 characters, the writer is either non-compliant or the reader is using the wrong encoding.

Body:
I am working in postgreSQL database and I have text column which in various languages like russian, chineses, korean, english etc. Although our application handles these languages well, we are having a issue dealing with non-UTF-8 characters.

For example, if you see the image from notepad++ where I have done Encoding > Encode in UTF-8, it neatly shows all the non-recognizable characters.

However, we are facing issue marking such records as non-process-able in postgres. Something like a flag should also do but I am trying something like below but it flags the valid russian records as well whereas notepad++ explicitly shows the hidden/non-UTF-8 characters.

Notepad++

Weird thing about these characters are that they do not show up regular select query but when I convert them to "UTF-8", those show up like below.

Database

Tried something like this (below query) but it does not seem to work i.e give me the desired output. Expectation is to set a flag to such records which have invalid hidden HTML references but not lose the valid text like the valid russian sentence in the snapshot. Should be able to distinctly identify only such texts.

select text, text ~ '[^[:ascii:]]', text ~ '^[\x00-\x7F]*$'
from sample_data;

Sample Data -

"Я не наркоман. Это у меня всегда, когда мне афигитительно. А если серьёзно, это интересно,…"

"Ya le dieron amor a la foto de instagram de mi #UberCALAVERITA?"

"Executive Admininstrative Assistant in Toronto, ON for a Group"

"Сегодня валютные стратеги BMO обновили прогнозы по основным валютам на ближайшие пять кварталов (на конец периода):  читать далее…"

"Flicitations  Gestion d'actifs pour 6 Trophes #FundGradeA+2016 de fonds communs de placement :"


问:
EXC_BAD_INSTRUCTION at performSelector
I have this code:

```<code>dispatch_async(dispatch_get_main_queue(), ^(void)
{
    SEL selector = @selector(callback:);
    [self.delegate performSelector:selector withObject:self];
});
</code>```

Both self.delegate and self is not nil.

I am getting EXC_BAD_INSTRUCTION at the performSelector line.

Any idea?

答:
I had the issue in Xcode 9 debugging calls to UI from outside Main Thread. I was simply trying to run blocking code from main thread.. while already on main thread!

Solution was to use this method (of course declaring as __block) all variables I needed to modify from the main thread (in my case just getting UIView width).

Of course if you need something async, just change dispatch_sync to dispatch_async

```<code>`
+ (void)runOnMainSafelyBlocking:(void(^)(void))block;
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}
`
</code>```

Title: EXC_BAD_INSTRUCTION at performSelector

Body:
I have this code:

dispatch_async(dispatch_get_main_queue(), ^(void)
{
    SEL selector = @selector(callback:);
    [self.delegate performSelector:selector withObject:self];
});

Both self.delegate and self is not nil.

I am getting EXC_BAD_INSTRUCTION at the performSelector line.

Any idea?

Body:
I had the issue in Xcode 9 debugging calls to UI from outside Main Thread. I was simply trying to run blocking code from main thread.. while already on main thread!

Solution was to use this method (of course declaring as __block) all variables I needed to modify from the main thread (in my case just getting UIView width).

Of course if you need something async, just change dispatch_sync to dispatch_async

`
+ (void)runOnMainSafelyBlocking:(void(^)(void))block;
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}
`


问:
PHP array to JavaScript array using json_encode()
How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.

JavaScript code:

```<code>$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });
</code>```

PHP code:

```<code><?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct
    //username and password
    $username = trim($_POST["user"]);

   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}
</code>```

答:
As has been mentioned, there are multiple options for passing the data from PHP:

add the Content-Type header with value application/json before sending the return from json_encode() to echo():

```<code>header('Content-Type: application/json');
echo json_encode($customer_array);
</code>```

Parse the return from the PHP using JSON.parse()

```<code>success:function(data){
    var y1=data;
    var data = JSON.parse(data);
</code>```

So pick one of those approaches. One might argue that the first is more semantically correct, since JSON data is being sent.

Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. However, the data returned should be an array of objects, each which has a property name. One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log().

```<code>data.forEach(function(dataItem) {
    console.log(dataItem.name);
});
</code>```

See a demonstration of this in this phpfiddle.

Body:
How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.

JavaScript code:

$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });

PHP code:

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct
    //username and password
    $username = trim($_POST["user"]);

   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}

Body:
As has been mentioned, there are multiple options for passing the data from PHP:

add the Content-Type header with value application/json before sending the return from json_encode() to echo():

header('Content-Type: application/json');
echo json_encode($customer_array);

Parse the return from the PHP using JSON.parse()

success:function(data){
    var y1=data;
    var data = JSON.parse(data);

So pick one of those approaches. One might argue that the first is more semantically correct, since JSON data is being sent.

Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. However, the data returned should be an array of objects, each which has a property name. One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log().

data.forEach(function(dataItem) {
    console.log(dataItem.name);
});

See a demonstration of this in this phpfiddle.


问:
How to use the java debug flag to look up parameters during compilation
I'm a noob and I was reading the spring reference documentation, specifically the section: constructor argument resolution

The documentation has a snippet in regards to dependency injection and defining your constructor-arg bean name:

```<code>package examples;

    public class ExampleBean {

        // Number of years to calculate the Ultimate Answer
        private int years;

        // The Answer to Life, the Universe, and Everything
        private String ultimateAnswer;

        public ExampleBean(int years, String ultimateAnswer) {
            this.years = years;
            this.ultimateAnswer = ultimateAnswer;
        }

    }
</code>```

```<code><bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>
</code>```

Keep in mind that to make this work out of the box your code must be compiled with the debug flag enabled so that Spring can look up the parameter name from the constructor. If you can’t compile your code with debug flag (or don’t want to) you can use @ConstructorProperties JDK annotation to explicitly name your constructor arguments.

I'm trying to understand how the compiler actually works and maybe a simple explanation.  For example:

How do the parameters become available during compile time if debug mode is enabled?  Does the compiler like put parameters in a special place in memory that spring can then access, or how does the process of obtaining parameters actually work?

Presumably debug mode enables this mechanism to obtain parameters based on ConstructorProperties.html i.e. Since parameter names are not in general available at runtime

But since they say "in general" makes me think sometimes they are available? Just looking for someone to explain this in a way that I might understand.

答:
Parameters names are not useful at runtime, unless you need them for some kind of reflection based binding (like spring does), but are useful during debugging, because you possibly want to inspect variables by name.

So, adding debugging information add those metadata to the class file. How springs achieve that is beyond my knowledge, but I think it might be based on bytecode tools (like ASM).

Spring uses bytecode manipulation tool to do some special injections.

Saying that in general this is so means that it depends on both the compiler and the runtime used. Since java 8 there is the -parameters flag to add params names to the class metadata.

I can also imagine that different compilers or pre/post compile processor could in fact add such information to the class files, but since the compiler spec do not require to do so they are in general not available.

Body:
I'm a noob and I was reading the spring reference documentation, specifically the section: constructor argument resolution

The documentation has a snippet in regards to dependency injection and defining your constructor-arg bean name:

package examples;

    public class ExampleBean {

        // Number of years to calculate the Ultimate Answer
        private int years;

        // The Answer to Life, the Universe, and Everything
        private String ultimateAnswer;

        public ExampleBean(int years, String ultimateAnswer) {
            this.years = years;
            this.ultimateAnswer = ultimateAnswer;
        }

    }

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>

Keep in mind that to make this work out of the box your code must be compiled with the debug flag enabled so that Spring can look up the parameter name from the constructor. If you can’t compile your code with debug flag (or don’t want to) you can use @ConstructorProperties JDK annotation to explicitly name your constructor arguments.

I'm trying to understand how the compiler actually works and maybe a simple explanation.  For example:

How do the parameters become available during compile time if debug mode is enabled?  Does the compiler like put parameters in a special place in memory that spring can then access, or how does the process of obtaining parameters actually work?

Presumably debug mode enables this mechanism to obtain parameters based on ConstructorProperties.html i.e. Since parameter names are not in general available at runtime

But since they say "in general" makes me think sometimes they are available? Just looking for someone to explain this in a way that I might understand.


问:
Using Enzyme simulate on custom events?
It is possible to use Enzyme's method .simulate() on custom events.
For Example:

```<code>// Code
<Element onFoo={someFunction}></Elements>

// Test
const element = shallow(<Element>);
element.simulate('foo');
</code>```

Is this the way custom events should be tested with Enzyme or is it a better approach to use s.th. like:

```<code>//Test
const element = shallow(<Element>);
element.props.onFoo()
</code>```

答:
What worked for me, trying to siumlate a custom event on a component that is not the top-level component was as follows:

```<code>const myComponent = enzymeWrapper.find('MyComponent');
myComponent.node.onThingSelected({}, { thing: newThing});
</code>```

Where myComponent is a React component, onThingSelected is the custom event handler exactly as named on the component, and newThing is an object of the type expected by the event handler.

Title: Using Enzyme simulate on custom events?

Body:
It is possible to use Enzyme's method .simulate() on custom events.
For Example:

// Code
<Element onFoo={someFunction}></Elements>

// Test
const element = shallow(<Element>);
element.simulate('foo');

Is this the way custom events should be tested with Enzyme or is it a better approach to use s.th. like:

//Test
const element = shallow(<Element>);
element.props.onFoo()

Body:
What worked for me, trying to siumlate a custom event on a component that is not the top-level component was as follows:

const myComponent = enzymeWrapper.find('MyComponent');
myComponent.node.onThingSelected({}, { thing: newThing});

Where myComponent is a React component, onThingSelected is the custom event handler exactly as named on the component, and newThing is an object of the type expected by the event handler.


问:
schema.graphql vs. buildSchema()
Following the Relay Modern documentation, first I started off by using the buildSchema() function and placing my schema and rootValue in JavaScript file and use it whenever needed.

Later I found out that relay-compiler needs a schema file either in JSON or .graphql format; So I copied my schema in schema.graphql and everything works as expected.

To avoid maintaining my schema in two places I can read the schema.graphql file and pass it to the buildSchema() function and it should work, but I was wondering if that's the correct approach or if there are better ways of doing it? Is there any way to avoid using buildSchema() function at all and totally rely on schema.graphql solely?

答:
This is the correct and required approach.

You can't avoid using the buildSchema function with your .graphql file ; but you could construct the full schema in JavaScript - see bottom of this page.

I recommend sticking with the Schema Language notation though.

Title: schema.graphql vs. buildSchema()


问:
tableGrob formatting
I have the following table in R (below in csv format). Since there are many of these and I need them formatted, I tried to use tableGrob to save a lot of time, yet I need the output in a very specific format, including the Calibri font (also below).

"2015\nabril","2016\nabril","2017\nmarzo","2017\nabril"

"Pedidos",-23.3,-13.8,-26,-39

"Existencias",7.6,1.2,5.3,10.5

"Expectativas",30.7,32.7,28.7,24

"ICI",-0.1,5.9,-0.9,-8.5

"ICI Desest*",0.4,5.7,-3.2,-6.9

However, every time I try to edit the theme and print the table I get this error

```<code>library(gridExtra)
t1 <- ttheme_default(core=list(
       fg_params=list(fontface=c(rep("plain", 4), "bold.italic")),
       bg_params = list(fill=c(rep(c("grey95", "grey90"),
                               length.out=4), "#6BAED6"),
                    alpha = rep(c(1,0.5), each=5))
))

t  <- tableGrob(tabla_fin)
grid.table(t, theme = t1)
</code>```

Error in array(x, c(length(x), 1L), if (!is.null(names(x)))
  list(names(x),  :    dims [product 60] do not match the length of
  object [12]

I'd appreciate any help. Thank you!

答:
Here are some ideas that could be useful for solving your problem.

```<code>library(grid)
library(gridExtra)
library(gtable)

# Build table
tabla_fin <- rbind(
c("","2015\nabril","2016\nabril","2017\nmarzo","2017\nabril"),
c("Pedidos",-23.3,-13.8,-26,-39),
c("Existencias",7.6,1.2,5.3,10.5),
c("Expectativas",30.7,32.7,28.7,24),
c("ICI",-0.1,5.9,-0.9,-8.5),
c("ICI Desest*",0.4,5.7,-3.2,-6.9))

colnames(tabla_fin) <- tabla_fin[1,]
tabla_fin <- tabla_fin[-1,]

rownames(tabla_fin) <- tabla_fin[,1]
tabla_fin <- tabla_fin[,-1]

print(tabla_fin)

#              2015\nabril 2016\nabril 2017\nmarzo 2017\nabril
# Pedidos      "-23.3"     "-13.8"     "-26"       "-39"
# Existencias  "7.6"       "1.2"       "5.3"       "10.5"
# Expectativas "30.7"      "32.7"      "28.7"      "24"
# ICI          "-0.1"      "5.9"       "-0.9"      "-8.5"
# ICI Desest*  "0.4"       "5.7"       "-3.2"      "-6.9"

# Install Calibri font using the extrafont package
# read the help of font_install()
library(extrafont)
loadfonts(device="win")
# font_install()

# Theme for text tables
t1 <- ttheme_default(
        core=list(
         fg_params=list(fontface=rep("plain", 6), fontfamily="Calibri",
                      x=1, hjust=1),
         bg_params = list(
                     fill=c(rep("white",3),"grey80","grey90"),
                     col=c("white","white","white","grey80","grey90"),
                     alpha = rep(1,5))
        ),
        rowhead=list(
         fg_params=list(x=0, hjust=0, fontface="plain", fontfamily="Calibri"),
         bg_params = list(
                     fill=c("white",rep("white",3),"grey80","grey90"),
                     col=c("white","white","white","white","grey80","grey90"),
                     alpha = rep(1,5))
        ),
        colhead=list(
         fg_params=list(fontface="plain",fontfamily="Calibri"),
         bg_params = list(
                     fill="grey70",
                     col="grey70",
                     alpha = rep(1,5))
        )
)

# Create gtable containing text grobs
t  <- tableGrob(tabla_fin, theme=t1)

# Add horizontal and vertical lines
t <- gtable_add_grob(t,
        grobs = segmentsGrob( # line across the bottom
            x0 = unit(0,"npc"),
            y0 = unit(0,"npc"),
            x1 = unit(1,"npc"),
            y1 = unit(0,"npc"),
            gp = gpar(lwd = 4.0)),
        t = 1, b = 1, l = 1, r = ncol(t))
t <- gtable_add_grob(t,
        grobs = segmentsGrob( # line across the bottom
            x0 = unit(0,"npc"),
            y0 = unit(0,"npc"),
            x1 = unit(1,"npc"),
            y1 = unit(0,"npc"),
            gp = gpar(lwd = 4.0)),
        t = 4, b = 4, l = 1, r = ncol(t))
t <- gtable_add_grob(t,
        grobs = segmentsGrob( # line across the bottom
            x0 = unit(0,"npc"),
            y0 = unit(0,"npc"),
            x1 = unit(0,"npc"),
            y1 = unit(1,"npc"),
            gp = gpar(lwd = 4.0)),
        t = 1, b = nrow(t), l = 4, r =4)

# Draw table
grid.newpage()
grid.draw(t)
</code>```

Here is the table:

Title: tableGrob formatting

Body:
I have the following table in R (below in csv format). Since there are many of these and I need them formatted, I tried to use tableGrob to save a lot of time, yet I need the output in a very specific format, including the Calibri font (also below).

"2015\nabril","2016\nabril","2017\nmarzo","2017\nabril"

"Pedidos",-23.3,-13.8,-26,-39

"Existencias",7.6,1.2,5.3,10.5

"Expectativas",30.7,32.7,28.7,24

"ICI",-0.1,5.9,-0.9,-8.5

"ICI Desest*",0.4,5.7,-3.2,-6.9

However, every time I try to edit the theme and print the table I get this error

library(gridExtra)
t1 <- ttheme_default(core=list(
       fg_params=list(fontface=c(rep("plain", 4), "bold.italic")),
       bg_params = list(fill=c(rep(c("grey95", "grey90"),
                               length.out=4), "#6BAED6"),
                    alpha = rep(c(1,0.5), each=5))
))

t  <- tableGrob(tabla_fin)
grid.table(t, theme = t1)

Error in array(x, c(length(x), 1L), if (!is.null(names(x)))
  list(names(x),  :    dims [product 60] do not match the length of
  object [12]

I'd appreciate any help. Thank you!

Body:
Here are some ideas that could be useful for solving your problem.

library(grid)
library(gridExtra)
library(gtable)

# Build table
tabla_fin <- rbind(
c("","2015\nabril","2016\nabril","2017\nmarzo","2017\nabril"),
c("Pedidos",-23.3,-13.8,-26,-39),
c("Existencias",7.6,1.2,5.3,10.5),
c("Expectativas",30.7,32.7,28.7,24),
c("ICI",-0.1,5.9,-0.9,-8.5),
c("ICI Desest*",0.4,5.7,-3.2,-6.9))

colnames(tabla_fin) <- tabla_fin[1,]
tabla_fin <- tabla_fin[-1,]

rownames(tabla_fin) <- tabla_fin[,1]
tabla_fin <- tabla_fin[,-1]

print(tabla_fin)

#              2015\nabril 2016\nabril 2017\nmarzo 2017\nabril
# Pedidos      "-23.3"     "-13.8"     "-26"       "-39"
# Existencias  "7.6"       "1.2"       "5.3"       "10.5"
# Expectativas "30.7"      "32.7"      "28.7"      "24"
# ICI          "-0.1"      "5.9"       "-0.9"      "-8.5"
# ICI Desest*  "0.4"       "5.7"       "-3.2"      "-6.9"

# Install Calibri font using the extrafont package
# read the help of font_install()
library(extrafont)
loadfonts(device="win")
# font_install()

# Theme for text tables
t1 <- ttheme_default(
        core=list(
         fg_params=list(fontface=rep("plain", 6), fontfamily="Calibri",
                      x=1, hjust=1),
         bg_params = list(
                     fill=c(rep("white",3),"grey80","grey90"),
                     col=c("white","white","white","grey80","grey90"),
                     alpha = rep(1,5))
        ),
        rowhead=list(
         fg_params=list(x=0, hjust=0, fontface="plain", fontfamily="Calibri"),
         bg_params = list(
                     fill=c("white",rep("white",3),"grey80","grey90"),
                     col=c("white","white","white","white","grey80","grey90"),
                     alpha = rep(1,5))
        ),
        colhead=list(
         fg_params=list(fontface="plain",fontfamily="Calibri"),
         bg_params = list(
                     fill="grey70",
                     col="grey70",
                     alpha = rep(1,5))
        )
)

# Create gtable containing text grobs
t  <- tableGrob(tabla_fin, theme=t1)

# Add horizontal and vertical lines
t <- gtable_add_grob(t,
        grobs = segmentsGrob( # line across the bottom
            x0 = unit(0,"npc"),
            y0 = unit(0,"npc"),
            x1 = unit(1,"npc"),
            y1 = unit(0,"npc"),
            gp = gpar(lwd = 4.0)),
        t = 1, b = 1, l = 1, r = ncol(t))
t <- gtable_add_grob(t,
        grobs = segmentsGrob( # line across the bottom
            x0 = unit(0,"npc"),
            y0 = unit(0,"npc"),
            x1 = unit(1,"npc"),
            y1 = unit(0,"npc"),
            gp = gpar(lwd = 4.0)),
        t = 4, b = 4, l = 1, r = ncol(t))
t <- gtable_add_grob(t,
        grobs = segmentsGrob( # line across the bottom
            x0 = unit(0,"npc"),
            y0 = unit(0,"npc"),
            x1 = unit(0,"npc"),
            y1 = unit(1,"npc"),
            gp = gpar(lwd = 4.0)),
        t = 1, b = nrow(t), l = 4, r =4)

# Draw table
grid.newpage()
grid.draw(t)

Here is the table:


问:
Expose ADA API to C/C++ ( the Scalable way )
Recently, I came across a safety critical system that uses only Ada. The system provides about 3 packages with about 200-300 functions in each package as source.

I need to access almost all of these function in another software system (very nice and neat) that is completely written in C/C++.

Goal: I need to expose these Ada functions to C/C++.

I understand I can use pragma Export() construct to export the functions and interfaces.C package to  convert parameters between C and Ada.

But, I was wondering if there's an easier or more scalable way to do this?

Maybe expose the complete package somehow?

Or develop an RPC Architecture?

Or use a tool that creates the C/C++ declarations and Type Conversions?

It would really help if somebody with similar experience could point me in the right direction.

Remember I am not looking for an Ada to C translator

答:
You could try adding the Export and Convention => X aspects to the package if you're using an Ada 2012 compiler; example:

```<code>Package K with Export, Convention => C_Plus_Plus is

    Function A( Input_1, Input_2 : Integer ) return Integer;

End K;
</code>```

This actually compiles, though since I don't have any C++ or C mixed-source projects to try this on I can't tell you if the results are strictly-speaking usable from the C++ side.

If that doesn't work, perhaps a better method would be to create a package especially for exporting the functions (and types) that will be used on the C++ side.

```<code>With
System,
Interfaces.C.Strings,
Interfaces.C.Pointers;

Package K with Convention => C_Plus_Plus is

    -------------
    --  TYPES  --
    -------------

    Type CPP_Window_Handle is Private;
    Subtype CPP_String is Interfaces.C.Strings.chars_ptr;

    --------------
    -- MODULES  --
    --------------

    Package UI_Module is
        Procedure Set_Title( Window : CPP_Window_Handle; Text : CPP_String )
        with Export;
    End UI_Module;

Private
    Package STUB_TYPES is
        Type Window is tagged null record;
    End STUB_TYPES;
    Use STUB_TYPES;

    Type CPP_Window_Handle is not null access Window'Class
    with Convention => C_Plus_Plus, Size => Interfaces.C.int'Size;

End K;
</code>```

Implemented as:

```<code>Package Body K is

    Package STUB_FUNCTIONS is
        Procedure Set_Window(Object : in out STUB_TYPES.Window'Class; Text : String) is null;
        --'
    End STUB_FUNCTIONS;

    Package Ada_Dependencies renames STUB_FUNCTIONS;

    Package Body UI_Module is
        Procedure Set_Title( Window : CPP_Window_Handle; Text : CPP_String ) is
            function Value (Item : CPP_String) return Interfaces.C.char_array
              renames Interfaces.C.Strings.Value;
            function Convert(Item     : Interfaces.C.char_array;
                             Trim_Nul : Boolean := True) return String
              renames Interfaces.C.To_Ada;
        Begin
            Ada_Dependencies.Set_Window(
              Object => Window.all,
              Text   => Convert( Value( Text ) )
          );
        End Set_Title;

    End UI_Module;

End K;
</code>```

Body:
You could try adding the Export and Convention => X aspects to the package if you're using an Ada 2012 compiler; example:

Package K with Export, Convention => C_Plus_Plus is

    Function A( Input_1, Input_2 : Integer ) return Integer;

End K;

This actually compiles, though since I don't have any C++ or C mixed-source projects to try this on I can't tell you if the results are strictly-speaking usable from the C++ side.

If that doesn't work, perhaps a better method would be to create a package especially for exporting the functions (and types) that will be used on the C++ side.

With
System,
Interfaces.C.Strings,
Interfaces.C.Pointers;

Package K with Convention => C_Plus_Plus is

    -------------
    --  TYPES  --
    -------------

    Type CPP_Window_Handle is Private;
    Subtype CPP_String is Interfaces.C.Strings.chars_ptr;

    --------------
    -- MODULES  --
    --------------

    Package UI_Module is
        Procedure Set_Title( Window : CPP_Window_Handle; Text : CPP_String )
        with Export;
    End UI_Module;

Private
    Package STUB_TYPES is
        Type Window is tagged null record;
    End STUB_TYPES;
    Use STUB_TYPES;

    Type CPP_Window_Handle is not null access Window'Class
    with Convention => C_Plus_Plus, Size => Interfaces.C.int'Size;

End K;

Implemented as:

Package Body K is

    Package STUB_FUNCTIONS is
        Procedure Set_Window(Object : in out STUB_TYPES.Window'Class; Text : String) is null;
        --'
    End STUB_FUNCTIONS;

    Package Ada_Dependencies renames STUB_FUNCTIONS;

    Package Body UI_Module is
        Procedure Set_Title( Window : CPP_Window_Handle; Text : CPP_String ) is
            function Value (Item : CPP_String) return Interfaces.C.char_array
              renames Interfaces.C.Strings.Value;
            function Convert(Item     : Interfaces.C.char_array;
                             Trim_Nul : Boolean := True) return String
              renames Interfaces.C.To_Ada;
        Begin
            Ada_Dependencies.Set_Window(
              Object => Window.all,
              Text   => Convert( Value( Text ) )
          );
        End Set_Title;

    End UI_Module;

End K;


问:
Send email using codeigniter on localhost
I am trying to create a send email form and my code keeps giving me the error message that the email is not being sent. This is my first time creating a form like this on codeigniter. Please help,

Here's my controller:

```<code>  <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contactus extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('email');
    }
    public function index(){
        $this->load->helper('url');

        $this->load->view('base');
        $this->load->view('contactUs');
    }
    public function send_mail(){
        //read parameters from $_POST using input class
        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $subject = $this->input->post('subject');
        $message = $this->input->post('yourMessage');

        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'your host',
            'smtp_port' => port for host,
            'smtp_user' => 'user@example.com',
            'smtp_pass' => 'yourpassword',
            'mailtype' => 'html',
            'charset' => 'iso-8859-1',
            'wordwrap' => TRUE
        );
        $this->load->library('email', $config);

        $this->email->set_newline("\r\n");

        $this->email->from($email, $name);
        $this->email->to('example@example.com');

        $this->email->subject($subject);
        $this->email->message($message);

        if ($this->email->send()){
            // mail sent
            $this->session->set_flashdata('msg','<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
            redirect('contactus/send_mail');
        }else{
            //error
            $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
            redirect('contactus/index');
        }
    }
}
</code>```

Here's my Html file:

```<code>    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/contact.css">
        <title>Contact Us</title>
    </head>
    <body>
        <h1><center>Contact Us</center></h1>
        <hr>
        <div class="container">
            <div id="home-search">
                <form action= "<?php echo site_url("contactus/send_mail"); ?>" method='POST'>
                    <div class="row">
                    <div class="col-md-8 col-md-offset-2">
                        <img src="http://oasissanjose.com/uploads/3/6/2/4/3624456/8429182_orig.png" class="pull-right" width="200" height="250">

                        <div class="panel panel-primary">
                            <h2 class="lead section-lead panel-heading">Questions, Concerns? Contact us using the email template below:</h2>
                            <h3 class="text-info panel-body"><center>All Fields are Mandatory</center></h3>
                            <div class="form-all">
                                    <div class="form-group">
                                        <label for="name">Full Name<span class="form-required">*</span></label>
                                        <input type="text" class="form-control" id="name" name="name" placeholder="Jane Doe" required/>
                                    </div>
                                    <div class="form-group">
                                        <label for="email">Email Address<span class="form-required">*</span></label>
                                        <input type="email" class="form-control" id="email" name="email" placeholder="jane.doe@example.com" required/>
                                    </div>
                                    <div class="form-group">
                                        <label for="subject">Subject<span class="form-required">*</span></label>
                                        <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required/>
                                    </div>
                                    <div class="form-group ">
                                        <label for="yourMessage">Your Message<span class="form-required">*</span></label>
                                        <textarea  class="form-control" id="yourMessage" name="yourMessage" placeholder="Message" required></textarea>
                                    </div>
                                    <input type="submit" class="btn btn-primary" name="submit" value="Send Message" >
                                <br>
                            </div>
                        </div>
                        <br><br>
                        <img src="http://content.presentermedia.com/files/animsp/00005000/5562/question_mark_serious_thinker_md_wm.gif" class="pull-right" width="400" height="250">
                    </div>
                </div>
                </form>
                <?php echo $this->session->flashdata('msg'); ?>
            </div>
        </div>
        <!-- End of Container -->
    </body>
</html>
</code>```

答:
For sending email on localhost using gmail smtp through xampp, edit your sendmail.ini to something like this

```<code>    smtp_server=smtp.gmail.com
    smtp_port=587
    smtp_ssl=tls

    auth_username=your_email@gmail.com
    auth_password=password_of_email

    force_sender=your_email@gmail.com
    hostname=smtp.gmail.com
</code>```

sendmail location : xampp/sendmail/sendmail.ini

also, change settings in your email to the Allowing less secure apps to access your account

Body:
I am trying to create a send email form and my code keeps giving me the error message that the email is not being sent. This is my first time creating a form like this on codeigniter. Please help,

Here's my controller:

  <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contactus extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('email');
    }
    public function index(){
        $this->load->helper('url');

        $this->load->view('base');
        $this->load->view('contactUs');
    }
    public function send_mail(){
        //read parameters from $_POST using input class
        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $subject = $this->input->post('subject');
        $message = $this->input->post('yourMessage');

        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'your host',
            'smtp_port' => port for host,
            'smtp_user' => 'user@example.com',
            'smtp_pass' => 'yourpassword',
            'mailtype' => 'html',
            'charset' => 'iso-8859-1',
            'wordwrap' => TRUE
        );
        $this->load->library('email', $config);

        $this->email->set_newline("\r\n");

        $this->email->from($email, $name);
        $this->email->to('example@example.com');

        $this->email->subject($subject);
        $this->email->message($message);

        if ($this->email->send()){
            // mail sent
            $this->session->set_flashdata('msg','
Your mail has been sent successfully!
');
            redirect('contactus/send_mail');
        }else{
            //error
            $this->session->set_flashdata('msg','
There is error in sending mail! Please try again later
');
            redirect('contactus/index');
        }
    }
}

Here's my Html file:

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/contact.css">
        <title>Contact Us</title>

Contact Us

                <form action= "<?php echo site_url("contactus/send_mail"); ?>" method='POST'>

Questions, Concerns? Contact us using the email template below:

All Fields are Mandatory

                                        Full Name*
                                        <input type="text" class="form-control" id="name" name="name" placeholder="Jane Doe" required/>

                                        Email Address*
                                        <input type="email" class="form-control" id="email" name="email" placeholder="jane.doe@example.com" required/>

                                        Subject*
                                        <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required/>

                                        Your Message*
                                        <textarea  class="form-control" id="yourMessage" name="yourMessage" placeholder="Message" required></textarea>

                                    <input type="submit" class="btn btn-primary" name="submit" value="Send Message" >

                </form>
                <?php echo $this->session->flashdata('msg'); ?>

Body:
For sending email on localhost using gmail smtp through xampp, edit your sendmail.ini to something like this

    smtp_server=smtp.gmail.com
    smtp_port=587
    smtp_ssl=tls

    auth_username=your_email@gmail.com
    auth_password=password_of_email

    force_sender=your_email@gmail.com
    hostname=smtp.gmail.com

sendmail location : xampp/sendmail/sendmail.ini

also, change settings in your email to the Allowing less secure apps to access your account


问:
Angular2 ng build not working properly
So i am using ng build in my angular2 project to create smaller folder size of my project called dist, but once i upload my project to my web host using file transfer protocol(Filezilla) it doesn't show my website. Is there some step i am still missing?</p>

答:
for prod build, you need to run </p>

```<code>ng build --prod --aot --base-href /name/
</code>```

Title: Angular2 ng build not working properly

Body:
for prod build, you need to run

ng build --prod --aot --base-href /name/


问:
HTTP DELETE with WebApi - passing a URL to the controller from javascript
My WebApi controller looks like this:

```<code>    [HttpDelete]
    [Route("api/eventMetadataByPath/{mediaPath}")]
    public HttpResponseMessage DeleteEventMetadataByPath(string mediaPath)
    {
          // do stuff
    }
</code>```

And my JS looks like this:

```<code>  eventService.sendRequest("DELETE", "eventMetadataByPath/" + mediaPath);
</code>```

With eventService doing the following:

```<code>  const options = { url: self.baseUrl + self.apiEndpoint + extension } // localhost/eventMedtadataByPath/google.com
  return $.ajax(options)
</code>```

How can I get the URL encoded as a URI parameter clientside so that the api controller can receive it?

答:
Assuming eventService is below.  jQuery is your game, your best bet is to read the jQuery.ajax documentation as it covers all of your HTTP Request Types.

So for DELETE, In your options object, you're going to add

```<code>var eventService = {
  sendRequest : function (parameterValueThatIsDelete, extension) {

  const options = {
    url: self.baseUrl + self.apiEndpoint + extension,
    type : parameterValueThatIsDelete
  }
  }
}
</code>```

Body:
My WebApi controller looks like this:

    [HttpDelete]
    [Route("api/eventMetadataByPath/{mediaPath}")]
    public HttpResponseMessage DeleteEventMetadataByPath(string mediaPath)
    {
          // do stuff
    }

And my JS looks like this:

  eventService.sendRequest("DELETE", "eventMetadataByPath/" + mediaPath);

With eventService doing the following:

  const options = { url: self.baseUrl + self.apiEndpoint + extension } // localhost/eventMedtadataByPath/google.com
  return $.ajax(options)

How can I get the URL encoded as a URI parameter clientside so that the api controller can receive it?

Body:
Assuming eventService is below.  jQuery is your game, your best bet is to read the jQuery.ajax documentation as it covers all of your HTTP Request Types.

So for DELETE, In your options object, you're going to add

var eventService = {
  sendRequest : function (parameterValueThatIsDelete, extension) {

  const options = {
    url: self.baseUrl + self.apiEndpoint + extension,
    type : parameterValueThatIsDelete
  }
  }
}


问:
Show modal optionally when commandButton clicked
I have a problem that I need to show a modal based on the value of the input field, so I write some value in the input field, click Save button, based on the value I should run db query, if result is present then show modal, otherwise not. What is the best approach?

A problem is that I need to have separate onclick, oncomplete events.

```<code> <p:commandButton id="save_button"
  value="Save"
  update="@([id*=modalId]) @form"
  onclick="jQuery('#modalId').show();"
  action="#{cc.attrs.saveAction}">
  </p:commandButton>

   <p:inputNumber required="true"
   value="#{bean.number}">
   </p:inputNumber>
</code>```

答:
You can set the db result in your backing bean and then change the .show() invocation to the oncomplete attribute, so you can conditionally show the modal panel depending on the query result.

```<code>public class BackingBean{
    private Object dbResult;

    public Object getDbResut(){ return dbResult; }

    public void executeDbQuery(){
          dbResult = yourDbApi.doSomeQuery();
    }
}

<p:commandButton id="save_button"
  value="Save"
  update="@([id*=modalId]) @form"
  actionListener="#{bean.executeDbQuery}">
  action="#{cc.attrs.saveAction}"
  ocomplete="#{not empty bean.dbResult ? 'jQuery('#modalId').show();' : ''}">
  </p:commandButton>

   <p:inputNumber required="true"
   value="#{bean.number}">
   </p:inputNumber>
</code>```

actionListener executes before action , so its garanteed that after your action call the oncomplete would take the correct bean.dbResult

Body:
You can set the db result in your backing bean and then change the .show() invocation to the oncomplete attribute, so you can conditionally show the modal panel depending on the query result.

public class BackingBean{
    private Object dbResult;

    public Object getDbResut(){ return dbResult; }

    public void executeDbQuery(){
          dbResult = yourDbApi.doSomeQuery();
    }
}

<p:commandButton id="save_button"
  value="Save"
  update="@([id*=modalId]) @form"
  actionListener="#{bean.executeDbQuery}">
  action="#{cc.attrs.saveAction}"
  ocomplete="#{not empty bean.dbResult ? 'jQuery('#modalId').show();' : ''}">
  </p:commandButton>

   <p:inputNumber required="true"
   value="#{bean.number}">
   </p:inputNumber>

actionListener executes before action , so its garanteed that after your action call the oncomplete would take the correct bean.dbResult


问:
Rem-Based Layouts, Zooming on chrome is inconsistent, PX vs REM
I've been wracking my brain over this one, google searches don't really have much in the way of help or even documentation of this problem but it's greatly affecting my current conversion to a mobile-friendly design.

Everywhere I go, everyone's touting using rem-based layouts as the new gold standard, and on the surface the virtues of this approach seem ideal (full accesibility support for both reference pixel based scaling and font-size scaling to support many DPIs and many screen sizes / settings).

However I've run into a rather large snag, I'm finding that Chrome (and possibly all webkit browsers but I don't have a mac atm to test) don't seem to scale the same as the rest.

With the initial setup like this:

```<code>html { font-size: 62.5%; }
body { font-size: 1.6rem; }
</code>```

We should be able to set up all our measurements using 1/10th the pixel size in rems:

```<code>.my-element { height: 15rem; } /* 150px */
</code>```

I've created a simple example that illustrates my problem here: https://jsfiddle.net/gLkpz88q/2/embedded/result/

When you use Chrome and you scale this way out, notice how the layout stops scaling but the content continues.

Compare this to Firefox, IE11, Edge and you don't see this behavior at all, they all scale uniformly and continually.

Here's (Top-Left: Chrome, Top-Right: IE11, Bottom-Left: Edge, Bottom-Right: FireFox) side-by-side:

As you can see this has some terrible implications for layouts if the rem unit scales differently than everything else.

I'm not certain how to proceed with this scenario as it seems like WebKit/Chrome have decided to handle scaling completely differently and this calls in to question all the scaling scenarios going forward.

There's a number of articles advocating just using pixels as the CSS Reference Pixel takes care of mobile scaling rather well:

Just Use Pixels

R.I.P. Rem, Viva CSS Reference Pixel!

However these tend to ignore the font-scaling issue, citing it as an unlikely situation.

I did a quick look around at man big mobile friendly/friendlyish sites I could think of from large & successful companies and it seems most of them just use pixels for all their layout needs. (Google, Facebook, Wordpress, Twitter, Bootstrap 3, [and to some extent Bootstrap 4], MDN, and WebPlatform)

Is Chrome the new Standards-Busting IE? Or am I doing something horribly wrong? I'm tempted to just use pixels at this point for consistency.

答:
That's because Chrome's behavior of setting a minimum font-size, so if you zoom-out, chrome will set the minimum font-size to 6px (12px for chinese and japanese version). So your div will have a minimum width as it depends on your base font-size (which can't be smaller then chrome's minimum).

See also:

Chrome will increase the font size when zooming out

[Edit] Additional Information:

Chromium Tickets & Discussions On this topic:

https://bugs.chromium.org/p/chromium/issues/detail?id=16875
https://bugs.chromium.org/p/chromium/issues/detail?id=36429

-webkit-text-size-adjust Support Dropped, so the viable solution for this behavior is not reliable anymore:

https://trac.webkit.org/changeset/145168/webkit

Body:
I've been wracking my brain over this one, google searches don't really have much in the way of help or even documentation of this problem but it's greatly affecting my current conversion to a mobile-friendly design.

Everywhere I go, everyone's touting using rem-based layouts as the new gold standard, and on the surface the virtues of this approach seem ideal (full accesibility support for both reference pixel based scaling and font-size scaling to support many DPIs and many screen sizes / settings).

However I've run into a rather large snag, I'm finding that Chrome (and possibly all webkit browsers but I don't have a mac atm to test) don't seem to scale the same as the rest.

With the initial setup like this:

html { font-size: 62.5%; }
body { font-size: 1.6rem; }

We should be able to set up all our measurements using 1/10th the pixel size in rems:

.my-element { height: 15rem; } /* 150px */

I've created a simple example that illustrates my problem here: https://jsfiddle.net/gLkpz88q/2/embedded/result/

When you use Chrome and you scale this way out, notice how the layout stops scaling but the content continues.

Compare this to Firefox, IE11, Edge and you don't see this behavior at all, they all scale uniformly and continually.

Here's (Top-Left: Chrome, Top-Right: IE11, Bottom-Left: Edge, Bottom-Right: FireFox) side-by-side:

As you can see this has some terrible implications for layouts if the rem unit scales differently than everything else.

I'm not certain how to proceed with this scenario as it seems like WebKit/Chrome have decided to handle scaling completely differently and this calls in to question all the scaling scenarios going forward.

There's a number of articles advocating just using pixels as the CSS Reference Pixel takes care of mobile scaling rather well:

Just Use Pixels

R.I.P. Rem, Viva CSS Reference Pixel!

However these tend to ignore the font-scaling issue, citing it as an unlikely situation.

I did a quick look around at man big mobile friendly/friendlyish sites I could think of from large & successful companies and it seems most of them just use pixels for all their layout needs. (Google, Facebook, Wordpress, Twitter, Bootstrap 3, [and to some extent Bootstrap 4], MDN, and WebPlatform)

Is Chrome the new Standards-Busting IE? Or am I doing something horribly wrong? I'm tempted to just use pixels at this point for consistency.