问:
My PHP code is not picking up the variables when using the mail function
My PHP code is not picking up the variables in $message, when $message is sent to an email address using the mail function the variables are missing. Not sure what I am doing wrong.

```<code>    <?php

    $to = 'test@email.com';
    $subject = 'Booking';

    $name = $_post['name'];
    $email = $_post['email'];
    $pickup = $_post['pickup'];
    $destination = $_post['destination'];

    $message = <<<Email
    Hi,
    Please pick up $name from $pickup and drop to $destination
    Email;

    $header = $email;

    mail($to, $subject, $message, $header);

    echo "Message Sent";

    ?>
</code>```

The html code is provided below, not sure why $_POST is not pulling through.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Sign Up</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <form action="form.php" method="POST">
        <fieldset>
            <legend>Book your Journey</legend>
            <label for ="name">Name:</label>
            <input type="text" id="name" name="name">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email">
            <label for="pickup"> Pick Up Location</label>
            <input type="text" id="pickup" name="pickup">
            <label>Time:</label>
            <select>
                <option>--HR--</option>
                <option value="1">01</option>
                <option value="2">02</option>
                <option value="3">03</option>
                <option value="4">04</option>
                <option value="5">05</option>
                <option value="6">06</option>
                <option value="7">07</option>
                <option value="8">08</option>
                <option value="9">09</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
            </select>
            <label>:</label>
            <select>
                <option>--MIN--</option>
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
            </select>
            <select>
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>
            </fieldset>
            <fieldset>
            <label for="destination"> Destination Postal Code</label>
            <input type="text" id="destination" name="destination">
        </fieldset>
        <button>Submit</button>
    </form>

</body>
</html>
</code>```

答:
The problem isn't necessarily that $message isn't picking up the variables. Rather, the problem is that $name, $email, etc. are all blank values.

PHP's variables are case sensitive, and $_POST should be all upper case.

You can do a test by outputting your $email, $name, etc. and you'll see that they're blank.

To fix it, all you need to do is capitalize $_POST:

```<code>$name = $_POST['name'];
$email = $_POST['email'];
$pickup = $_POST['pickup'];
$destination = $_POST['destination'];
</code>```

Body:
My PHP code is not picking up the variables in $message, when $message is sent to an email address using the mail function the variables are missing. Not sure what I am doing wrong.

    <?php

    $to = 'test@email.com';
    $subject = 'Booking';

    $name = $_post['name'];
    $email = $_post['email'];
    $pickup = $_post['pickup'];
    $destination = $_post['destination'];

    $message = <<<Email
    Hi,
    Please pick up $name from $pickup and drop to $destination
    Email;

    $header = $email;

    mail($to, $subject, $message, $header);

    echo "Message Sent";

    ?>

The html code is provided below, not sure why $_POST is not pulling through.

<!DOCTYPE html>

    <title>Sign Up</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <form action="form.php" method="POST">
        <fieldset>
            <legend>Book your Journey</legend>
            Name:
            <input type="text" id="name" name="name">
            Email:
            <input type="email" id="email" name="email">
             Pick Up Location
            <input type="text" id="pickup" name="pickup">
            Time:
            <select>
                <option>--HR--</option>
                <option value="1">01</option>
                <option value="2">02</option>
                <option value="3">03</option>
                <option value="4">04</option>
                <option value="5">05</option>
                <option value="6">06</option>
                <option value="7">07</option>
                <option value="8">08</option>
                <option value="9">09</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
            </select>
            :
            <select>
                <option>--MIN--</option>
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
            </select>
            <select>
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>
            </fieldset>
            <fieldset>
             Destination Postal Code
            <input type="text" id="destination" name="destination">
        </fieldset>
        <button>Submit</button>
    </form>

Body:
The problem isn't necessarily that $message isn't picking up the variables. Rather, the problem is that $name, $email, etc. are all blank values.

PHP's variables are case sensitive, and $_POST should be all upper case.

You can do a test by outputting your $email, $name, etc. and you'll see that they're blank.

To fix it, all you need to do is capitalize $_POST:

$name = $_POST['name'];
$email = $_POST['email'];
$pickup = $_POST['pickup'];
$destination = $_POST['destination'];


来源: stackexchange

问:
Unable to show video in camera roll after trimming
I'm developing video player in which I have trimming functionality. I am using ABVideoRangeSlider for that. Whenever I try to trim and save video I'm getting Error Domain=NSCocoaErrorDomain Code=-1 "(null)" this error.
Here is my code snippet

```<code>    let composition = AVMutableComposition()
    let track = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID:Int32(kCMPersistentTrackID_Invalid))

    try! track.insertTimeRange(CMTimeRangeMake(startTimeForCurrentSlice, endTimeForCurrentSlice), of: asset.tracks(withMediaType: AVMediaTypeVideo)[0] as AVAssetTrack, at: kCMTimeZero)
    var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0] as String
    let videoPathToSave = documentsDirectory.appending("mergeVideo-\(arc4random()%1000)-d.mp4")
    let videoURLToSave = NSURL(fileURLWithPath: videoPathToSave)

    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURLToSave as URL)
    }) { saved, error in
        if saved {
            let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertController.addAction(defaultAction)
            self.present(alertController, animated: true, completion: nil)
        } else {
            print("Error: \(String(describing: error!))")
        }
    }
</code>```

Any help will be appreciated.

答:
Before saving to camera roll You need to export your AVMutableComposition with AVAssetExportSession or with AVAssetWriter, and after that You can save it to camera roll.

Checkout this tutorial for AVAssetExportSession usage. For saving to camera roll it uses ALAssetsLibrary, but You can save it with Photos.

ContentLicense: CC BY-SA 3.0

Body:
I'm developing video player in which I have trimming functionality. I am using ABVideoRangeSlider for that. Whenever I try to trim and save video I'm getting Error Domain=NSCocoaErrorDomain Code=-1 "(null)" this error.
Here is my code snippet

    let composition = AVMutableComposition()
    let track = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID:Int32(kCMPersistentTrackID_Invalid))

    try! track.insertTimeRange(CMTimeRangeMake(startTimeForCurrentSlice, endTimeForCurrentSlice), of: asset.tracks(withMediaType: AVMediaTypeVideo)[0] as AVAssetTrack, at: kCMTimeZero)
    var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0] as String
    let videoPathToSave = documentsDirectory.appending("mergeVideo-\(arc4random()%1000)-d.mp4")
    let videoURLToSave = NSURL(fileURLWithPath: videoPathToSave)

    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURLToSave as URL)
    }) { saved, error in
        if saved {
            let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertController.addAction(defaultAction)
            self.present(alertController, animated: true, completion: nil)
        } else {
            print("Error: \(String(describing: error!))")
        }
    }

Any help will be appreciated.


问:
How to ignore values when using numpy.sum and numpy.mean in matrices
Is there a way to avoid using specific values when applying sum and mean in numpy?

I'd like to avoid, for instance, the -999 value when calculating the result.

```<code>In [14]: c = np.matrix([[4., 2.],[4., 1.]])

In [15]: d = np.matrix([[3., 2.],[4., -999.]])

In [16]: np.sum([c, d], axis=0)
Out[16]:
array([[   7.,    4.],
       [   8., -998.]])

In [17]: np.mean([c, d], axis=0)
Out[17]:
array([[   3.5,    2. ],
       [   4. , -499. ]])
</code>```

答:
One option is to replace the specific value with np.nan and then use numpy.nansum and numpy.nanmean as commented by @s.k:

```<code>import numpy as np
def nan_if(arr, value):
    return np.where(arr == value, np.nan, arr)

np.nansum([nan_if(c, -999), nan_if(d, -999)], axis=0)
#array([[ 7.,  4.],
#       [ 8.,  1.]])

np.nanmean([nan_if(c, -999), nan_if(d, -999)], axis=0)
#array([[ 3.5,  2. ],
#       [ 4. ,  1. ]])
</code>```

Body:
Is there a way to avoid using specific values when applying sum and mean in numpy?

I'd like to avoid, for instance, the -999 value when calculating the result.

In [14]: c = np.matrix([[4., 2.],[4., 1.]])

In [15]: d = np.matrix([[3., 2.],[4., -999.]])

In [16]: np.sum([c, d], axis=0)
Out[16]:
array([[   7.,    4.],
       [   8., -998.]])

In [17]: np.mean([c, d], axis=0)
Out[17]:
array([[   3.5,    2. ],
       [   4. , -499. ]])

Body:
One option is to replace the specific value with np.nan and then use numpy.nansum and numpy.nanmean as commented by @s.k:

import numpy as np
def nan_if(arr, value):
    return np.where(arr == value, np.nan, arr)

np.nansum([nan_if(c, -999), nan_if(d, -999)], axis=0)
#array([[ 7.,  4.],
#       [ 8.,  1.]])

np.nanmean([nan_if(c, -999), nan_if(d, -999)], axis=0)
#array([[ 3.5,  2. ],
#       [ 4. ,  1. ]])


问:
Tkinter disable Return key behaviour on function call
I need to print the widget contents after pressing Control+Return, but after I press it, it adds a new line. How do I disable the Enter key behaviour when calling the function?

```<code>from Tkinter import *

def test(event):
    a1 = e.get(1.0, END)
    print a1

root = Tk()
e = Text(root)
e.pack()
root.bind('<Control-Return>', test)
root.mainloop()
</code>```

return 'break' doesn't do what I want, as I saw in other questions.

I could get the cursor position and delete the new line created, but I think there's a better way.

Python 2.7

答:
Oh, I was binding to root, if I bind it to the text widget itself and add return 'break', it works as intended.

```<code>from Tkinter import *

def test(event):
    a1 = e.get(1.0, END)
    print a1
    return 'break'

root = Tk()
e = Text(root)
e.pack()
e.bind('<Control-Return>', test)
root.mainloop()
</code>```

Body:
I need to print the widget contents after pressing Control+Return, but after I press it, it adds a new line. How do I disable the Enter key behaviour when calling the function?

from Tkinter import *

def test(event):
    a1 = e.get(1.0, END)
    print a1

root = Tk()
e = Text(root)
e.pack()
root.bind('<Control-Return>', test)
root.mainloop()

return 'break' doesn't do what I want, as I saw in other questions.

I could get the cursor position and delete the new line created, but I think there's a better way.

Python 2.7

Body:
Oh, I was binding to root, if I bind it to the text widget itself and add return 'break', it works as intended.

from Tkinter import *

def test(event):
    a1 = e.get(1.0, END)
    print a1
    return 'break'

root = Tk()
e = Text(root)
e.pack()
e.bind('<Control-Return>', test)
root.mainloop()


问:
SDWebImage returning -1100
I am trying to fetch an image using SDWebImage but it is returning a -1100 error. I am not able to figure out why:

```<code>[eventImageView sd_setImageWithURL:[NSURL URLWithString:@"http://farm3.staticflickr.com/2350/2605722927_8cf675a249_b.jpg"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (error) {
                NSLog(@"error: %@", error.localizedDescription);
            }
        }];
</code>```

The error description:

The operation couldn’t be completed. (NSURLErrorDomain error -1100.)

答: Check app transport security settings, and try using an HTTPS URL. </p>

Title: SDWebImage returning -1100

Body:
I am trying to fetch an image using SDWebImage but it is returning a -1100 error. I am not able to figure out why:

[eventImageView sd_setImageWithURL:[NSURL URLWithString:@"http://farm3.staticflickr.com/2350/2605722927_8cf675a249_b.jpg"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (error) {
                NSLog(@"error: %@", error.localizedDescription);
            }
        }];

The error description:

The operation couldn’t be completed. (NSURLErrorDomain error -1100.)


问:
How to speed Meteor.js build times?
When I make a change to Javascript file and save it, it takes over 5 seconds to build and restart the development server even if it is simple 10 line example app. I am new to Meteor.js so I don't know if it's normal, but I though changes should appear instantly (about a second or two) on a browser? 5-6 seconds feels pretty long time for me.

Selecting package versions and downloading packages seem to take the major part of the time.

There is one websocket pending (Chrome Dev tools Network tab) when it's restarting. I'm using Meteor 1.0.

答:
This was my purely hardware solution to the problem of slow Meteor build times.

When I decided to get into development I was adamant that I wasn't going to run out and buy the latest and greatest in hardware until I actually knew how to code and knew what my requirements were in the long term.

So I went out and bought a used 15" Acer laptop; it had the following spec:

Memory: 6Gb RAM

Processor: Intel Pentium CPu 6200 @ 2.13GHz *2

OS: Ubuntu 16.04.1 LTS 32-bit

Storage: 153.5GB HDD

With this setup I saw rebuild times of between 15s ~ 30s (including the browser refresh) of a side project using Meteor 1.4, Reactand a Mongo db instance with around 1500 records. I found these times to be excruciatingly slow when it came to making multiple changes. You can see the initial version of the project I was working on herehere.

After trying to get work done in cafe's and libraries I realised that I was much happier working at home, and once the side project was complete I decided I would reward myself with an upgrade.

My initial choices were between a Macbook Pro and a gaming PC such as the Asus ROG, but since the former are very expensive and the later's graphics abilities were of no use to me (I'm not a gamer) I ruled them both out. These being quality machines, when I compared them against reviews of other PC's and laptops I noticed that where other systems scored higher in performance, they were lower in build quality and vice versa and there was no overall winner that had me sold.

I decided, a self build was in order and that it would be great if I could fit it all into a mini-ITX board and case. My requirements became:

An SSD drive (faster read/write times than a HDD)

Ubuntu: On account of it being free and faster that MacOS

Mini-ITX: so that it can unobtrusively fit onto my desk

Quite

16Gb DDR4 RAM: this seems the bare minimum for development.

After some searching I came across these instructions for a $682 Skylake Mac Mini Hackintosh Build, which formed the basis of my build.

As I currently have no intention of working with MacOS, as per the Hackintosh instructions, I did not change the Wifi card.

My new spec list along with what I paid for each item were as follows:

Intel Core i7 Quad-Core i7-6700 3.4GHz Processor    £279.97

Crucial Ballistix Sport 16 GB kit (8 GB x 2) DDR4 2400MT/s UDIMM 288-Pin Memory    £121.00

Samsung 850 Pro 250GB SSD £121.00

Gigabyte H-170 Motherboard    £109.00

Noctua NH-L9i CPU Cooler  £35.00

External PicoPSU Power Brick  £24.00

MiniBox 160W PicoPSU  £40.00

Streacom F1C-WS   £90.00

Noctua NF-A4x10 FLX £10.99

Making a total spend of £830 (correct at time of writing).

The case comes in two finishes; black and silver, I went with the former to keep my monitor my main point of focus on my desk. It took me about an hour as a newbie to put it all together. I imagine it would be much faster if I did this for living.

Pros:

My rebuild times were drastically reduced to only 2s using Meteor 1.4.

The PC as a whole takes only 15 seconds to boot up whereas the laptop could take as long as 2 minutes.

With the laptop, a Meteor reload would fully load the CPU whereas with the PC the 4 cores barley rose above a few percent, as viewed from the System Monitor tool.

It has a footprint of 19cm x 19cm making which is smaller than my laptop.

It was super quite, the fans were barley noticeable on most days.

Cons:

The draw back of such a small case is that there is no room for a graphics card should I want to start gaming in the future.

All the ports are at the rear. However, this does give the front a clean look.

There is no reset button but the power switch can be configured via the bios to act as a "soft" switch such that, pressing it brings up a dialogue giving you the option to restart/suspend/shutdown.

Conclusion:

Overall I am very happy with the choice of components I made and the money I saved by self-building.The PC is powerful enough for video editing and I am working towards editing my first Youtube tutorials.

Being more wise about my needs means that I am now using Docker to create isolated development environments to prevent software conflicts which in themselves can chew up time in resolving.

The component research I did means that I am aware of the massive progress that PC cases, coolers, cables, memory cards, fans have made since I left college. You can now build something not only small and powerful but also attractive with options like tempered glass, liquid coolers, custom braided cables, case strobe lighting and shaped cases.

Title: How to speed Meteor.js build times?


问:
Background-color overlapping border-radius
I am making this page where I wanted a rounded box in the middle.
My issue is (as seen in the picture) that I have a div with background-color that is overlapping the div behind with the border-radius.

Her is the image!

答: On the outer div(the one with the border radius) add overflow:hidden.  If for whatever reason you want to avoid that, you can also add an additional border radius to the child element.</p>


问:
FOSUserBundle: "The file could not be found." error while resetting/changing password
I've encountered a strange error while working with FOSUserBundle. When I try to reset or change a password for user who has filename of uploaded image in his entity I receive an error: "The file could not be found." If image field is null, everything is fine. So I've just workaround this problem by setting photo as null before $form->setData($user) in resetAction and then after form submission and validation I set an old photo value again.

My solution:

```<code>/**
 * Reset user password.
 *
 * @param Request $request
 * @param string  $token
 *
 * @return Response
 */
public function resetAction(Request $request, $token)
{
    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.resetting.form.factory');
    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');
    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $user = $userManager->findUserByConfirmationToken($token);

    if (null === $user) {
        throw new NotFoundHttpException(sprintf('The user with "confirmation token" does not exist for value "%s"', $token));
    }

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_INITIALIZE, $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }

    $form = $formFactory->createForm();

    //fix error upon form validation: "The file could not be found."
    $photo = $user->getPhoto();
    $user->setPhoto(null);

    $form->setData($user);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_SUCCESS, $event);

        //set photo name instead of null
        $user->setPhoto($photo);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_profile_show');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(
            FOSUserEvents::RESETTING_RESET_COMPLETED,
            new FilterUserResponseEvent($user, $request, $response)
        );

        return $response;
    }

    return $this->render('@FOSUser/Resetting/reset.html.twig', array(
        'token' => $token,
        'form' => $form->createView(),
    ));
}
</code>```

Fragment of my User entity:

```<code>class User extends BaseUser
{
    /**
     * @ var string
     *
     * @ORM\Column(name="photo", type="string", length=255, nullable=true)
     * @Assert\File(mimeTypes={ "image/jpeg", "image/png" })
     */
    private $photo;
</code>```

I don't understand why file validation takes place when I submit form without file upload input. And what is the point of checking all fields of user when you just resetting password?

答: In form workflow submit provide handlerequest to fill all user row, set up your form with required false for your form field</p>

Body:
I've encountered a strange error while working with FOSUserBundle. When I try to reset or change a password for user who has filename of uploaded image in his entity I receive an error: "The file could not be found." If image field is null, everything is fine. So I've just workaround this problem by setting photo as null before $form->setData($user) in resetAction and then after form submission and validation I set an old photo value again.

My solution:

/**
 * Reset user password.
 *
 * @param Request $request
 * @param string  $token
 *
 * @return Response
 */
public function resetAction(Request $request, $token)
{
    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.resetting.form.factory');
    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');
    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $user = $userManager->findUserByConfirmationToken($token);

    if (null === $user) {
        throw new NotFoundHttpException(sprintf('The user with "confirmation token" does not exist for value "%s"', $token));
    }

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_INITIALIZE, $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }

    $form = $formFactory->createForm();

    //fix error upon form validation: "The file could not be found."
    $photo = $user->getPhoto();
    $user->setPhoto(null);

    $form->setData($user);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_SUCCESS, $event);

        //set photo name instead of null
        $user->setPhoto($photo);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_profile_show');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(
            FOSUserEvents::RESETTING_RESET_COMPLETED,
            new FilterUserResponseEvent($user, $request, $response)
        );

        return $response;
    }

    return $this->render('@FOSUser/Resetting/reset.html.twig', array(
        'token' => $token,
        'form' => $form->createView(),
    ));
}

Fragment of my User entity:

class User extends BaseUser
{
    /**
     * @ var string
     *
     * @ORM\Column(name="photo", type="string", length=255, nullable=true)
     * @Assert\File(mimeTypes={ "image/jpeg", "image/png" })
     */
    private $photo;

I don't understand why file validation takes place when I submit form without file upload input. And what is the point of checking all fields of user when you just resetting password?


问:
Set values on Select2 search form for multiselect
I have a json string that I wish to add to select2 multiselect search input. I am getting map error as below

Cannot read property 'map' of undefined

The json field from console log is

```<code>[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]
</code>```

And the js code is

```<code>   var employees = $(this).attr('data-employees');
    console.log(employees);

    $("select[name='employees[]']").val(employees.data.map(function(x) {
   return x.id; })); // Set the selected data before show it.
            $('select').select2()
</code>```

HTML

```<code><select multiple="multiple" name="employees[]" id="form-field-select-4" width="200px "class="form-control search-select"></select>
</code>```

答:
As I can see you are getting this array from element attribute and if you are, probably the console.log is a string so, try this:

```<code>var employees = JSON.parse( $(this).attr('data-employees') );
console.log(employees);

$('select').select2(); // init with select2
$("select[name='employees[]']").val(employees.map(function(x) {
   return x.id;  // Set the selected data before show it.
}))
.trigger("change");
</code>```

If you see this

var employees = JSON.parse('[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]');
console.log('The whole array:', employees); // you have a valid array

var ids = employees.map(function(x){ return x.id; })
console.log('Employee ids only: ', ids);```

Edited

Body:
I have a json string that I wish to add to select2 multiselect search input. I am getting map error as below

Cannot read property 'map' of undefined

The json field from console log is

[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]

And the js code is

   var employees = $(this).attr('data-employees');
    console.log(employees);

    $("select[name='employees[]']").val(employees.data.map(function(x) {
   return x.id; })); // Set the selected data before show it.
            $('select').select2()

HTML

<select multiple="multiple" name="employees[]" id="form-field-select-4" width="200px "class="form-control search-select"></select>

Body:
As I can see you are getting this array from element attribute and if you are, probably the console.log is a string so, try this:

var employees = JSON.parse( $(this).attr('data-employees') );
console.log(employees);

$('select').select2(); // init with select2
$("select[name='employees[]']").val(employees.map(function(x) {
   return x.id;  // Set the selected data before show it.
}))
.trigger("change");

If you see this

var employees = JSON.parse('[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]');
console.log('The whole array:', employees); // you have a valid array

var ids = employees.map(function(x){ return x.id; })
console.log('Employee ids only: ', ids);

Edited


问:
Javascript array items to numbers
I've made a program that sorts numbers user inputs. The problem is that when I insert an empty space, it is stored in array as a number 0. I tried to set up several conditions to prevent this but nothing seems to work out. Any solution?
here's a little snippet of my code where I believe the mistake occurs and where some kind of condition should be set:
stringArray = userInput.value.split(' ');
  numArray = stringArray.map(Number);

答:
As Javascript nature is weakly typed language, every time when you map your value and coerce it to Number in your code, JS tries to convert it to compatible types. Hence, empty space is converted to 0.

you can do multiple things in this case. The easiest one would be to get rid of any spaces before mapping.

I'd suggest filtering the array before mapping, e.g. :

```<code>stringArray.filter(function(value) {
  return value.trim() !== '';
}).map(Number);
</code>```

Another idea would be to get rid of spaces before, as suggested in the comments, using RegExp ;)

Title: Javascript array items to numbers

Body:
As Javascript nature is weakly typed language, every time when you map your value and coerce it to Number in your code, JS tries to convert it to compatible types. Hence, empty space is converted to 0.

you can do multiple things in this case. The easiest one would be to get rid of any spaces before mapping.

I'd suggest filtering the array before mapping, e.g. :

stringArray.filter(function(value) {
  return value.trim() !== '';
}).map(Number);

Another idea would be to get rid of spaces before, as suggested in the comments, using RegExp ;)


问:
CUDA: passing class to device with a class member that is a pointer function
I want to write a c++ CUDA program where I pass a class to the kernel. The class just evaluates a function on the kernel via the call operator(). If I hardwire the function in the class everything works as I'd like. However I want some flexibility with the class so I'd like the class to be able to be instantiated with different functions. Say by passing in a pointer function. I can't get the pointer function implementation to work. Below I define two classes, one that has the function defined (fixedFunction) and another that takes a pointer to function (genericFunction)

```<code>//Functions.hh
#include <iostream>
#include <stdio.h>

class fixedFunction{
public:
 __host__ fixedFunction() {}
 __host__ __device__ double operator()(double x) {
    return x*x;
 }
};

double f1(double x){
  return x*x;
}

typedef double (*pf) (double var);

class genericFunction{
public:
  __host__ genericFunction(double (*infunc)(double)) : func(infunc){}
  __host__ __device__ double operator()(double x) {
    return func(x);
  }
private:
  pf func;
};

__global__ void kernel1(fixedFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}

__global__ void kernel2(genericFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}
</code>```

Instantiating both classes and running them on the host works. Passing to the relevant kernels I see that kernel2 where that class calls a pointer function fails

```<code>#include "Functions.hh"

int main(){

  fixedFunction h_g1;
  fixedFunction* d_g1;
  cudaMallocManaged(&d_g1, sizeof(h_g1));

  //Host call
  std::cout << h_g1(2.0) << "\n";

  //device call
  kernel1<<<1,32>>>(d_g1);
  cudaDeviceSynchronize();

  genericFunction h_g2(f1);
  genericFunction* d_g2;
  cudaMallocManaged(&d_g2, sizeof(h_g2));

  //Host call
  std::cout << h_g2(3.0) << "\n";

  //device call
  kernel2<<<1,32>>>(d_g2);
  cudaDeviceSynchronize();
</code>```

I can see an issue in the pointer function can be any size and that is not accounted for on the device. So is there a way to pass a pointer function to a class and run it on the device?

Thanks

答:
This was approximately the "smallest" number of changes I could make to your code to get it to function approximately as you appeared to intend.  Also note that there are many other questions about function pointers in CUDA, this answer links to several.

decorate f1 with __host__ __device__.  This is necessary to get the compiler to generate a device-callable routine for it.  Otherwise, only host code is generated.

we need to capture the device entry address for the device callable version of f1 created in 1 above.  There are a number of methods to do this.  I will capture it "statically" with another __device__ variable (f1_d) and then use cudaMemcpyFromSymbol to pull it into host code.

Your genericFunction class is modified to be able to hold both __host__ and separate __device__ entry points (function pointers) for the desired function. Also, the class is modified to select the proper one, based on whether we are compiling the host or device version of the class (__CUDA_ARCH__ macro), and the class constructor is modified to accept and assign both entry points.

Finally, we also need to initialize the d_g2 object on the device.  In the case of the d_g1 object, there are no class data members for that object, so we can "get away with" creating an "empty" object pointed to by d_g1 and it works correctly because the entry points for that object's class member functions are already known in device code.  However, in the case of d_g2, we are accessing the functions indirectly via class data members which are pointers to the respective host and device versions (entry points) of the function.  Therefore, after initializing the h_g2 object in host code, and establishing storage for the d_g2 object in device code, we must initialize d_g2 with the contents of h_g2 using cudaMemcpy after the cudaMallocManaged for d_g2.

With those changes, your code works as written according to my test:

```<code>$ cat t353.cu
#include <iostream>
#include <stdio.h>

class fixedFunction{
public:
 __host__ fixedFunction() {}
 __host__ __device__ double operator()(double x) {
    return x*x;
 }
};

__host__ __device__ double f1(double x){
  return x*x;
}

typedef double (*pf) (double var);

__device__ pf f1_d = f1;

class genericFunction{
public:
  __host__ genericFunction(double (*h_infunc)(double), double (*d_infunc)(double)) : h_func(h_infunc),d_func(d_infunc){}
  __host__ __device__ double operator()(double x) {
#ifdef __CUDA_ARCH__
    return d_func(x);
#else
    return h_func(x);
#endif
  }
private:
  pf h_func;
  pf d_func;
};

__global__ void kernel1(fixedFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}

__global__ void kernel2(genericFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}

int main(){

  fixedFunction h_g1;
  fixedFunction* d_g1;
  cudaMallocManaged(&d_g1, sizeof(h_g1));

  //Host call
  std::cout << h_g1(2.0) << "\n";

  //device call
  kernel1<<<1,32>>>(d_g1);
  cudaDeviceSynchronize();
  pf d_f1;
  cudaMemcpyFromSymbol(&d_f1, f1_d, sizeof(void*));
  genericFunction h_g2(f1, d_f1);
  genericFunction* d_g2;
  cudaMallocManaged(&d_g2, sizeof(h_g2));
  cudaMemcpy(d_g2, &h_g2, sizeof(h_g2), cudaMemcpyDefault);
  //Host call
  std::cout << h_g2(3.0) << "\n";

  //device call
  kernel2<<<1,32>>>(d_g2);
  cudaDeviceSynchronize();
}
$ nvcc -arch=sm_61 -o t353 t353.cu
$ cuda-memcheck ./t353
========= CUDA-MEMCHECK
4
Func val is: 0.000000
Func val is: 1.000000
Func val is: 4.000000
Func val is: 9.000000
Func val is: 16.000000
Func val is: 25.000000
Func val is: 36.000000
Func val is: 49.000000
Func val is: 64.000000
Func val is: 81.000000
Func val is: 100.000000
Func val is: 121.000000
Func val is: 144.000000
Func val is: 169.000000
Func val is: 196.000000
Func val is: 225.000000
Func val is: 256.000000
Func val is: 289.000000
Func val is: 324.000000
Func val is: 361.000000
Func val is: 400.000000
Func val is: 441.000000
Func val is: 484.000000
Func val is: 529.000000
Func val is: 576.000000
Func val is: 625.000000
Func val is: 676.000000
Func val is: 729.000000
Func val is: 784.000000
Func val is: 841.000000
Func val is: 900.000000
Func val is: 961.000000
9
Func val is: 0.000000
Func val is: 1.000000
Func val is: 4.000000
Func val is: 9.000000
Func val is: 16.000000
Func val is: 25.000000
Func val is: 36.000000
Func val is: 49.000000
Func val is: 64.000000
Func val is: 81.000000
Func val is: 100.000000
Func val is: 121.000000
Func val is: 144.000000
Func val is: 169.000000
Func val is: 196.000000
Func val is: 225.000000
Func val is: 256.000000
Func val is: 289.000000
Func val is: 324.000000
Func val is: 361.000000
Func val is: 400.000000
Func val is: 441.000000
Func val is: 484.000000
Func val is: 529.000000
Func val is: 576.000000
Func val is: 625.000000
Func val is: 676.000000
Func val is: 729.000000
Func val is: 784.000000
Func val is: 841.000000
Func val is: 900.000000
Func val is: 961.000000
========= ERROR SUMMARY: 0 errors
$
</code>```

Body:
I want to write a c++ CUDA program where I pass a class to the kernel. The class just evaluates a function on the kernel via the call operator(). If I hardwire the function in the class everything works as I'd like. However I want some flexibility with the class so I'd like the class to be able to be instantiated with different functions. Say by passing in a pointer function. I can't get the pointer function implementation to work. Below I define two classes, one that has the function defined (fixedFunction) and another that takes a pointer to function (genericFunction)

//Functions.hh
#include <iostream>
#include <stdio.h>

class fixedFunction{
public:
 __host__ fixedFunction() {}
 __host__ __device__ double operator()(double x) {
    return x*x;
 }
};

double f1(double x){
  return x*x;
}

typedef double (*pf) (double var);

class genericFunction{
public:
  __host__ genericFunction(double (*infunc)(double)) : func(infunc){}
  __host__ __device__ double operator()(double x) {
    return func(x);
  }
private:
  pf func;
};

__global__ void kernel1(fixedFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}

__global__ void kernel2(genericFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}

Instantiating both classes and running them on the host works. Passing to the relevant kernels I see that kernel2 where that class calls a pointer function fails

#include "Functions.hh"

int main(){

  fixedFunction h_g1;
  fixedFunction* d_g1;
  cudaMallocManaged(&d_g1, sizeof(h_g1));

  //Host call
  std::cout << h_g1(2.0) << "\n";

  //device call
  kernel1<<<1,32>>>(d_g1);
  cudaDeviceSynchronize();

  genericFunction h_g2(f1);
  genericFunction* d_g2;
  cudaMallocManaged(&d_g2, sizeof(h_g2));

  //Host call
  std::cout << h_g2(3.0) << "\n";

  //device call
  kernel2<<<1,32>>>(d_g2);
  cudaDeviceSynchronize();

I can see an issue in the pointer function can be any size and that is not accounted for on the device. So is there a way to pass a pointer function to a class and run it on the device?

Thanks

Body:
This was approximately the "smallest" number of changes I could make to your code to get it to function approximately as you appeared to intend.  Also note that there are many other questions about function pointers in CUDA, this answer links to several.

decorate f1 with __host__ __device__.  This is necessary to get the compiler to generate a device-callable routine for it.  Otherwise, only host code is generated.

we need to capture the device entry address for the device callable version of f1 created in 1 above.  There are a number of methods to do this.  I will capture it "statically" with another __device__ variable (f1_d) and then use cudaMemcpyFromSymbol to pull it into host code.

Your genericFunction class is modified to be able to hold both __host__ and separate __device__ entry points (function pointers) for the desired function. Also, the class is modified to select the proper one, based on whether we are compiling the host or device version of the class (__CUDA_ARCH__ macro), and the class constructor is modified to accept and assign both entry points.

Finally, we also need to initialize the d_g2 object on the device.  In the case of the d_g1 object, there are no class data members for that object, so we can "get away with" creating an "empty" object pointed to by d_g1 and it works correctly because the entry points for that object's class member functions are already known in device code.  However, in the case of d_g2, we are accessing the functions indirectly via class data members which are pointers to the respective host and device versions (entry points) of the function.  Therefore, after initializing the h_g2 object in host code, and establishing storage for the d_g2 object in device code, we must initialize d_g2 with the contents of h_g2 using cudaMemcpy after the cudaMallocManaged for d_g2.

With those changes, your code works as written according to my test:

$ cat t353.cu
#include <iostream>
#include <stdio.h>

class fixedFunction{
public:
 __host__ fixedFunction() {}
 __host__ __device__ double operator()(double x) {
    return x*x;
 }
};

__host__ __device__ double f1(double x){
  return x*x;
}

typedef double (*pf) (double var);

__device__ pf f1_d = f1;

class genericFunction{
public:
  __host__ genericFunction(double (*h_infunc)(double), double (*d_infunc)(double)) : h_func(h_infunc),d_func(d_infunc){}
  __host__ __device__ double operator()(double x) {
#ifdef __CUDA_ARCH__
    return d_func(x);
#else
    return h_func(x);
#endif
  }
private:
  pf h_func;
  pf d_func;
};

__global__ void kernel1(fixedFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}

__global__ void kernel2(genericFunction* g1){
  unsigned int tid = blockIdx.x *blockDim.x + threadIdx.x;
  printf("Func val is: %f\n", (*g1)(tid));
}

int main(){

  fixedFunction h_g1;
  fixedFunction* d_g1;
  cudaMallocManaged(&d_g1, sizeof(h_g1));

  //Host call
  std::cout << h_g1(2.0) << "\n";

  //device call
  kernel1<<<1,32>>>(d_g1);
  cudaDeviceSynchronize();
  pf d_f1;
  cudaMemcpyFromSymbol(&d_f1, f1_d, sizeof(void*));
  genericFunction h_g2(f1, d_f1);
  genericFunction* d_g2;
  cudaMallocManaged(&d_g2, sizeof(h_g2));
  cudaMemcpy(d_g2, &h_g2, sizeof(h_g2), cudaMemcpyDefault);
  //Host call
  std::cout << h_g2(3.0) << "\n";

  //device call
  kernel2<<<1,32>>>(d_g2);
  cudaDeviceSynchronize();
}
$ nvcc -arch=sm_61 -o t353 t353.cu
$ cuda-memcheck ./t353
========= CUDA-MEMCHECK
4
Func val is: 0.000000
Func val is: 1.000000
Func val is: 4.000000
Func val is: 9.000000
Func val is: 16.000000
Func val is: 25.000000
Func val is: 36.000000
Func val is: 49.000000
Func val is: 64.000000
Func val is: 81.000000
Func val is: 100.000000
Func val is: 121.000000
Func val is: 144.000000
Func val is: 169.000000
Func val is: 196.000000
Func val is: 225.000000
Func val is: 256.000000
Func val is: 289.000000
Func val is: 324.000000
Func val is: 361.000000
Func val is: 400.000000
Func val is: 441.000000
Func val is: 484.000000
Func val is: 529.000000
Func val is: 576.000000
Func val is: 625.000000
Func val is: 676.000000
Func val is: 729.000000
Func val is: 784.000000
Func val is: 841.000000
Func val is: 900.000000
Func val is: 961.000000
9
Func val is: 0.000000
Func val is: 1.000000
Func val is: 4.000000
Func val is: 9.000000
Func val is: 16.000000
Func val is: 25.000000
Func val is: 36.000000
Func val is: 49.000000
Func val is: 64.000000
Func val is: 81.000000
Func val is: 100.000000
Func val is: 121.000000
Func val is: 144.000000
Func val is: 169.000000
Func val is: 196.000000
Func val is: 225.000000
Func val is: 256.000000
Func val is: 289.000000
Func val is: 324.000000
Func val is: 361.000000
Func val is: 400.000000
Func val is: 441.000000
Func val is: 484.000000
Func val is: 529.000000
Func val is: 576.000000
Func val is: 625.000000
Func val is: 676.000000
Func val is: 729.000000
Func val is: 784.000000
Func val is: 841.000000
Func val is: 900.000000
Func val is: 961.000000
========= ERROR SUMMARY: 0 errors
$


问:
Failed building wheel for python-ldap (windows) *first stackoverflow ask*
I've installed flask, flask_login, and ldap in the virtualenv for my flask package (to authenticate ldap users with the usernames & passwords of the other users at my company).

When I run my flask app, I get "AttributeError: 'module' object has no attribute 'initialize'"

I'm tried "pip install python-ldap"
but I get a red error (sandwiched between other white text) that reads:
"Failed building wheel for python-ldap"

I have thoroughly examined these:
How to install python-ldap on a python 2.7 virtualenv on windows without compiling

Installing python-ldap in a virtualenv on Windows

https://www.python-ldap.org/docs.html

https://www.linuxjournal.com/article/6988?page=0,1

to no avail.
I've had this error for days now...

(also:

pip install openldap

gives:

Collecting openldap
  Could not find a version that satisfies the requirement openldap (from versions: )
No matching distribution found for openldap

...(in and outside of my venv) if that information helps)

I had this error last week and after switching work computers, I recreated the virtualenv and installed all of the other packages and dependencies successfully.

my requirements.txt file contains these lines after a line of git stuff:

click==6.7

Flask==0.12.2

Flask-Login==0.4.0

itsdangerous==0.24

Jinja2==2.9.6

ldap==1.0.2

ldap3==2.2.4

MarkupSafe==1.0

pyasn1==0.2.3

Werkzeug==0.12.2

Has anyone successfully installed python-ldap into a flask virtualenv with windows? If so... how?!

答:
Go to:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap

download python_ldap-2.4.38-cp27-cp27m-win_amd64.whl in the same directory that your venv folder is listed under

(ex.)

```<code>/myrepo
    /myapp
      /myapp
      /venv
      /run.py
      /python_ldap-2.4.38-cp27-cp27m-win_amd64.whl
</code>```

install the .whl file while inside of your venv

```<code>venv\Scripts\activate

pip install python_ldap-2.4.38-cp27-cp27m-win_amd64.whl
</code>```

Voila!

Body:
Go to:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap

download python_ldap-2.4.38-cp27-cp27m-win_amd64.whl in the same directory that your venv folder is listed under

(ex.)

/myrepo
    /myapp
      /myapp
      /venv
      /run.py
      /python_ldap-2.4.38-cp27-cp27m-win_amd64.whl

install the .whl file while inside of your venv

venv\Scripts\activate

pip install python_ldap-2.4.38-cp27-cp27m-win_amd64.whl

Voila!


问:
Unable to resolve class : Gradle 'AppName' project refresh failed
I have a problem whit Android Studio. I did not pass this issue. :) I am waitin for this a week after. I delete studio and load agan bur why not woring. have I change to pc or home or country or world :)) Wyh it is not work>in...

I tried delete Android Studio from pc  a few times. :p

Clean project

Tried rebuild project

Invaidate caches/ restart

Synchronize project

Synchronize project whit gradle Files
7- I try to previous Android Studio ide's but not working!

Not wor KİNG :D

I cannot pass following issue on Android Studio:

Gradle 'xName' project refresh failed

Error:Cause: startup failed:

initialization script
  'C:\Users\Şerif\AppData\Local\Temp\ijinit.gradle': 17: unable to
  resolve class
  org.jetbrains.plugins.gradle.tooling.internal.ExtraModelBuilder  @
  line 17, column 1.

error !  import

org.jetbrains.plugins.gradle.tooling.internal.ExtraModelBuilder    ^

1 error

And How I setup new one Android Studio
(I am usin android studio officail web site download.
Is there any other action?

please help :)

Where is the build gradle app is not here!! There is somthing wrong in list

答:
i got the right answer, after struggling for 2 days.
Go to file->project structure->project -> and there change gradle version to latest if you updated it.
In my case, i changed it from 3.3 to 4.0 yesterday and this error was gone.
Best of luck, if it will help you then accept my answer </p>


问:
Java, send multiple get request per second
How to send N (N > 100) request per second to specify URL in java?
I'm using ExecutorService and CountDownLatch for it.

```<code>CountDownLatch latch = new CountDownLatch(DEFAULT_LATCH_COUNT);
    for (int i = 0; i < requestNumber; i++) {
        executor.submit(RequestFactory.getInstance().createRequester(latch, url));
    }
    latch.countDown();
</code>```

But creating new Thread for each request is not good practice, isn't it ?
If I must send 500 asynchronous request per second I must create 500 threads.
Is this a right way to solve it or are there other solutions ?

答:
Having 500 threads would be bad practice, because it will incur unnecessary overhead for context switching between threads, not to mention the initialization overhead of creating 500 threads.

Keep in mind that the amount of threads that can run in parallel is limited by the number of available processors (i.e. Runtime.getRuntime().availableProcessors()).  So if your computer has 8 available processors, there is no point in making more than 8 worker threads.

As for actually performing the work, this is a cookie cutter worker queue scenario.  Here you can create the number of worker threads equal to the number of available processors, and have each worker thread perform chunks of work until all of the work is completed (tracked by an AtomicInteger or something similar)

Body:
How to send N (N > 100) request per second to specify URL in java?
I'm using ExecutorService and CountDownLatch for it.

CountDownLatch latch = new CountDownLatch(DEFAULT_LATCH_COUNT);
    for (int i = 0; i < requestNumber; i++) {
        executor.submit(RequestFactory.getInstance().createRequester(latch, url));
    }
    latch.countDown();

But creating new Thread for each request is not good practice, isn't it ?
If I must send 500 asynchronous request per second I must create 500 threads.
Is this a right way to solve it or are there other solutions ?


问:
Wordpress and handling if (($_SERVER["REQUEST_METHOD"] == "POST")
I've written a script in php which works like a charm. Now I'm trying to integrate this script in WordPress. Which is new for me.

In my php script I removed all the PDO commands as I know/think WordPress can't handle these.

I simply changed it to $wpdb. I did some test and this works.
The test I did were with a simple script. User input that gets submitted and gets uploaded to my database.

Now I want to make it a bit more complicated. I first want the user input to be checked for errors. The error handling is in a different php file. I know this works as I've tested it.

Where I seem to struggle is putting it all together in Wordpress.

What I did you can see below. Question is why is this not working in WordPress? Am I overlooking something?

```<code><?php
include_once('scripts/useful_functions.inc.php');
global $wpdb;

if (($_SERVER["REQUEST_METHOD"] == "POST") && $geslachtErr== "" && $voornaamErr== "" && $familienaamErr== "" && $emailErr== "" && $telErr== "" && $afileErr== "") {

    sendmail($mail);

    $table = $wpdb->ajrecuit_com.'sollicitatie_form';
    $file = rand(1000,100000)."-".$_FILES['afile']['name'];
    $file_size = $_FILES['afile']['size'];
    $file_type = $_FILES['afile']['type'];
    $file_loc = $_FILES['afile']['tmp_name'];
    $folder="uploads/";
    $data = array(
        'geslacht' => $_POST['geslacht'],
        'voornaam' => $_POST['voornaam'],
        'familienaam' => $_POST['familienaam'],
        'email' => $_POST['email'],
        'tel' => $_POST['tel'],
        'afile' => rand(1000,100000)."-".$_FILES['afile']['name'],
        'size' => $_FILES['afile']['size'],
        'type' => $_FILES['afile']['type'],
    );

    $new_size = $file_size/1024;
    $new_file_name = strtolower($file);
    $final_file=str_replace(' ','-',$new_file_name);

    $format = array(
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s'
    );

    if(move_uploaded_file($file_loc,$folder.$final_file)) {
        $success=$wpdb->insert( $table, $data, $format,$folder);
        if($success) {
            ?>

            <script>
                alert('successfully uploaded');
                window.location.href='sollicitatie_formulier_wp?success';
            </script>
            <?php
        }
    }
}else { ?>

<div class="form">

    <div class="tab-content">
        <h1>Sollicitatie Formulier</h1>

        <form method="post" enctype="multipart/form-data" >

            <div class="top-row">
                <div class="field-wrap">
                    <p><span class="error">* verplichte velden.</span></p>
                    <label>Geslacht</label><span class="error">* <?php echo $geslachtErr;?></span>
                    <select name="options[foo]">
                        <option value="" <?php selected( $options['foo'], 1 ); ?>></option>
                        <option value="Man" <?php selected( $options['foo'], 2 ); ?>>Man</option>
                        <option value="Vrouw" <?php selected( $options['foo'], 3 ); ?>>Vrouw</option>
                    </select>
                </div> <!-- /field-wrap-->

                <div class="field-wrap">
                    <label>Voornaam</label><span class="error">* <?php echo $voornaamErr;?></span>
                    <input type="text" name="voornaam" value="">
                </div> <!-- /field-wrap-->

                <div class="field-wrap">
                    <label>Familienaam</label><span class="error">* <?php echo $familienaamErr;?></span>
                    <input type="text" name="familienaam" value="<?= isset($_POST['familienaam']) ? $_POST['familienaam'] : ''; ?>">
                </div> <!-- /field-wrap-->
            </div> <!-- /top-row -->

            <div class="field-wrap">
                <label>Email Adres</label><span class="error">* <?php echo $emailErr;?></span>
                <input type="email" name="email" value="<?= isset($_POST['email']) ? $_POST['email'] : ''; ?>">
            </div> <!-- /field-wrap-->

            <div class="field-wrap">
                <label>Telefoon/GSM</label><span class="error">* <?php echo $telErr;?></span>
                <input type="text" name="tel" value="<?= isset($_POST['tel']) ? $_POST['tel'] : ''; ?>">
            </div> <!-- /field-wrap-->

            <div class="field-wrap">
                <label>CV</label><span class="error">* <?php echo $afileErr;?></span>
                <input type="file" name="afile" >
            </div> <!-- /field-wrap-->

            <button type="submit" class="button button-block" />Get Started</button>

        </form>

    </div><!-- /tab-content-->

</div> <!-- /form -->

<?php }
</code>```

答:
Wordpress has a function "selected()" - https://codex.wordpress.org/Function_Reference/selected

You have to change that selected name to something else or use the Wordpress function

Body:
I've written a script in php which works like a charm. Now I'm trying to integrate this script in WordPress. Which is new for me.

In my php script I removed all the PDO commands as I know/think WordPress can't handle these.

I simply changed it to $wpdb. I did some test and this works.
The test I did were with a simple script. User input that gets submitted and gets uploaded to my database.

Now I want to make it a bit more complicated. I first want the user input to be checked for errors. The error handling is in a different php file. I know this works as I've tested it.

Where I seem to struggle is putting it all together in Wordpress.

What I did you can see below. Question is why is this not working in WordPress? Am I overlooking something?

<?php
include_once('scripts/useful_functions.inc.php');
global $wpdb;

if (($_SERVER["REQUEST_METHOD"] == "POST") && $geslachtErr== "" && $voornaamErr== "" && $familienaamErr== "" && $emailErr== "" && $telErr== "" && $afileErr== "") {

    sendmail($mail);

    $table = $wpdb->ajrecuit_com.'sollicitatie_form';
    $file = rand(1000,100000)."-".$_FILES['afile']['name'];
    $file_size = $_FILES['afile']['size'];
    $file_type = $_FILES['afile']['type'];
    $file_loc = $_FILES['afile']['tmp_name'];
    $folder="uploads/";
    $data = array(
        'geslacht' => $_POST['geslacht'],
        'voornaam' => $_POST['voornaam'],
        'familienaam' => $_POST['familienaam'],
        'email' => $_POST['email'],
        'tel' => $_POST['tel'],
        'afile' => rand(1000,100000)."-".$_FILES['afile']['name'],
        'size' => $_FILES['afile']['size'],
        'type' => $_FILES['afile']['type'],
    );

    $new_size = $file_size/1024;
    $new_file_name = strtolower($file);
    $final_file=str_replace(' ','-',$new_file_name);

    $format = array(
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s'
    );

    if(move_uploaded_file($file_loc,$folder.$final_file)) {
        $success=$wpdb->insert( $table, $data, $format,$folder);
        if($success) {
            ?>

            <?php
        }
    }
}else { ?>

Sollicitatie Formulier

        <form method="post" enctype="multipart/form-data" >

* verplichte velden.

                    Geslacht* <?php echo $geslachtErr;?>
                    <select name="options[foo]">
                        <option value="" <?php selected( $options['foo'], 1 ); ?>></option>
                        <option value="Man" <?php selected( $options['foo'], 2 ); ?>>Man</option>
                        <option value="Vrouw" <?php selected( $options['foo'], 3 ); ?>>Vrouw</option>
                    </select>

                    Voornaam* <?php echo $voornaamErr;?>
                    <input type="text" name="voornaam" value="">

                    Familienaam* <?php echo $familienaamErr;?>
                    <input type="text" name="familienaam" value="<?= isset($_POST['familienaam']) ? $_POST['familienaam'] : ''; ?>">

                Email Adres* <?php echo $emailErr;?>
                <input type="email" name="email" value="<?= isset($_POST['email']) ? $_POST['email'] : ''; ?>">

                Telefoon/GSM* <?php echo $telErr;?>
                <input type="text" name="tel" value="<?= isset($_POST['tel']) ? $_POST['tel'] : ''; ?>">

                CV* <?php echo $afileErr;?>
                <input type="file" name="afile" >

            <button type="submit" class="button button-block" />Get Started</button>

        </form>

<?php }


问:
Is it possible to test for an attribute specifier in C++?
I'm trying to achieve different behavior based on an attribute applied to a function. Basically I'm trying to see if it is possible to test for the presence of an attribute at compile time.

```<code>struct AbortError
{
    [[noreturn]] static void error(const std::string& msg)
    {
        std::cerr << "critical error: " << msg << std::endl;
        std::abort();
    }
}

struct LogError
{
    static void error(const std::string& msg)
    {
        std::cerr << "non-critical error: " << msg << std::endl;
    }
}
</code>```

Is it possible to test for the presence of [[noreturn]]?

I'm hoping to acheive something like

```<code>template <typename ErrorPolicy>
void function()
{
    // ...
    if constexpr(std::is_noreturn<ErrorPolicy::error>::value)
    {
        performCriticalCleanup();
    }

    ErrorPolicy::error("Bad things happened.");
}
</code>```

答:
Since C++ does not have reflection, the answer is no: it is not possible.

What I, instead, suggest you to do is to make a different design choice in order to achieve the same goal.
You could use, for example, polymorfism in an run-time environment.

If you need some at compile time, instead, you can "integrate" a constant expression in your structure and check it later.

For example:

```<code>struct AbortError {
  static constexpr bool critical = true;
  // ...
};
</code>```

or

```<code>struct AbortError: std::true_type {
// ...
};
</code>```

Here an online example which shows both options.

Body:
I'm trying to achieve different behavior based on an attribute applied to a function. Basically I'm trying to see if it is possible to test for the presence of an attribute at compile time.

struct AbortError
{
    [[noreturn]] static void error(const std::string& msg)
    {
        std::cerr << "critical error: " << msg << std::endl;
        std::abort();
    }
}

struct LogError
{
    static void error(const std::string& msg)
    {
        std::cerr << "non-critical error: " << msg << std::endl;
    }
}

Is it possible to test for the presence of [[noreturn]]?

I'm hoping to acheive something like

template <typename ErrorPolicy>
void function()
{
    // ...
    if constexpr(std::is_noreturn<ErrorPolicy::error>::value)
    {
        performCriticalCleanup();
    }

    ErrorPolicy::error("Bad things happened.");
}

Body:
Since C++ does not have reflection, the answer is no: it is not possible.

What I, instead, suggest you to do is to make a different design choice in order to achieve the same goal.
You could use, for example, polymorfism in an run-time environment.

If you need some at compile time, instead, you can "integrate" a constant expression in your structure and check it later.

For example:

struct AbortError {
  static constexpr bool critical = true;
  // ...
};

or

struct AbortError: std::true_type {
// ...
};

Here an online example which shows both options.


问:
How to share NSManagedObject array between threads
I have an app where I am storing contacts to core data , on every launch app loads these contacts to an array of NSManagedObject. Now whenever I try to read from this array for some purpose app crashes, I am trying to read the entire array and check for some data disparity. Problem is this array will be huge and I want to do this task in background so that UI doesn't get blocked, but every time I run the code which modifies some objects from this array Xcode asserts and stops app. I have enabled -com.apple.CoreData.ConcurrencyDebug 1 flag in scheme to enable multi threading related assertion.
Now how can i do the above task in background ? </p>

答: You need to fetch this array in background thread with appropriate NSManagedObjectContext. You can check this tutorial for more info: https://www.raywenderlich.com/145877/core-data-tutorial-multiple-managed-object-contexts-2</p>


问:
Pandas - Replace values in a DataFrame Based on a Boollean DataFrame
I'm using Pandas v0.20.2 and I have DataFrame, like the following:

```<code>df = pd.DataFrame(dict(a=[0,1], b=[3,4], c=[6,7]),
              index=['spam', 'ham'])
#       a  b  c
# spam  0  3  6
# ham   1  4  7
</code>```

And I have another DataFrame that is a mask:

```<code>mask = pd.DataFrame(dict(a=[True,False], b=[True,True]),
                index=['spam', 'ham'])
#           a     b
# spam   True  True
# ham   False  True
</code>```

And I want to set the values in df equal to 999 where it is True in the mask.

I thought that the following would work:

```<code>df[mask] = 999
</code>```

But it doesn't. I get the error below:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-65-503f937859ab> in <module>()
----> 1 df[mask] = 999

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2326             self._setitem_array(key, value)
   2327         elif isinstance(key, DataFrame):
-> 2328             self._setitem_frame(key, value)
   2329         else:
   2330             # set column

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in _setitem_frame(self, key, value)
   2364         self._check_inplace_setting(value)
   2365         self._check_setitem_copy()
-> 2366         self._where(-key, value, inplace=True)
   2367
   2368     def _ensure_valid_index(self, value):

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/generic.pyc in _where(self, cond, other, inplace, axis, level, try_cast, raise_on_error)
   5096             for dt in cond.dtypes:
   5097                 if not is_bool_dtype(dt):
-> 5098                     raise ValueError(msg.format(dtype=dt))
   5099
   5100         cond = cond.astype(bool, copy=False)

ValueError: Boolean array expected for the condition, not float64
</code>```

I would appreciate any help on this.

答:
Another solution, without updating mask

```<code>df[mask.columns] = df[mask.columns].mask(mask, 999)
</code>```

Body:
I'm using Pandas v0.20.2 and I have DataFrame, like the following:

df = pd.DataFrame(dict(a=[0,1], b=[3,4], c=[6,7]),
              index=['spam', 'ham'])
#       a  b  c
# spam  0  3  6
# ham   1  4  7

And I have another DataFrame that is a mask:

mask = pd.DataFrame(dict(a=[True,False], b=[True,True]),
                index=['spam', 'ham'])
#           a     b
# spam   True  True
# ham   False  True

And I want to set the values in df equal to 999 where it is True in the mask.

I thought that the following would work:

df[mask] = 999

But it doesn't. I get the error below:

ValueError                                Traceback (most recent call last)
<ipython-input-65-503f937859ab> in <module>()
----> 1 df[mask] = 999

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2326             self._setitem_array(key, value)
   2327         elif isinstance(key, DataFrame):
-> 2328             self._setitem_frame(key, value)
   2329         else:
   2330             # set column

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in _setitem_frame(self, key, value)
   2364         self._check_inplace_setting(value)
   2365         self._check_setitem_copy()
-> 2366         self._where(-key, value, inplace=True)
   2367
   2368     def _ensure_valid_index(self, value):

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/generic.pyc in _where(self, cond, other, inplace, axis, level, try_cast, raise_on_error)
   5096             for dt in cond.dtypes:
   5097                 if not is_bool_dtype(dt):
-> 5098                     raise ValueError(msg.format(dtype=dt))
   5099
   5100         cond = cond.astype(bool, copy=False)

ValueError: Boolean array expected for the condition, not float64

I would appreciate any help on this.

Body:
Another solution, without updating mask

df[mask.columns] = df[mask.columns].mask(mask, 999)


问:
Better responsive street view cardinal direction buttons
The context

In a hybrid Android app I am getting images for the current location of the user courtesy of the Google Streetview API.  What I want to be able to do is to provide a set of four buttons pointing to four cardinal directions - I think of these as Up, Down, Left, Right as opposed to North, South etc since the top of the phone screen will not necessarily point "north".  Here is how I have done this for now

.lrdiv{display:flex;}
.ldiv,.rdiv
{
 flex:1;
 text-align:left;
 vertical-align:middle;
 height:2em;
 line-height:2em;
}
.rdiv
{
 text-align:right;
 padding-left:0;
}
.upddiv
{
 text-align:center;
}
#mapJog
{
 padding:0.5em;
 padding-left:80%;
 text-align:right;
 border:1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name='viewport' content='user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height' />

<div id='mapJog'>
<div class='upddiv'>
▲
</div>
<div class='lrdiv'>
<div class='ldiv'>
◄
</div>
<div class='rdiv'>
►
</div>
</div>
<div class='upddiv'>
▼

</div>
</div></code>```

The intent here is to provide a street view 200m to the left/right/above/below the current position depending on which of these buttons is clicked.

The red border has been left in to make the result easier to visualize.  Whilst this is the layout I am after I am concerned that I have not adequately addressed the issue of being able to detect tap events (think fat fingers) on the four buttons at different screen sizes.  Hopefully,someone here will be able to suggest improvements which ensure that this always happens irrespective of screen size.

答:
The simplest is to use pseudo element to extend an elements clickable area.

(function(w, d, last) {
  w.addEventListener("load", function() {

    d.getElementById('mapJog').addEventListener('click', function(e) {
      if(last) {
        last.classList.remove('clicked');
      }
      e.target.classList.add('clicked');
      last = e.target;
    });

  });
}(window, document));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.lrdiv {
  display: flex;
}

.ldiv,
.rdiv {
  flex: 1;
  text-align: left;
  vertical-align: middle;
  height: 2em;
  line-height: 2em;
}

.rdiv {
  text-align: right;
  padding-left: 0;
}

.upddiv {
  text-align: center;
}

#mapJog {
  padding: 0.5em;
  padding-left: 80%;
  text-align: right;
  border: 1px solid red;
}

#mapJog div:not(.lrdiv) {
  position: relative;
  pointer-events: none;
}
#mapJog div:not(.lrdiv)::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  width: 100%;
  height: 150%;
  border-radius: 50%;
  border: 1px solid red;
  pointer-events: auto;
}
#mapJog div.upddiv::after {
  width: 50%;
  height: 220%;
}
#mapJog div.ldiv::after {
  left: 20%;
}
#mapJog div.rdiv::after {
  left: 80%;
}
#mapJog div.clicked:not(.lrdiv)::after {
  background: yellow;
  z-index: -1;
}</code>```

<meta name='viewport' content='user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height' />

    ▲

      ◄

      ►

    ▼

```

Body:
The context

In a hybrid Android app I am getting images for the current location of the user courtesy of the Google Streetview API.  What I want to be able to do is to provide a set of four buttons pointing to four cardinal directions - I think of these as Up, Down, Left, Right as opposed to North, South etc since the top of the phone screen will not necessarily point "north".  Here is how I have done this for now

.lrdiv{display:flex;}
.ldiv,.rdiv
{
 flex:1;
 text-align:left;
 vertical-align:middle;
 height:2em;
 line-height:2em;
}
.rdiv
{
 text-align:right;
 padding-left:0;
}
.upddiv
{
 text-align:center;
}
#mapJog
{
 padding:0.5em;
 padding-left:80%;
 text-align:right;
 border:1px solid red;
}

<meta name='viewport' content='user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height' />

▲

◄

►

▼

The intent here is to provide a street view 200m to the left/right/above/below the current position depending on which of these buttons is clicked.

The red border has been left in to make the result easier to visualize.  Whilst this is the layout I am after I am concerned that I have not adequately addressed the issue of being able to detect tap events (think fat fingers) on the four buttons at different screen sizes.  Hopefully,someone here will be able to suggest improvements which ensure that this always happens irrespective of screen size.

Body:
The simplest is to use pseudo element to extend an elements clickable area.

(function(w, d, last) {
  w.addEventListener("load", function() {

    d.getElementById('mapJog').addEventListener('click', function(e) {
      if(last) {
        last.classList.remove('clicked');
      }
      e.target.classList.add('clicked');
      last = e.target;
    });

  });
}(window, document));

.lrdiv {
  display: flex;
}

.ldiv,
.rdiv {
  flex: 1;
  text-align: left;
  vertical-align: middle;
  height: 2em;
  line-height: 2em;
}

.rdiv {
  text-align: right;
  padding-left: 0;
}

.upddiv {
  text-align: center;
}

#mapJog {
  padding: 0.5em;
  padding-left: 80%;
  text-align: right;
  border: 1px solid red;
}

#mapJog div:not(.lrdiv) {
  position: relative;
  pointer-events: none;
}
#mapJog div:not(.lrdiv)::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  width: 100%;
  height: 150%;
  border-radius: 50%;
  border: 1px solid red;
  pointer-events: auto;
}
#mapJog div.upddiv::after {
  width: 50%;
  height: 220%;
}
#mapJog div.ldiv::after {
  left: 20%;
}
#mapJog div.rdiv::after {
  left: 80%;
}
#mapJog div.clicked:not(.lrdiv)::after {
  background: yellow;
  z-index: -1;
}

<meta name='viewport' content='user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height' />

<div id='mapJog'>
  <div class='upddiv'>
    &#9650;
  </div>
  <div class='lrdiv'>
    <div class='ldiv'>
      &#9668;
    </div>
    <div class='rdiv'>
      &#9658;
    </div>
  </div>
  <div class='upddiv'>
    &#9660;
  </div>
</div>


问:
google static maps with enc path is not always working
i have implement a static map that show a route based on

```<code>routes[0]->overview_polyline
</code>```

and i also have add the start and end markers

The problem is that is not always working and i assume that there is a problem with overview_polyline but i can not figure out

This is a working static map that show both markets and route

```<code>https://maps.googleapis.com/maps/api/staticmap?size=650x400&path=enc:q|wfFs}yoCuEhLyC`Gk@rI{@pLoF|LyEiAaHrE{VlPzAxNsAnK{Plc@gl@jbAon@|sAuN~b@uRr\}Rl\iIxWbCr}@fG`d@iJnp@{Ez]v@nhA~ItjAgGzn@}Ib[wQfAit@vAcf@rOig@h\wWpc@ie@~uAmF~aAtRrbAsLdVgZf_@_LjrAuEjp@^|_@n^fr@`_@pi@h\|Z|y@|`@rRhZ?~a@sGz\nLjiB~Yh`Cvr@vqBjc@`qAf^xoBvXfoAp|@bdBht@xwAhC~ZqAb^aGlt@fHbe@jp@rfAfE`a@oBna@cMlr@aXljATnx@xIbp@dA~r@_Ghm@jKds@`O~z@nAj|@tP`h@|nAvrCz]fw@hIx^nLzu@|Nz[jZjl@vh@ndAny@n_Btv@n}AQfl@{Rfm@wTl`@eQdv@Cni@nGjb@zL|k@~Afj@iCva@eJblDrE`n@`Mbe@eAxUiJxTHj\`Oh_@nRtcA?lWsJpq@wJfy@w@rt@pG|w@zGfh@`FfqCpSl{BnWvzAxLt{@tD~}@]`|@cGxj@}Ujy@_Uv^yUt|@oHdk@{^xbBap@jkB{\bu@gYd`@wd@`c@}_@`Wid@lR_b@rD}SfU{b@rXgh@p[wVw@giAZe\{BwNXq^xNm|@~^em@nd@uiAr{Au_@hrA}Zf}@g]p}@eKp^eBxd@wGrWcQjPwNbP{ElV}o@v}Bl@hh@cArn@cO`d@mNv^wBnU}Wtw@sM|[yAvTyKl^ae@|y@mM|k@aOb`@cGvd@{Wr}Agr@foAkk@p}@ij@pw@aZfr@^lm@hAzbAd\lkB{Krs@oMrXeNpj@}Jh`AbCpQfS`s@`Avj@_]``Cwh@rbA?hc@wTty@iSffAs]`n@{Xd\cg@zb@ai@lhAc@n_AyBlpAwCfx@~Frd@xNpb@y@~kAsFjZuYn_@uFp[v@fZcGjs@{F`j@cGdxAeXjyA{Kx{@}HjaAiAde@sOr[}IvzAe[`c@iNpNu[h^mM`ZmNlXgJfY{ZfeAwWzkA}h@rjAqt@j}Ak]j]qr@j\qk@dTg\`g@wNtJuWzUma@n~@iUpd@_Wz[iE~S{Gld@yEpMuRzIuVpNmp@nvAeYll@{_@vWuNtZaa@jq@oYv_@qf@tsA}Nli@mAlXeHd|@xHv^uAjx@lLl\|Bhf@iCli@xGpi@}If{@fFn[d@py@uFd|@vCftAq@h`@vBhb@tB`m@jUrj@rZ|WrOjb@rJji@rPte@h`@f|@dq@lwAjXtm@dY|^ti@|m@veAzbAb}@ri@fKxH_CtQ^f@bWzHlQfPrQzY&markers=color:green|label:A|37.9746479,23.73097699999994&markers=color:red|label:B|38.24670270000001,21.7345758000000162
</code>```

This route is not working

```<code>https://maps.googleapis.com/maps/api/staticmap?size=650x400&path=enc:q|wfFs…n@y@zHc@hCg@jCmASUnDUbDc@tGWzCEp@MxBSnBCRM?uDlCkA{AY_@[c@IHmAjA[^e@Z}At@aC`BeIvFu@^cBfA{GlEKF\fCb@lDXpBJhAE~@[rBMv@c@bDgAvIW~@aA~BKPcBjDoAbCsA~BeCrDeEnG}D~GmDdGeE~G}F~J{B~D}DzGUNUZ_A~AaHjLIXAf@Bf@H^^t@FR@PbDrDpDvEbAlAjAvApD`E~@`A`KrLX\v@|@vCjDr@t@`Av@rKxGnEpCfFjDtHdFbC~AhAn@lFdD~E~CpMjIzBtAn@b@lIpFlC~A\LnBp@j@JbAFrB?|Ba@bBm@vBkAdG}C`@WvBwAxAgAxAaAbAk@p@Wp@Mz@G^AdAHpCt@t@Vh@V|J`DlHbCpKnDbBd@lB^~Bd@rCr@|HzBzIhCfAXfAP`F^z@FbEVhDJnJFlGBjC@d@Ln@?ZHb@V^j@Jb@Fr@?bA?bGEpBAzNE|DPzK@zAAr@KfASx@a@z@mDbGyGfLeBzCs@~Am@fB{@bE_@|Bw@dJ]xENd@@l@FbBDz@DN`@P`Bx@lCtAlD~AdAd@vA|@vIhHvAdA^Vx@n@CH&markers=color:green|label:A|37.9746479,23.73097699999994&markers=color:red|label:B|37.9429712,23.646971099999973
</code>```

Its only displays the markers without the route

i have implement the code from here
Google static maps with directions

Can any help me make this work, any help appreciated

答:
When I check the encoded polyline from the second example in the Interactive Polyline encoder utility

https://developers.google.com/maps/documentation/utilities/polylineutility

I can see that the route is located somewhere in the sea as shown in the screenshot

Can you post the original Directions API request that returns this encoded polyline, please?

Body:
i have implement a static map that show a route based on

routes[0]->overview_polyline

and i also have add the start and end markers

The problem is that is not always working and i assume that there is a problem with overview_polyline but i can not figure out

This is a working static map that show both markets and route

https://maps.googleapis.com/maps/api/staticmap?size=650x400&path=enc:q|wfFs}yoCuEhLyC`Gk@rI{@pLoF|LyEiAaHrE{VlPzAxNsAnK{Plc@gl@jbAon@|sAuN~b@uRr\}Rl\iIxWbCr}@fG`d@iJnp@{Ez]v@nhA~ItjAgGzn@}Ib[wQfAit@vAcf@rOig@h\wWpc@ie@~uAmF~aAtRrbAsLdVgZf_@_LjrAuEjp@^|_@n^fr@`_@pi@h\|Z|y@|`@rRhZ?~a@sGz\nLjiB~Yh`Cvr@vqBjc@`qAf^xoBvXfoAp|@bdBht@xwAhC~ZqAb^aGlt@fHbe@jp@rfAfE`a@oBna@cMlr@aXljATnx@xIbp@dA~r@_Ghm@jKds@`O~z@nAj|@tP`h@|nAvrCz]fw@hIx^nLzu@|Nz[jZjl@vh@ndAny@n_Btv@n}AQfl@{Rfm@wTl`@eQdv@Cni@nGjb@zL|k@~Afj@iCva@eJblDrE`n@`Mbe@eAxUiJxTHj\`Oh_@nRtcA?lWsJpq@wJfy@w@rt@pG|w@zGfh@`FfqCpSl{BnWvzAxLt{@tD~}@]`|@cGxj@}Ujy@_Uv^yUt|@oHdk@{^xbBap@jkB{\bu@gYd`@wd@`c@}_@`Wid@lR_b@rD}SfU{b@rXgh@p[wVw@giAZe\{BwNXq^xNm|@~^em@nd@uiAr{Au_@hrA}Zf}@g]p}@eKp^eBxd@wGrWcQjPwNbP{ElV}o@v}Bl@hh@cArn@cO`d@mNv^wBnU}Wtw@sM|[yAvTyKl^ae@|y@mM|k@aOb`@cGvd@{Wr}Agr@foAkk@p}@ij@pw@aZfr@^lm@hAzbAd\lkB{Krs@oMrXeNpj@}Jh`AbCpQfS`s@`Avj@_]``Cwh@rbA?hc@wTty@iSffAs]`n@{Xd\cg@zb@ai@lhAc@n_AyBlpAwCfx@~Frd@xNpb@y@~kAsFjZuYn_@uFp[v@fZcGjs@{F`j@cGdxAeXjyA{Kx{@}HjaAiAde@sOr[}IvzAe[`c@iNpNu[h^mM`ZmNlXgJfY{ZfeAwWzkA}h@rjAqt@j}Ak]j]qr@j\qk@dTg\`g@wNtJuWzUma@n~@iUpd@_Wz[iE~S{Gld@yEpMuRzIuVpNmp@nvAeYll@{_@vWuNtZaa@jq@oYv_@qf@tsA}Nli@mAlXeHd|@xHv^uAjx@lLl\|Bhf@iCli@xGpi@}If{@fFn[d@py@uFd|@vCftAq@h`@vBhb@tB`m@jUrj@rZ|WrOjb@rJji@rPte@h`@f|@dq@lwAjXtm@dY|^ti@|m@veAzbAb}@ri@fKxH_CtQ^f@bWzHlQfPrQzY&markers=color:green|label:A|37.9746479,23.73097699999994&markers=color:red|label:B|38.24670270000001,21.7345758000000162

This route is not working

https://maps.googleapis.com/maps/api/staticmap?size=650x400&path=enc:q|wfFs…n@y@zHc@hCg@jCmASUnDUbDc@tGWzCEp@MxBSnBCRM?uDlCkA{AY_@[c@IHmAjA[^e@Z}At@aC`BeIvFu@^cBfA{GlEKF\fCb@lDXpBJhAE~@[rBMv@c@bDgAvIW~@aA~BKPcBjDoAbCsA~BeCrDeEnG}D~GmDdGeE~G}F~J{B~D}DzGUNUZ_A~AaHjLIXAf@Bf@H^^t@FR@PbDrDpDvEbAlAjAvApD`E~@`A`KrLX\v@|@vCjDr@t@`Av@rKxGnEpCfFjDtHdFbC~AhAn@lFdD~E~CpMjIzBtAn@b@lIpFlC~A\LnBp@j@JbAFrB?|Ba@bBm@vBkAdG}C`@WvBwAxAgAxAaAbAk@p@Wp@Mz@G^AdAHpCt@t@Vh@V|J`DlHbCpKnDbBd@lB^~Bd@rCr@|HzBzIhCfAXfAP`F^z@FbEVhDJnJFlGBjC@d@Ln@?ZHb@V^j@Jb@Fr@?bA?bGEpBAzNE|DPzK@zAAr@KfASx@a@z@mDbGyGfLeBzCs@~Am@fB{@bE_@|Bw@dJ]xENd@@l@FbBDz@DN`@P`Bx@lCtAlD~AdAd@vA|@vIhHvAdA^Vx@n@CH&markers=color:green|label:A|37.9746479,23.73097699999994&markers=color:red|label:B|37.9429712,23.646971099999973

Its only displays the markers without the route

i have implement the code from here
Google static maps with directions

Can any help me make this work, any help appreciated


问:
Understanding std::map::find
I am trying to learn how to use std::map with functions. I am a bit confused about how std::map::find works in this regard. Here is a simple code where I use a Lambda function along with map.

```<code>auto Lambda = [](const int&a, const int& b) {
 cout << "\n Inside lambda \n";
 return a < b;
 };

std::map<int, int, decltype(Lambda)> expt(Lambda);
expt[1] = 2;
expt[10] = 12;
auto search1 = expt.find(1);
auto search10 = expt.find(10);
if(search1 != expt.end()) {
    std::cout << "Found " << search1->first << " " << search1->second << '\n';
}
else {
    std::cout << "Not found\n";
}
</code>```

Here is the output that I get:

```<code>Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Found 1 2
</code>```

I am a bit confused about how find actually works in this case. Why do I get 7 calls of the lambda function even though I just have 2 keys in my map?

答:
operator < cannot tell you that two things are equal in one go. You need to call both x < y and y < x in order to verify that x == y. So each time map actually finds a key, it compares the argument and the found key twice, once normally and once swapped around.

This accounts for double occurrence of lambda(1,1) and lambda(10,10).

As for lambda(10,1) and lambda(1,10) when inserting an element with the key of 10, this is needed because map may have to call comparison twice also when it fails to find a key (swap order of insertions to see that).

Title: Understanding std::map::find

Body:
I am trying to learn how to use std::map with functions. I am a bit confused about how std::map::find works in this regard. Here is a simple code where I use a Lambda function along with map.

auto Lambda = [](const int&a, const int& b) {
 cout << "\n Inside lambda \n";
 return a < b;
 };

std::map<int, int, decltype(Lambda)> expt(Lambda);
expt[1] = 2;
expt[10] = 12;
auto search1 = expt.find(1);
auto search10 = expt.find(10);
if(search1 != expt.end()) {
    std::cout << "Found " << search1->first << " " << search1->second << '\n';
}
else {
    std::cout << "Not found\n";
}

Here is the output that I get:

Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Found 1 2

I am a bit confused about how find actually works in this case. Why do I get 7 calls of the lambda function even though I just have 2 keys in my map?


问:
Making a normal "submit" button that will get me to the "div id="example"
Is it possible to make a submit button that when I click it, it will get me to the for example
 without Javascript? I already tried with different ways but as always the first page is showing all tags from other ID's page's. I already have the Javascript code but I don't want to use, I want to do all this by simple HTML tags, if possible please help.

答:
Give your div an id such as

```<code><div id="#home">
</code>```

and then the link should link to the #home.

```<code><a href="#home">
</code>```

That should work

Try it here
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_href_anchor

Body:
Give your div an id such as

<div id="#home">

and then the link should link to the #home.

<a href="#home">

That should work

Try it here
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_href_anchor


问:
ES6 getter/setter with arrow function
I'm using babel6 and for my pet project I'm creating a wrapper for XMLHttpRequest, for the methods I can use:

```<code>open = (method, url, something) => {
  return this.xhr.open(method, url, something);
}
</code>```

but for the properties arrow function doesn't work

this works:

```<code>get status() { return this.xhr.status; }
</code>```

but I can not use

```<code>get status = () => this.xhr.status;
</code>```

Is this intentional?

答:
The accepted answer is great. It's the best if you're willing to use normal function syntax/ object initialization/MethodDefinition syntax like get NAME () { BODY } instead of compact "arrow function syntax".

But maybe you really like arrow functions; maybe you use the arrow function for another reason which a normal function syntax cannot replace; you may need a different solution.

For example,  I notice OP uses this, you may want to bind this lexically; aka "non-binding of this"), and arrow functions are good for that lexical binding.

You can still use an arrow function with a getter via the Object.defineProperty technique.

```<code>{
  ...
  Object.defineProperty(your_obj, 'status', {
     get : () => this.xhr.status
  });
  ...
}
</code>```

See mentions of object initialization technique (aka get NAME() {...}) vs the defineProperty technique (aka get : ()=>{}). There is at least one significant difference, using defineProperty requires the variables already exists:

Defining a getter on existing objects

i.e.  with Object.defineProperty you must ensure that your_obj (in my example) exists and is saved into a variable (whereas with a object-initialization you could return an object-literal in your object initialization: {..., get(){ }, ... }). More info on Object.defineProperty specifically, here

As one commenter says, Object.defineProperty(...) is also nice because you can run the code in a loop (i.e. defie multiple properties)

Object.defineProperty(...) seems to have comparable browser support to the get NAME(){...} syntax; modern browsers, IE 9.

Title: ES6 getter/setter with arrow function

Body:
I'm using babel6 and for my pet project I'm creating a wrapper for XMLHttpRequest, for the methods I can use:

open = (method, url, something) => {
  return this.xhr.open(method, url, something);
}

but for the properties arrow function doesn't work

this works:

get status() { return this.xhr.status; }

but I can not use

get status = () => this.xhr.status;

Is this intentional?

Body:
The accepted answer is great. It's the best if you're willing to use normal function syntax/ object initialization/MethodDefinition syntax like get NAME () { BODY } instead of compact "arrow function syntax".

But maybe you really like arrow functions; maybe you use the arrow function for another reason which a normal function syntax cannot replace; you may need a different solution.

For example,  I notice OP uses this, you may want to bind this lexically; aka "non-binding of this"), and arrow functions are good for that lexical binding.

You can still use an arrow function with a getter via the Object.defineProperty technique.

{
  ...
  Object.defineProperty(your_obj, 'status', {
     get : () => this.xhr.status
  });
  ...
}

See mentions of object initialization technique (aka get NAME() {...}) vs the defineProperty technique (aka get : ()=>{}). There is at least one significant difference, using defineProperty requires the variables already exists:

Defining a getter on existing objects

i.e.  with Object.defineProperty you must ensure that your_obj (in my example) exists and is saved into a variable (whereas with a object-initialization you could return an object-literal in your object initialization: {..., get(){ }, ... }). More info on Object.defineProperty specifically, here

As one commenter says, Object.defineProperty(...) is also nice because you can run the code in a loop (i.e. defie multiple properties)

Object.defineProperty(...) seems to have comparable browser support to the get NAME(){...} syntax; modern browsers, IE 9.

ContentLicense: CC BY-SA 4.0


问:
TimeoutException connecting to Oracle XE 11 via JDBC
I am trying to coax Oracle XE into accepting connections from JDBC. I use ojdbc6.jar from the XE installation (there are the ojdbc5 and ojdbc6_g jars also). I have tried with oracle.jdbc.OracleDriver and oracle.jdbc.driver.OracleDriver, the driver class is registered. I use the descriptor: jdbc:oracle:thin:@localhost:1521:XE.

I have also tried ending with /XE instead of :XE, which I have seen at times. Also tried actual hostname Kaveri instead of localhost.

I can log on with sqlplus, the database is open and the main service and TNS listener service are running.

listener.ora:

```<code>SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
  (SID_NAME = PLSExtProc)
  (ORACLE_HOME = E:\Data\OracleXE\app\oracle\product\11.2.0\server)
  (PROGRAM = extproc)
)
(SID_DESC =
  (SID_NAME = CLRExtProc)
  (ORACLE_HOME = E:\Data\OracleXE\app\oracle\product\11.2.0\server)
  (PROGRAM = extproc)
)
)

LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
  (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
  (ADDRESS = (PROTOCOL = TCP)(HOST = Kaveri)(PORT = 1521))
)
)

DEFAULT_SERVICE_LISTENER = (XE)
</code>```

tsnames.ora:

```<code>XE =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = Kaveri)(PORT = 1521))
(CONNECT_DATA =
  (SERVER = DEDICATED)
  (SERVICE_NAME = XE)
)
)

EXTPROC_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
  (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
)
(CONNECT_DATA =
  (SID = PLSExtProc)
  (PRESENTATION = RO)
)
)

ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
  (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
)
(CONNECT_DATA =
  (SID = CLRExtProc)
  (PRESENTATION = RO)
)
)
</code>```

I get

```<code>java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(Unknown Source)
at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand.awaitConnection(OpenConnectionCommand.java:132)
at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand.access$100(OpenConnectionCommand.java:45)
at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand$2.run(OpenConnectionCommand.java:115)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code>```

Alternatively using a java program of our own I get

```<code>java.sql.SQLRecoverableException: IO Error: Socket read timed out
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:673)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:715)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:385)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:30)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:564)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
...
Caused by: oracle.net.ns.NetException: Socket read timed out
at oracle.net.ns.Packet.receive(Packet.java:350)
at oracle.net.ns.NSProtocolStream.negotiateConnection(NSProtocolStream.java:153)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:263)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1360)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:486)
... 39 more
</code>```

lsnrctl seems to hang after a while:

```<code>> lsnrctl status

LSNRCTL for 64-bit Windows: Version 11.2.0.2.0 - Production on 04-JUL-2017
17:29:09

Copyright (c) 1991, 2014, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
TNS-12560: TNS:protocol adapter error
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=Kaveri)(PORT=1521)))
</code>```

This is a "fresh reinstallation" of Oracle XE on Windows 10. For the avoidance of doubt, I switched off firewall too, with no effect (I hope!).

How does one debug connecting to Oracle? Thank you.

UPDATE: I was lying - or Windows was - when it lists the TNSListener as running, the situation is actually "The OracleXETNSListener service on Local Computer started and then stopped..."

答:
If I use localhost instead of Kaveri in the configuration files, then the listener stays up (why, as the hostname is Kaveri..?)

After that Bob 1174's answer here is what was needed.

Body:
I am trying to coax Oracle XE into accepting connections from JDBC. I use ojdbc6.jar from the XE installation (there are the ojdbc5 and ojdbc6_g jars also). I have tried with oracle.jdbc.OracleDriver and oracle.jdbc.driver.OracleDriver, the driver class is registered. I use the descriptor: jdbc:oracle:thin:@localhost:1521:XE.

I have also tried ending with /XE instead of :XE, which I have seen at times. Also tried actual hostname Kaveri instead of localhost.

I can log on with sqlplus, the database is open and the main service and TNS listener service are running.

listener.ora:

SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
  (SID_NAME = PLSExtProc)
  (ORACLE_HOME = E:\Data\OracleXE\app\oracle\product\11.2.0\server)
  (PROGRAM = extproc)
)
(SID_DESC =
  (SID_NAME = CLRExtProc)
  (ORACLE_HOME = E:\Data\OracleXE\app\oracle\product\11.2.0\server)
  (PROGRAM = extproc)
)
)

LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
  (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
  (ADDRESS = (PROTOCOL = TCP)(HOST = Kaveri)(PORT = 1521))
)
)

DEFAULT_SERVICE_LISTENER = (XE)

tsnames.ora:

XE =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = Kaveri)(PORT = 1521))
(CONNECT_DATA =
  (SERVER = DEDICATED)
  (SERVICE_NAME = XE)
)
)

EXTPROC_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
  (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
)
(CONNECT_DATA =
  (SID = PLSExtProc)
  (PRESENTATION = RO)
)
)

ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
  (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
)
(CONNECT_DATA =
  (SID = CLRExtProc)
  (PRESENTATION = RO)
)
)

I get

java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(Unknown Source)
at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand.awaitConnection(OpenConnectionCommand.java:132)
at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand.access$100(OpenConnectionCommand.java:45)
at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand$2.run(OpenConnectionCommand.java:115)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Alternatively using a java program of our own I get

java.sql.SQLRecoverableException: IO Error: Socket read timed out
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:673)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:715)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:385)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:30)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:564)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
...
Caused by: oracle.net.ns.NetException: Socket read timed out
at oracle.net.ns.Packet.receive(Packet.java:350)
at oracle.net.ns.NSProtocolStream.negotiateConnection(NSProtocolStream.java:153)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:263)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1360)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:486)
... 39 more

lsnrctl seems to hang after a while:

> lsnrctl status

LSNRCTL for 64-bit Windows: Version 11.2.0.2.0 - Production on 04-JUL-2017
17:29:09

Copyright (c) 1991, 2014, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
TNS-12560: TNS:protocol adapter error
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=Kaveri)(PORT=1521)))

This is a "fresh reinstallation" of Oracle XE on Windows 10. For the avoidance of doubt, I switched off firewall too, with no effect (I hope!).

How does one debug connecting to Oracle? Thank you.

UPDATE: I was lying - or Windows was - when it lists the TNSListener as running, the situation is actually "The OracleXETNSListener service on Local Computer started and then stopped..."