问:
How do you check for user input without using input in Python
I am trying to make it so that the while loop stops when you press c without stopping it using input.

The code I have at the moment is this:

```<code>    while True:
        print("Test")
        if msvcrt.kbhit():
            if (msvcrt.getch() == "c"):
                os._exit(0)
                break
            elif (msvcrt.getch() != "c"):
                continue
</code>```

FYI I am on windows.
Any ideas on how to do it besides the attempt I have already done?

答:
The problem is in the line if (msvcrt.getch() == "c"):.

You don't use getch() == "c" but getch() == 99 or but getch() == ord("c").

Why? Because it's what ord() returns. It returns an integer representing the Unicode code point of the only character in the string, in this case c.

By the way, Python already has KeyboardInterrupt that allows using Ctrl+C for interrupting code. You can also try-except it.

Note: You may also want to use 67 for if Caps Lock is on.

Body:
I am trying to make it so that the while loop stops when you press c without stopping it using input.

The code I have at the moment is this:

    while True:
        print("Test")
        if msvcrt.kbhit():
            if (msvcrt.getch() == "c"):
                os._exit(0)
                break
            elif (msvcrt.getch() != "c"):
                continue

FYI I am on windows.
Any ideas on how to do it besides the attempt I have already done?


来源: stackexchange

问:
Not able to track htaccess issue, How to implement IF ELSE in htaccess
I have a problem with htaccess to execute a rule and if rule matches then do not check for another rule. which i am trying to figure out from last few hours. Below is the sample code

```<code><IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_URI} ^/projectname/$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f

   RewriteCond %{REQUEST_URI}  projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/storage/$1 [L]

   Rewritecond %{REQUEST_URI} projectname/(.*)$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$ [NC]
   RewriteCond %{REQUEST_URI}  !\.(html?|png|woff|ttf|eot|svg|woff2|jpg|gif|xml|rss|png|css|js|json)$ [NC]
   RewriteRule ^(.*)$ /projectname/#/$1 [NE,R=301,L]
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]
</code>```

I want to load everything from projectname/abc/dist folder but not for the case when i have storage inside url then i want to load the data from storage folder only.
So as per rules defined here everything works fine but when i have storage inside url/src for image it still checks /projectname/abc/dist/storage/xxxx.png instead of checking  /projectname/storage/xxxx.png as defined in htaccess rule.

I have tried using [S=5] skip with storage rule in htaccess does not works from reference http://httpd.apache.org/docs/2.4/rewrite/flags.html.

Also as per my understanding [L] is the last so it should stop the htaccess after storage rule but it does not.

I have tried implementing IF ELSE in htaccess but the examples i tried for IF ELSE does not help even.
reference https://blogs.apache.org/httpd/entry/new_in_httpd_2_4
reference http://httpd.apache.org/docs/2.4/rewrite/flags.html (check Skip IF ELSE stanza)

Any Idea would be useful.

答:
First of all, L|last doesn't mean stop all processing.

If you are using RewriteRule in either .htaccess files or in  sections, it is important to have some understanding of how the rules are processed. The simplified form of this is that once the rules have been processed, the rewritten request is handed back to the URL parsing engine to do what it may with it.

See also Ruleset Processing for how this works.

To load from /project/abc/dist, except when there's storage in the URL, you must first check for storage

```<code>RewriteCond %{REQUEST_URI} /storage/
RewriteRule /([^/]*$ /project/storage/$1 [L]
</code>```

And then

```<code>RewriteRule ^(.*)$ /project/abc/dist/$1 [L]
</code>```

Finally, to prevent a rewrite loop, prefix the rules with

```<code>RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
</code>```

Everything together

```<code>RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} /storage/
RewriteRule /([^/]*$ /project/storage/$1 [L]

RewriteRule ^(.*)$ /project/abc/dist/$1 [L]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with htaccess to execute a rule and if rule matches then do not check for another rule. which i am trying to figure out from last few hours. Below is the sample code

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_URI} ^/projectname/$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f

   RewriteCond %{REQUEST_URI}  projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/storage/$1 [L]

   Rewritecond %{REQUEST_URI} projectname/(.*)$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$ [NC]
   RewriteCond %{REQUEST_URI}  !\.(html?|png|woff|ttf|eot|svg|woff2|jpg|gif|xml|rss|png|css|js|json)$ [NC]
   RewriteRule ^(.*)$ /projectname/#/$1 [NE,R=301,L]
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]

I want to load everything from projectname/abc/dist folder but not for the case when i have storage inside url then i want to load the data from storage folder only.
So as per rules defined here everything works fine but when i have storage inside url/src for image it still checks /projectname/abc/dist/storage/xxxx.png instead of checking  /projectname/storage/xxxx.png as defined in htaccess rule.

I have tried using [S=5] skip with storage rule in htaccess does not works from reference http://httpd.apache.org/docs/2.4/rewrite/flags.html.

Also as per my understanding [L] is the last so it should stop the htaccess after storage rule but it does not.

I have tried implementing IF ELSE in htaccess but the examples i tried for IF ELSE does not help even.
reference https://blogs.apache.org/httpd/entry/new_in_httpd_2_4
reference http://httpd.apache.org/docs/2.4/rewrite/flags.html (check Skip IF ELSE stanza)

Any Idea would be useful.

Body:
First of all, L|last doesn't mean stop all processing.

If you are using RewriteRule in either .htaccess files or in  sections, it is important to have some understanding of how the rules are processed. The simplified form of this is that once the rules have been processed, the rewritten request is handed back to the URL parsing engine to do what it may with it.

See also Ruleset Processing for how this works.

To load from /project/abc/dist, except when there's storage in the URL, you must first check for storage

RewriteCond %{REQUEST_URI} /storage/
RewriteRule /([^/]*$ /project/storage/$1 [L]

And then

RewriteRule ^(.*)$ /project/abc/dist/$1 [L]

Finally, to prevent a rewrite loop, prefix the rules with

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

Everything together

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} /storage/
RewriteRule /([^/]*$ /project/storage/$1 [L]

RewriteRule ^(.*)$ /project/abc/dist/$1 [L]


问:
Display to Raspberry Pi HDMI From Raspberry Pi Camera using C++
Question: How do I write video stream from Raspberry Pi camera to HDMI connected display?

Answer: see below

答:
My system: Raspberry Pi3, Raspbian Jessie distribution
VisualGDB and VisualStudio 2015

Spending a few hours putting together various test code from different posts, I'm posting this compiled test code for the community to use. It works ~ 15fps with 1200x720p color video output.

Sources:
https://raspberrypi.stackexchange.com/questions/7092/display-a-test-pattern-by-writing-the-frame-buffer-and-then-clear-it

https://visualgdb.com/tutorials/raspberry/camera/

NOTES:
VisualGDB has some issues with Sysroot syncing, when I ran the built-in operation from Visual Studio, it copied a bunch of headers with size 0. Instead, I manually copied the /opt/vc folder to C:\SysGCC\raspberry\arm-linux-gnueabihf\sysroot directly

I also had to copy libbcm_host.so (along with libraspicam.so.0.1 as in the linked tutorial) from /opt/vc/lib to local build/Debug/src folder,

And add =/opt/vc/include to includes (= indicates local sysroom directory)
And bcm_host to library names.

NOTE2: Either Raspbian distro or the compiler do not like while(1) loops, so if you replace the for(...) loop for drawing frames with a while(1) without any exit conditions, you will get a black screen for output. Probable cause is the optimizer, good practice is to just avoid having infinite loops without an exit condition altogether.

NOTE3: If using HDMI output to monitor with less than 1280x720 resolution (less than camera video stream), some issues may occur, looking for someone to edit the code for smaller screens. Older versions of RPi with Composite video output are also not tested.

Thanks,

```<code>#include <stdio.h>
#include <syslog.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include "interface\vmcs_host\vc_dispmanx_types.h"
#include <bcm_host.h>
#include "raspicam.h"
#include <iostream>

typedef struct
{
    DISPMANX_DISPLAY_HANDLE_T   display;
    DISPMANX_MODEINFO_T         info;
    void                        *image;
    DISPMANX_UPDATE_HANDLE_T    update;
    DISPMANX_RESOURCE_HANDLE_T  resource;
    DISPMANX_ELEMENT_HANDLE_T   element;
    uint32_t                    vc_image_ptr;

} RECT_VARS_T;

int main(int argc, char **argv)
{
    RECT_VARS_T vars;
    VC_RECT_T src_rect;
    VC_RECT_T dst_rect;
    VC_DISPMANX_ALPHA_T alpha = {
        static_cast<DISPMANX_FLAGS_ALPHA_T>(DISPMANX_FLAGS_ALPHA_FROM_SOURCE | DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS),
        255, /*alpha 0->255*/
        0
    };

    bcm_host_init();

    vars.display = vc_dispmanx_display_open(0);
    vc_dispmanx_display_get_info(vars.display, &vars.info);

    //Grab Camera feed
    raspicam::RaspiCam v_camera; //camera object
    //Open camera
    std::cout << "Opening Camera..." << std::endl;
    if (!v_camera.open())
    {
        std::cerr << "Error opening camera" << std::endl;
        return -1;
    }
    //may need to wait a while until camera stabilizes

    int cam_width = v_camera.getWidth();
    int cam_height = v_camera.getHeight();

    vars.image = calloc(1, cam_width * cam_height * 3);
    vars.resource = vc_dispmanx_resource_create( VC_IMAGE_RGB888,
        cam_width,
        cam_height,
        &vars.vc_image_ptr);

    vc_dispmanx_rect_set(&dst_rect, 0, 0, cam_width, cam_height);
    vars.update = vc_dispmanx_update_start(10);
    vars.element = vc_dispmanx_element_add( vars.update,
        vars.display,
        2000, // layer
        &dst_rect,
        vars.resource,
        &src_rect, //may not need this
        DISPMANX_PROTECTION_NONE,
        &alpha,
        NULL, // clamp
        static_cast<DISPMANX_TRANSFORM_T>(0));

    //Draw 50 frames to screen
    for (int i = 0; i < 50; i++)
    {
        vc_dispmanx_resource_write_data( vars.resource,
            VC_IMAGE_RGB888,
            cam_width * 3,
            vars.image,
            &dst_rect);

        unsigned char* fbp = static_cast<unsigned char*>(vars.image);
        v_camera.grab();
        v_camera.retrieve(fbp, raspicam::RASPICAM_FORMAT_RGB);//get camera image
        vc_dispmanx_update_submit_sync(vars.update);
    }

    int ret = vc_dispmanx_resource_delete(vars.resource);
    vc_dispmanx_display_close(vars.display);

    return true;
}
</code>```

If you want to perform any image processing, just write directly using fbp pointer inside the loop, for example (not the most efficient method)

```<code>int location_cam = 0;
for (int x = 200; x < 300; x++)
{
    for (int y = 200; y < 300; y++)
    {
        location_cam = (x) * (3) + (y) * cam_width * 3;
        *(fbp + location_cam) = 255;        //red
        *(fbp + location_cam + 1) = 0;     //green
        *(fbp + location_cam + 2) = 0;    //blue
    }
}
</code>```

Body:
My system: Raspberry Pi3, Raspbian Jessie distribution
VisualGDB and VisualStudio 2015

Spending a few hours putting together various test code from different posts, I'm posting this compiled test code for the community to use. It works ~ 15fps with 1200x720p color video output.

Sources:
https://raspberrypi.stackexchange.com/questions/7092/display-a-test-pattern-by-writing-the-frame-buffer-and-then-clear-it

https://visualgdb.com/tutorials/raspberry/camera/

NOTES:
VisualGDB has some issues with Sysroot syncing, when I ran the built-in operation from Visual Studio, it copied a bunch of headers with size 0. Instead, I manually copied the /opt/vc folder to C:\SysGCC\raspberry\arm-linux-gnueabihf\sysroot directly

I also had to copy libbcm_host.so (along with libraspicam.so.0.1 as in the linked tutorial) from /opt/vc/lib to local build/Debug/src folder,

And add =/opt/vc/include to includes (= indicates local sysroom directory)
And bcm_host to library names.

NOTE2: Either Raspbian distro or the compiler do not like while(1) loops, so if you replace the for(...) loop for drawing frames with a while(1) without any exit conditions, you will get a black screen for output. Probable cause is the optimizer, good practice is to just avoid having infinite loops without an exit condition altogether.

NOTE3: If using HDMI output to monitor with less than 1280x720 resolution (less than camera video stream), some issues may occur, looking for someone to edit the code for smaller screens. Older versions of RPi with Composite video output are also not tested.

Thanks,

#include <stdio.h>
#include <syslog.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include "interface\vmcs_host\vc_dispmanx_types.h"
#include <bcm_host.h>
#include "raspicam.h"
#include <iostream>

typedef struct
{
    DISPMANX_DISPLAY_HANDLE_T   display;
    DISPMANX_MODEINFO_T         info;
    void                        *image;
    DISPMANX_UPDATE_HANDLE_T    update;
    DISPMANX_RESOURCE_HANDLE_T  resource;
    DISPMANX_ELEMENT_HANDLE_T   element;
    uint32_t                    vc_image_ptr;

} RECT_VARS_T;

int main(int argc, char **argv)
{
    RECT_VARS_T vars;
    VC_RECT_T src_rect;
    VC_RECT_T dst_rect;
    VC_DISPMANX_ALPHA_T alpha = {
        static_cast<DISPMANX_FLAGS_ALPHA_T>(DISPMANX_FLAGS_ALPHA_FROM_SOURCE | DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS),
        255, /*alpha 0->255*/
        0
    };

    bcm_host_init();

    vars.display = vc_dispmanx_display_open(0);
    vc_dispmanx_display_get_info(vars.display, &vars.info);

    //Grab Camera feed
    raspicam::RaspiCam v_camera; //camera object
    //Open camera
    std::cout << "Opening Camera..." << std::endl;
    if (!v_camera.open())
    {
        std::cerr << "Error opening camera" << std::endl;
        return -1;
    }
    //may need to wait a while until camera stabilizes

    int cam_width = v_camera.getWidth();
    int cam_height = v_camera.getHeight();

    vars.image = calloc(1, cam_width * cam_height * 3);
    vars.resource = vc_dispmanx_resource_create( VC_IMAGE_RGB888,
        cam_width,
        cam_height,
        &vars.vc_image_ptr);

    vc_dispmanx_rect_set(&dst_rect, 0, 0, cam_width, cam_height);
    vars.update = vc_dispmanx_update_start(10);
    vars.element = vc_dispmanx_element_add( vars.update,
        vars.display,
        2000, // layer
        &dst_rect,
        vars.resource,
        &src_rect, //may not need this
        DISPMANX_PROTECTION_NONE,
        &alpha,
        NULL, // clamp
        static_cast<DISPMANX_TRANSFORM_T>(0));

    //Draw 50 frames to screen
    for (int i = 0; i < 50; i++)
    {
        vc_dispmanx_resource_write_data( vars.resource,
            VC_IMAGE_RGB888,
            cam_width * 3,
            vars.image,
            &dst_rect);

        unsigned char* fbp = static_cast<unsigned char*>(vars.image);
        v_camera.grab();
        v_camera.retrieve(fbp, raspicam::RASPICAM_FORMAT_RGB);//get camera image
        vc_dispmanx_update_submit_sync(vars.update);
    }

    int ret = vc_dispmanx_resource_delete(vars.resource);
    vc_dispmanx_display_close(vars.display);

    return true;
}

If you want to perform any image processing, just write directly using fbp pointer inside the loop, for example (not the most efficient method)

int location_cam = 0;
for (int x = 200; x < 300; x++)
{
    for (int y = 200; y < 300; y++)
    {
        location_cam = (x) * (3) + (y) * cam_width * 3;
        *(fbp + location_cam) = 255;        //red
        *(fbp + location_cam + 1) = 0;     //green
        *(fbp + location_cam + 2) = 0;    //blue
    }
}


问:
failed to keep user on the same prompt when they enter the wrong nunber?
we'd like to keep user on the same prompt when they enter the wrong number, we have tried anything_else, and "true", "jump to",  but it messed up, please take a look at the attached to reproduce it, Thanks

pleae enter "how much"

if you enter 6, it will lock the prompt(I assign 1 to 5 to different identification), this behavior is correct .

then enter 2, we will get messed up...

please import this json to reproduce it, thanks
https://drive.google.com/file/d/0B1YdUMoS4l7ub1BZdUg1c1dQeG8/view?usp=sharing

答:
The better form is use the entitie pre-defined by IBM, @sys-number to get numbers from the user input. And you can use  use with conditions and to get the number with context variable too, check the JSON example:

```<code>{
  "context": {
    "number": "<? @sys-number ?>"
  },
  "output": {
    "text": {
      "values": [
        "Now is $hora. Sector please?"
      ],
      "selection_policy": "sequential"
    }
  }
}
</code>```

If user type two or 2, the entitie recognize!

You can use regex expression to obtain only the numbers you have pre-defined too!

How to active: -> Entities -> System Entities -> sys-number = ON:

Obs.: Waiting Watson TRAINNING after you active this entitie.

Example, with sys-number add in your node condition:

```<code>@sys-number:1
</code>```

Check the image:

If user type the number correct:

Check the dialog if user dont type the correct number with true condition:

I did the example for you understand what I do for that:

Download the JSON for verify how to do it with REGEX here.

Download the JSON for verify how to do it with SYS-NUMBER here.

EDIT:

Refer your questions
In this case you can use regex, and use the context variable for make conditions in other node. My workspace with regex can help you with numbers. And, the variable $number you can use in the next node to verify if the user typed correctly the number.

And, the other case is to use the Jump to inside conversation. And use true if the user dont type the number correctly again.

Check my image:

Download the new workspace here.

Study more about conditions here.

Body:
The better form is use the entitie pre-defined by IBM, @sys-number to get numbers from the user input. And you can use  use with conditions and to get the number with context variable too, check the JSON example:

{
  "context": {
    "number": "<? @sys-number ?>"
  },
  "output": {
    "text": {
      "values": [
        "Now is $hora. Sector please?"
      ],
      "selection_policy": "sequential"
    }
  }
}

If user type two or 2, the entitie recognize!

You can use regex expression to obtain only the numbers you have pre-defined too!

How to active: -> Entities -> System Entities -> sys-number = ON:

Obs.: Waiting Watson TRAINNING after you active this entitie.

Example, with sys-number add in your node condition:

@sys-number:1

Check the image:

If user type the number correct:

Check the dialog if user dont type the correct number with true condition:

I did the example for you understand what I do for that:

Download the JSON for verify how to do it with REGEX here.

Download the JSON for verify how to do it with SYS-NUMBER here.

EDIT:

Refer your questions
In this case you can use regex, and use the context variable for make conditions in other node. My workspace with regex can help you with numbers. And, the variable $number you can use in the next node to verify if the user typed correctly the number.

And, the other case is to use the Jump to inside conversation. And use true if the user dont type the number correctly again.

Check my image:

Download the new workspace here.

Study more about conditions here.


问:
how to get git log -p to show changes in merge commits
I have a branch with a function definition missing but the function is still being used causing a crash. The function definition must have been deleted during a merge. I have done 'git log -p' and searched for the function definition and I can see it being defined but couldn't find it being deleted later on. This leads me to believe that 'git log -p' doesn't show merge changes? How can I get this functionality?</p>

答:
This leads me to believe that 'git log -p' doesn't show merge changes? How can I get this functionality?

You are correct: by default, git log -p shows you the merge commit, but does not even attempt to show a diff for it.

As odradek wrote in a comment, adding the -c option will make git log show combined diffs.  You may also use --cc (note two dashes for --cc, vs one dash for -c) which also shows a combined diff, or -m, which effectively splits the merge for diff purposes, and shows one diff per parent, against that parent.

These same three options can be used with git show.  For whatever reason, though, git show defaults to --cc while git log defaults to nothing at all.

The difference between the three options is clear only with some merges, and it's a bit tricky to show them.  We can, however, say one thing pretty clearly: any combined diff shows only files that differ from all parents.  That is, both git show -c and git show --cc trim what's shown to try to be helpful.  (The --cc form may trim more than -c, depending on what there is that can be shown.  I do not have a handy example of this, though.)

For example, consider commit 3e5c63943d35be1804d302c0393affc4916c3dc3 in the Git repository for Git.  This is a merge (with parents c13c783... and 20690b2..., and if we run two separate git diff commands, we can see that, as compared to its first parent, only two files change:

```<code>$ git diff --name-status 3e5c639^1 3e5c639
M       builtin/remote.c
M       t/t5505-remote.sh
</code>```

but as compared to its second parent, many files (including those same two) change:

```<code>$ git diff --name-status 3e5c639^2 3e5c639 | expand
M       .gitignore
M       .mailmap
M       Documentation/Makefile
A       Documentation/RelNotes/2.12.0.txt
M       Documentation/SubmittingPatches
A       Documentation/asciidoctor-extensions.rb
M       Documentation/blame-options.txt
M       Documentation/cat-texi.perl
M       Documentation/config.txt
M       Documentation/diff-config.txt
[snipped here - but the same two files do appear in the 339-entry list]
</code>```

If I run git show --cc on this, I get no diff listing at all; if I run git show -c on it, I get a diff listing for builtin/remote.c and for t/t5505-remote.sh.

If I run git show -m on this, I get instead two separate git diff listings.  Neither is a "combined diff".  The first starts with:

```<code>commit 3e5c63943d35be1804d302c0393affc4916c3dc3 (from
 c13c783c9d3d7d3eff937b7bf3642d2a7fe32644)
</code>```

and shows just the first two files.  The second starts with:

```<code>commit 3e5c63943d35be1804d302c0393affc4916c3dc3 (from
 20690b213975ad3e9b1bc851f434d818bd2d1de9)
</code>```

and shows all 339 files.

Using -m is the Really Big Hammer, but you are left with a lot of sorting to do through a lot of pieces.  Using --cc or -c is usually sufficient.

(Something else that may help, when looking for this sort of change with git log -p, is to add --full-history to make sure that git log follows both branches down each merge.  This is only required if you are doing history simplification by adding -- <path> options.)

Body:
This leads me to believe that 'git log -p' doesn't show merge changes? How can I get this functionality?

You are correct: by default, git log -p shows you the merge commit, but does not even attempt to show a diff for it.

As odradek wrote in a comment, adding the -c option will make git log show combined diffs.  You may also use --cc (note two dashes for --cc, vs one dash for -c) which also shows a combined diff, or -m, which effectively splits the merge for diff purposes, and shows one diff per parent, against that parent.

These same three options can be used with git show.  For whatever reason, though, git show defaults to --cc while git log defaults to nothing at all.

The difference between the three options is clear only with some merges, and it's a bit tricky to show them.  We can, however, say one thing pretty clearly: any combined diff shows only files that differ from all parents.  That is, both git show -c and git show --cc trim what's shown to try to be helpful.  (The --cc form may trim more than -c, depending on what there is that can be shown.  I do not have a handy example of this, though.)

For example, consider commit 3e5c63943d35be1804d302c0393affc4916c3dc3 in the Git repository for Git.  This is a merge (with parents c13c783... and 20690b2..., and if we run two separate git diff commands, we can see that, as compared to its first parent, only two files change:

$ git diff --name-status 3e5c639^1 3e5c639
M       builtin/remote.c
M       t/t5505-remote.sh

but as compared to its second parent, many files (including those same two) change:

$ git diff --name-status 3e5c639^2 3e5c639 | expand
M       .gitignore
M       .mailmap
M       Documentation/Makefile
A       Documentation/RelNotes/2.12.0.txt
M       Documentation/SubmittingPatches
A       Documentation/asciidoctor-extensions.rb
M       Documentation/blame-options.txt
M       Documentation/cat-texi.perl
M       Documentation/config.txt
M       Documentation/diff-config.txt
[snipped here - but the same two files do appear in the 339-entry list]

If I run git show --cc on this, I get no diff listing at all; if I run git show -c on it, I get a diff listing for builtin/remote.c and for t/t5505-remote.sh.

If I run git show -m on this, I get instead two separate git diff listings.  Neither is a "combined diff".  The first starts with:

commit 3e5c63943d35be1804d302c0393affc4916c3dc3 (from
 c13c783c9d3d7d3eff937b7bf3642d2a7fe32644)

and shows just the first two files.  The second starts with:

commit 3e5c63943d35be1804d302c0393affc4916c3dc3 (from
 20690b213975ad3e9b1bc851f434d818bd2d1de9)

and shows all 339 files.

Using -m is the Really Big Hammer, but you are left with a lot of sorting to do through a lot of pieces.  Using --cc or -c is usually sufficient.

(Something else that may help, when looking for this sort of change with git log -p, is to add --full-history to make sure that git log follows both branches down each merge.  This is only required if you are doing history simplification by adding -- <path> options.)


问:
Why was function overloading added to C++?
I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?

What went across the mind of the language designer at that time?

答:
Would you prefer "selecting" one among abs/labs/llabs/fabs/fabsf/fabsl Or just abs()?

Obviously, abs().

So function overloading is a relief for programmers, most of the time, beside other advantages.

ContentLicense: CC BY-SA 2.5


问:
Concatenation of multiple HEX values in C
I have an array in memory that holds certain hex values that describe assembly instructions. For example:

```<code>708877665544332211 = jump 0x1122334455667788
</code>```

70 indicates a jump in assembly and the following hex numbers are what I need to concatenate. I've already tried doing,

```<code>address |= memory[1];
address |= memory[2]<<8;
address |= memory[3]<<16;
address |= memory[4]<<24;
address |= memory[5]<<32;
address |= memory[6]<<40;
address |= memory[7]<<48;
address |= memory[8]<<56;
</code>```

The string that was outputted was:

0x100: 708877665544332211   |   jump 1432778700

Where am I going wrong in the concatenation?

EDIT: Following Benjamin's suggestion, I changed it to:

With print statement printf("APPEND: %016llx", address) to debug, I found that the uint64_t was being changed as:

```<code>APPEND: 0000000000002211
APPEND: 0000000000332211
APPEND: 0000000044332211
APPEND: 0000000044332255
APPEND: 0000000044336655
APPEND: 0000000044776655
</code>```

If the address is a 64bit integer, why does it appear to be behaving as a 32bit integer?

答:
Decimal number 1432778700 in hex is 0x556677CC. This is most probably a problem with the data type of variable 'address'. It has to be able to hold 8 bytes. So you will have to use a data type like unsigned long long int.

Once you have solved that, then you need to know whether the address is stored in memory in little endian or big endian order and process it accordingly.

Update:
Just saw your edited question.
If you expect the following conversion:
708877665544332211 into 0x1122334455667788

then even something like this will work:

```<code>unsigned char bMemory[] = {0x70,0x88,0x77,0x66,0x55,0x44,0x33,0x22,0x11};

int main()
{
    unsigned long long int address = *((unsigned long long int *)(&bMemory[1]));
    printf("\n Address is %llX", address );

    return 0;
}
</code>```

Body:
I have an array in memory that holds certain hex values that describe assembly instructions. For example:

708877665544332211 = jump 0x1122334455667788

70 indicates a jump in assembly and the following hex numbers are what I need to concatenate. I've already tried doing,

address |= memory[1];
address |= memory[2]<<8;
address |= memory[3]<<16;
address |= memory[4]<<24;
address |= memory[5]<<32;
address |= memory[6]<<40;
address |= memory[7]<<48;
address |= memory[8]<<56;

The string that was outputted was:

0x100: 708877665544332211   |   jump 1432778700

Where am I going wrong in the concatenation?

EDIT: Following Benjamin's suggestion, I changed it to:

With print statement printf("APPEND: %016llx", address) to debug, I found that the uint64_t was being changed as:

APPEND: 0000000000002211
APPEND: 0000000000332211
APPEND: 0000000044332211
APPEND: 0000000044332255
APPEND: 0000000044336655
APPEND: 0000000044776655

If the address is a 64bit integer, why does it appear to be behaving as a 32bit integer?

Body:
Decimal number 1432778700 in hex is 0x556677CC. This is most probably a problem with the data type of variable 'address'. It has to be able to hold 8 bytes. So you will have to use a data type like unsigned long long int.

Once you have solved that, then you need to know whether the address is stored in memory in little endian or big endian order and process it accordingly.

Update:
Just saw your edited question.
If you expect the following conversion:
708877665544332211 into 0x1122334455667788

then even something like this will work:

unsigned char bMemory[] = {0x70,0x88,0x77,0x66,0x55,0x44,0x33,0x22,0x11};

int main()
{
    unsigned long long int address = *((unsigned long long int *)(&bMemory[1]));
    printf("\n Address is %llX", address );

    return 0;
}


问:
Silverlight (w/ SQL database) desktop application example?
Are there any freeware/shareware examples of Silverlight desktop applications with a local SQL backend?
I am planning to write a freeware/shareware personal finance application and I'm thinking if whether to do it on Silverlight or WPF.</p>

答:
There is SQLLite port for Silverlight and Sterling object-oriented database with LINQ support (much better for offline storage).

Both use IsolatedStorage, so no bloat WPF is needed.

Ideal for OOB Silverlight applications.


问:
R Leaflet: Is it possible to show polygon label when polygon is not clickable?
I need to show a label of polygon (with the name of the region) when moving the mouse over the polygon. However the polygon can not be clickable since I this property for another part of my code. Is this possible?

If this is not possible, another solution could be to write a name on the polygon. I don't know how to do that either. :/

Here is how my code looks so far

```<code>library(shiny)
library(leaflet)

ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%")
)

# Load shapefiles
shp_Tajo <- readOGR(dsn = "./Data/ES", layer = "Aqueduct_river_basins_TEJO", verbose = FALSE)

server <- function(input, output, session){
output$map <- renderLeaflet({
      # Arguments controlling the looks of the basin polygon
      dopacity = 0.3
      dsmoothFactor = 1
      dfillOpacity = 0.5
      vcolors = c("red")
      leaflet() %>% addTiles() %>% addPolygons(data = shp_Tajo, stroke = F,
opacity = dopacity, smoothFactor = dsmoothFactor, color = vcolors[1], fillColor = vcolors[1],
fillOpacity = dfillOpacity, highlightOptions = highlightOptions(color = "white", weight = 2,
bringToFront = FALSE), options = pathOptions(clickable = FALSE), label = "Tajo",
labelOptions = labelOptions(noHide = T, clickable = T, textOnly = TRUE, opacity=0.5,textsize='15px'))
  })
}
</code>```

The shape file can be downloaded from http://riverbasins.wateractionhub.org/#find_lat_lng
, where you have to choose spain in the drop down menu.

Any help would be greatly appreciated!

答:
By commenting out your pathOptions settings, it works as you intended: you can click anywhere except for the polygon and the label of the polygon is displayed on mouse-over:

Working example:

```<code>library("shiny")
library("rgdal")
library("leaflet")
library("ggmap")

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%")
)

# Load shapefiles
shp_Tajo <- readOGR(dsn = "./Data/ES", layer = "Aqueduct_river_basins_TEJO", verbose = FALSE)

server <- function(input, output, session){
  output$map <- renderLeaflet({
    # Arguments controlling the looks of the basin polygon
    dopacity = 0.3
    dsmoothFactor = 1
    dfillOpacity = 0.5
    vcolors = c("red")
    leaflet() %>%
      addTiles() %>%
      addPolygons(
        data = shp_Tajo
        , stroke = FALSE
        , opacity = dopacity
        , smoothFactor = dsmoothFactor
        , color = vcolors[1]
        , fillColor = vcolors[1]
        , fillOpacity = dfillOpacity
        , highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = FALSE)
        # , options = pathOptions(clickable = FALSE)
        , label = "Tajo"
        , labelOptions = labelOptions(noHide = TRUE, textOnly = TRUE, opacity = 0.5 , textsize='15px'))
  })

  observeEvent(input$map_click, {
    click <- input$map_click
    clat <- click$lat
    clng <- click$lng

    leafletProxy('map') %>%
      addCircles(
        lng = clng
        , lat = clat
        , group = 'circles'
        , weight = 1
        , radius = 5000
        , color = 'black'
        , fillColor = 'orange'
        , fillOpacity = 0.5
        , opacity = 1
        )
  })
}

shinyApp(ui, server)
</code>```

Body:
I need to show a label of polygon (with the name of the region) when moving the mouse over the polygon. However the polygon can not be clickable since I this property for another part of my code. Is this possible?

If this is not possible, another solution could be to write a name on the polygon. I don't know how to do that either. :/

Here is how my code looks so far

library(shiny)
library(leaflet)

ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%")
)

# Load shapefiles
shp_Tajo <- readOGR(dsn = "./Data/ES", layer = "Aqueduct_river_basins_TEJO", verbose = FALSE)

server <- function(input, output, session){
output$map <- renderLeaflet({
      # Arguments controlling the looks of the basin polygon
      dopacity = 0.3
      dsmoothFactor = 1
      dfillOpacity = 0.5
      vcolors = c("red")
      leaflet() %>% addTiles() %>% addPolygons(data = shp_Tajo, stroke = F,
opacity = dopacity, smoothFactor = dsmoothFactor, color = vcolors[1], fillColor = vcolors[1],
fillOpacity = dfillOpacity, highlightOptions = highlightOptions(color = "white", weight = 2,
bringToFront = FALSE), options = pathOptions(clickable = FALSE), label = "Tajo",
labelOptions = labelOptions(noHide = T, clickable = T, textOnly = TRUE, opacity=0.5,textsize='15px'))
  })
}

The shape file can be downloaded from http://riverbasins.wateractionhub.org/#find_lat_lng
, where you have to choose spain in the drop down menu.

Any help would be greatly appreciated!

Body:
By commenting out your pathOptions settings, it works as you intended: you can click anywhere except for the polygon and the label of the polygon is displayed on mouse-over:

Working example:

library("shiny")
library("rgdal")
library("leaflet")
library("ggmap")

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%")
)

# Load shapefiles
shp_Tajo <- readOGR(dsn = "./Data/ES", layer = "Aqueduct_river_basins_TEJO", verbose = FALSE)

server <- function(input, output, session){
  output$map <- renderLeaflet({
    # Arguments controlling the looks of the basin polygon
    dopacity = 0.3
    dsmoothFactor = 1
    dfillOpacity = 0.5
    vcolors = c("red")
    leaflet() %>%
      addTiles() %>%
      addPolygons(
        data = shp_Tajo
        , stroke = FALSE
        , opacity = dopacity
        , smoothFactor = dsmoothFactor
        , color = vcolors[1]
        , fillColor = vcolors[1]
        , fillOpacity = dfillOpacity
        , highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = FALSE)
        # , options = pathOptions(clickable = FALSE)
        , label = "Tajo"
        , labelOptions = labelOptions(noHide = TRUE, textOnly = TRUE, opacity = 0.5 , textsize='15px'))
  })

  observeEvent(input$map_click, {
    click <- input$map_click
    clat <- click$lat
    clng <- click$lng

    leafletProxy('map') %>%
      addCircles(
        lng = clng
        , lat = clat
        , group = 'circles'
        , weight = 1
        , radius = 5000
        , color = 'black'
        , fillColor = 'orange'
        , fillOpacity = 0.5
        , opacity = 1
        )
  })
}

shinyApp(ui, server)


问:
Swift UICollectionView Textfields
I have a bunch of UITextFields living inside a collection view in different cells (around 7). I'm looking for a way to delegate the responsibility of validating these fields to an internal service class. Is there a way in which I can do this without causing controller bloat?

What I've partially tried is to create an object and then assign the Textfield delegates to this object. However I struggled on linking the two together (able to access the textField.text property to validate and add the output into a struct).

Is there a cleaner, more efficient way or am I looking at a long Controller?

Thanks

答:
Features

Save data from TextFields in cell

Detect coordinates of editing TextField

Locate TextFields handler in ViewController (MVC)

Hide keyboard when scroll

Details

xCode 8.3, Swift 3.1

Full Example

ViewController.swift

```<code>import UIKit

fileprivate var textFieldsTexts = [IndexPath:String]()

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupCollectionView()
    }
}

extension ViewController: UICollectionViewDataSource {
    func setupCollectionView() {
        collectionView.dataSource = self
        collectionView.delegate = self
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
        cell.textField.placeholder = "\(indexPath)"
        cell.delegate = self
        return cell
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let cell = cell as! CollectionViewCell
        cell.textField.text = textFieldsTexts[indexPath]
    }

    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
}

extension ViewController: CollectionViewCellDelegate {

    func collectionViewCell(valueChangedIn textField: UITextField, delegatedFrom cell: CollectionViewCell) {
        if let indexPath = collectionView.indexPath(for: cell), let text = textField.text {
            print("textField text: \(text) from cell: \(indexPath))")
            textFieldsTexts[indexPath] = text
        }
    }

    func collectionViewCell(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, delegatedFrom cell: CollectionViewCell)  -> Bool {
        print("Validation action in textField from cell: \(String(describing: collectionView.indexPath(for: cell)))")
        return true
    }

}
</code>```

CollectionViewCell.swift

```<code>import UIKit

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var textField: UITextField!
    var delegate: CollectionViewCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        textField.delegate = self
    }

    @IBAction func valueChanged(_ sender: UITextField) {
        delegate?.collectionViewCell(valueChangedIn: textField, delegatedFrom: self)
    }
}

extension CollectionViewCell: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let delegate = delegate {
            return delegate.collectionViewCell(textField: textField, shouldChangeCharactersIn: range, replacementString: string, delegatedFrom: self)
        }
        return true
    }
}
</code>```

CollectionViewCellDelegate.swift

```<code>import UIKit

protocol CollectionViewCellDelegate {
    func collectionViewCell(valueChangedIn textField: UITextField, delegatedFrom cell: CollectionViewCell)
    func collectionViewCell(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, delegatedFrom cell: CollectionViewCell)  -> Bool
}
</code>```

Main.storyboard

```<code><?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12118" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_43143119" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="KWt-KV-A2D">
                                <rect key="frame" x="0.0" y="28" width="375" height="639"/>
                                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                                <collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="WoG-le-dkA">
                                    <size key="itemSize" width="100" height="50"/>
                                    <size key="headerReferenceSize" width="0.0" height="0.0"/>
                                    <size key="footerReferenceSize" width="0.0" height="0.0"/>
                                    <inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
                                </collectionViewFlowLayout>
                                <cells>
                                    <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="CollectionViewCell" id="w5c-mF-XjG" customClass="CollectionViewCell" customModule="stackoverflow_43143119" customModuleProvider="target">
                                        <rect key="frame" x="0.0" y="0.0" width="100" height="50"/>
                                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                        <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
                                            <rect key="frame" x="0.0" y="0.0" width="100" height="50"/>
                                            <autoresizingMask key="autoresizingMask"/>
                                            <subviews>
                                                <textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="text" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="HAy-QM-Eqi">
                                                    <rect key="frame" x="0.0" y="10" width="100" height="30"/>
                                                    <nil key="textColor"/>
                                                    <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                    <textInputTraits key="textInputTraits"/>
                                                    <connections>
                                                        <action selector="valueChanged:" destination="w5c-mF-XjG" eventType="editingChanged" id="qDf-D2-X1l"/>
                                                    </connections>
                                                </textField>
                                            </subviews>
                                        </view>
                                        <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
                                        <constraints>
                                            <constraint firstItem="HAy-QM-Eqi" firstAttribute="centerY" secondItem="w5c-mF-XjG" secondAttribute="centerY" id="JCH-09-Hsr"/>
                                            <constraint firstItem="HAy-QM-Eqi" firstAttribute="leading" secondItem="w5c-mF-XjG" secondAttribute="leading" id="YvF-Qw-sOW"/>
                                            <constraint firstAttribute="trailing" secondItem="HAy-QM-Eqi" secondAttribute="trailing" id="kPK-6X-Aug"/>
                                        </constraints>
                                        <connections>
                                            <outlet property="textField" destination="HAy-QM-Eqi" id="3tf-0f-agX"/>
                                        </connections>
                                    </collectionViewCell>
                                </cells>
                            </collectionView>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="KWt-KV-A2D" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="5Fe-R9-7li"/>
                            <constraint firstItem="KWt-KV-A2D" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="Rjm-Ij-0Pe"/>
                            <constraint firstAttribute="trailing" secondItem="KWt-KV-A2D" secondAttribute="trailing" id="kZ0-HK-x0Z"/>
                            <constraint firstItem="KWt-KV-A2D" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="zQM-Za-bkN"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="collectionView" destination="KWt-KV-A2D" id="SR1-Cn-p5v"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="133.59999999999999" y="137.18140929535232"/>
        </scene>
    </scenes>
</document>
</code>```

Result

Title: Swift UICollectionView Textfields

Body:
Features

Save data from TextFields in cell

Detect coordinates of editing TextField

Locate TextFields handler in ViewController (MVC)

Hide keyboard when scroll

Details

xCode 8.3, Swift 3.1

Full Example

ViewController.swift

import UIKit

fileprivate var textFieldsTexts = [IndexPath:String]()

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupCollectionView()
    }
}

extension ViewController: UICollectionViewDataSource {
    func setupCollectionView() {
        collectionView.dataSource = self
        collectionView.delegate = self
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
        cell.textField.placeholder = "\(indexPath)"
        cell.delegate = self
        return cell
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let cell = cell as! CollectionViewCell
        cell.textField.text = textFieldsTexts[indexPath]
    }

    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
}

extension ViewController: CollectionViewCellDelegate {

    func collectionViewCell(valueChangedIn textField: UITextField, delegatedFrom cell: CollectionViewCell) {
        if let indexPath = collectionView.indexPath(for: cell), let text = textField.text {
            print("textField text: \(text) from cell: \(indexPath))")
            textFieldsTexts[indexPath] = text
        }
    }

    func collectionViewCell(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, delegatedFrom cell: CollectionViewCell)  -> Bool {
        print("Validation action in textField from cell: \(String(describing: collectionView.indexPath(for: cell)))")
        return true
    }

}

CollectionViewCell.swift

import UIKit

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var textField: UITextField!
    var delegate: CollectionViewCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        textField.delegate = self
    }

    @IBAction func valueChanged(_ sender: UITextField) {
        delegate?.collectionViewCell(valueChangedIn: textField, delegatedFrom: self)
    }
}

extension CollectionViewCell: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let delegate = delegate {
            return delegate.collectionViewCell(textField: textField, shouldChangeCharactersIn: range, replacementString: string, delegatedFrom: self)
        }
        return true
    }
}

CollectionViewCellDelegate.swift

import UIKit

protocol CollectionViewCellDelegate {
    func collectionViewCell(valueChangedIn textField: UITextField, delegatedFrom cell: CollectionViewCell)
    func collectionViewCell(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, delegatedFrom cell: CollectionViewCell)  -> Bool
}

Main.storyboard

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12118" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_43143119" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="KWt-KV-A2D">
                                <rect key="frame" x="0.0" y="28" width="375" height="639"/>
                                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                                <collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="WoG-le-dkA">
                                    <size key="itemSize" width="100" height="50"/>
                                    <size key="headerReferenceSize" width="0.0" height="0.0"/>
                                    <size key="footerReferenceSize" width="0.0" height="0.0"/>
                                    <inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
                                </collectionViewFlowLayout>
                                <cells>
                                    <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="CollectionViewCell" id="w5c-mF-XjG" customClass="CollectionViewCell" customModule="stackoverflow_43143119" customModuleProvider="target">
                                        <rect key="frame" x="0.0" y="0.0" width="100" height="50"/>
                                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                        <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
                                            <rect key="frame" x="0.0" y="0.0" width="100" height="50"/>
                                            <autoresizingMask key="autoresizingMask"/>
                                            <subviews>
                                                <textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="text" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="HAy-QM-Eqi">
                                                    <rect key="frame" x="0.0" y="10" width="100" height="30"/>
                                                    <nil key="textColor"/>
                                                    <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                    <textInputTraits key="textInputTraits"/>
                                                    <connections>
                                                        <action selector="valueChanged:" destination="w5c-mF-XjG" eventType="editingChanged" id="qDf-D2-X1l"/>
                                                    </connections>
                                                </textField>
                                            </subviews>
                                        </view>
                                        <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
                                        <constraints>
                                            <constraint firstItem="HAy-QM-Eqi" firstAttribute="centerY" secondItem="w5c-mF-XjG" secondAttribute="centerY" id="JCH-09-Hsr"/>
                                            <constraint firstItem="HAy-QM-Eqi" firstAttribute="leading" secondItem="w5c-mF-XjG" secondAttribute="leading" id="YvF-Qw-sOW"/>
                                            <constraint firstAttribute="trailing" secondItem="HAy-QM-Eqi" secondAttribute="trailing" id="kPK-6X-Aug"/>
                                        </constraints>
                                        <connections>
                                            <outlet property="textField" destination="HAy-QM-Eqi" id="3tf-0f-agX"/>
                                        </connections>
                                    </collectionViewCell>
                                </cells>
                            </collectionView>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="KWt-KV-A2D" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="5Fe-R9-7li"/>
                            <constraint firstItem="KWt-KV-A2D" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="Rjm-Ij-0Pe"/>
                            <constraint firstAttribute="trailing" secondItem="KWt-KV-A2D" secondAttribute="trailing" id="kZ0-HK-x0Z"/>
                            <constraint firstItem="KWt-KV-A2D" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="zQM-Za-bkN"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="collectionView" destination="KWt-KV-A2D" id="SR1-Cn-p5v"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="133.59999999999999" y="137.18140929535232"/>
        </scene>
    </scenes>
</document>

Result


问:
How to regenerate latex fragments in org-mode?
I have latex fragments in org-mode that were generated with my previous emacs theme and now that I switched my theme, the old latex fragments still have my old background color instead of the new one. How can I clear them and regenerate them (linux)?</p>

答:
C-c C-x C-l is bound to org-toggle-latex-fragment. Do it once to get rid of the overlay and do it again to regenerate the overlay. Depending on where you are in the buffer and whether you invoke it with one C-u or two C-u or no C-u, it will do different things (affect the current latex fragment, all fragments in a subtree, or all fragments in the buffer). You should read the doc string of the funcion with

```<code>C-h C-f org-toggle-latex-fragment RET
</code>```

Body:
C-c C-x C-l is bound to org-toggle-latex-fragment. Do it once to get rid of the overlay and do it again to regenerate the overlay. Depending on where you are in the buffer and whether you invoke it with one C-u or two C-u or no C-u, it will do different things (affect the current latex fragment, all fragments in a subtree, or all fragments in the buffer). You should read the doc string of the funcion with

C-h C-f org-toggle-latex-fragment RET


问:
Trying to Concatenate from another sheet on VBA
I'm new to VB and am trying to get a code together that will pull data from two cells (B13,B14) onto Sheet3, while having the concatenate and data in the next empty cell on table (A3:A47) onto Sheet10.

This is the input:

```<code> #   A    B
 #1
 #2
 #3
 .
 .
 .
 #13     02
 #14     01
</code>```

And desired output (some characters are added to the string):

```<code> #   A           B
 #1
 #2
 #3  not-empty
 #4  not-empty
 #5  not-empty
 #6  not-empty
 #7  R02-S01
 #8
 ...
</code>```

Any help would be greatly appreciated!

答:
This macro does what you want (or at least what you mentioned). You can loop this over a range for further use.</p>

```<code> Option Explicit

 Dim iwsh As Worksheet
 Dim owsh As Worksheet
 Dim output As String
 Dim i As Integer

 Sub Copy()

 Set iwsh = Worksheets("Sheet3")
 Set owsh = Worksheets("Sheet10")

 i = 3

 While owsh.Cells(i, 1) <> ""

 i = i + 1

 Wend

 output = "R" & iwsh.Cells(13, 2).Value & "-S" & iwsh.Cells(14, 2).Value

 owsh.Cells(i, 1) = output

 End Sub
</code>```

Body:
I'm new to VB and am trying to get a code together that will pull data from two cells (B13,B14) onto Sheet3, while having the concatenate and data in the next empty cell on table (A3:A47) onto Sheet10.

This is the input:

 #   A    B
 #1
 #2
 #3
 .
 .
 .
 #13     02
 #14     01

And desired output (some characters are added to the string):

 #   A           B
 #1
 #2
 #3  not-empty
 #4  not-empty
 #5  not-empty
 #6  not-empty
 #7  R02-S01
 #8
 ...

Any help would be greatly appreciated!

Body:
This macro does what you want (or at least what you mentioned). You can loop this over a range for further use.

 Option Explicit

 Dim iwsh As Worksheet
 Dim owsh As Worksheet
 Dim output As String
 Dim i As Integer

 Sub Copy()

 Set iwsh = Worksheets("Sheet3")
 Set owsh = Worksheets("Sheet10")

 i = 3

 While owsh.Cells(i, 1) <> ""

 i = i + 1

 Wend

 output = "R" & iwsh.Cells(13, 2).Value & "-S" & iwsh.Cells(14, 2).Value

 owsh.Cells(i, 1) = output

 End Sub


问:
Is it possible to ignore case using xpath and c#?
Just wondered if its possible to ignore case with c# and xpath when searching an xml document?</p>

答:
XPath is case sensitive.

If you would allow any case combination of characters in a name (bad decision!), an XPath expression successfully dealing with this might look like:

```<code>/a/b/*['anycasename'
      = translate(name(),
                 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                 'abcdefghijklmnopqrstuvwxyz'
                 )
      ]
</code>```

Body:
XPath is case sensitive.

If you would allow any case combination of characters in a name (bad decision!), an XPath expression successfully dealing with this might look like:

/a/b/*['anycasename'
      = translate(name(),
                 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                 'abcdefghijklmnopqrstuvwxyz'
                 )
      ]


问:
Intellij Scala Type Info stopped working
Scala's Type Info from the View menu and by pressing ctrl-shift-p has just stopped working. I press and nothing appears ever. I upgraded the IDE and the plugin but it doesn't make a difference. Any help on how to fix it would be appreciated.</p>

答:
Try File > Project Structure > Global Libraries and make sure you have at least one scala-sdk present.

In the same screen, select Modules and check the Dependencies tab and make sure your scala-sdk is present (it's usually toward the top of the list).


问:
Change set of Image resource on Button click in fragment
I have there sets of drawable in int array. Is it possible to change the image resource of the image view in the fragment on button click? for example i have there a method onclicklistener for button benefit_babies... i want to set the image resource into the int array benefitBaby on click of the button.

InformationTab fragment

```<code>package com.example.aldrinjohn.sample;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Aldrin John on 3/20/2017.
 */

public class InformationTab extends Fragment{
    ViewPager viewPager;
    CustomSwipeAdapter adapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.informationtab, container, false);
        viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
        adapter = new CustomSwipeAdapter(this.getActivity());
        viewPager.setAdapter(adapter);

        return rootView;

    }

}
</code>```

XML File:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/trivia"
        android:text="BreastFeeding Trivia"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/benefit_babies"
        android:text="Benefits to Babies"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/storing"
        android:text="Storing Breastmilk"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/pump"
            android:text="How to Pump Breastmilk"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/benefit_mother"
            android:text="Benefits to Mothers"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/tips"
            android:text="Tips and Information"/>

    </LinearLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/image_view"/>

</LinearLayout>
</code>```

JAVA Code:

```<code>package com.example.aldrinjohn.sample;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.tagmanager.Container;

/**
 * Created by Aldrin John on 3/26/2017.
 */

public class CustomSwipeAdapter extends PagerAdapter implements View.OnClickListener{
    private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
    private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
    private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
    private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
                            R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
    private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
    private Context ctx;
    private LayoutInflater layoutInflater;
    Button btnbenefitB;

    public CustomSwipeAdapter(Context ctx)
    {
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        return trivia.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position){
        layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        btnbenefitB = (Button)item_view.findViewById(R.id.benefit_babies);
        btnbenefitB.setOnClickListener(this);
        ImageView imageView = (ImageView)item_view.findViewById(R.id.image_view);
        imageView.setImageResource(trivia[position]);
        container.addView(item_view);

        return item_view;
    }
@Override
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((LinearLayout)object);
    }

    public int getCount(int[] x) {
        return x.length - 1;
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.benefit_babies:

                break;
        }
    }
}
</code>```

答:
imageview.setImageResource(id) where id is in your int array. See the documentation for ImageView for details. It is the same as you have in your code just in the onClick() handler.

setImageResource

void setImageResource (int resId)

Sets a drawable as the content of this ImageView.

This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.

Body:
I have there sets of drawable in int array. Is it possible to change the image resource of the image view in the fragment on button click? for example i have there a method onclicklistener for button benefit_babies... i want to set the image resource into the int array benefitBaby on click of the button.

InformationTab fragment

package com.example.aldrinjohn.sample;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Aldrin John on 3/20/2017.
 */

public class InformationTab extends Fragment{
    ViewPager viewPager;
    CustomSwipeAdapter adapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.informationtab, container, false);
        viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
        adapter = new CustomSwipeAdapter(this.getActivity());
        viewPager.setAdapter(adapter);

        return rootView;

    }

}

XML File:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/trivia"
        android:text="BreastFeeding Trivia"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/benefit_babies"
        android:text="Benefits to Babies"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/storing"
        android:text="Storing Breastmilk"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/pump"
            android:text="How to Pump Breastmilk"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/benefit_mother"
            android:text="Benefits to Mothers"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/tips"
            android:text="Tips and Information"/>

    </LinearLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/image_view"/>

</LinearLayout>

JAVA Code:

package com.example.aldrinjohn.sample;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.tagmanager.Container;

/**
 * Created by Aldrin John on 3/26/2017.
 */

public class CustomSwipeAdapter extends PagerAdapter implements View.OnClickListener{
    private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
    private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
    private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
    private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
                            R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
    private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
    private Context ctx;
    private LayoutInflater layoutInflater;
    Button btnbenefitB;

    public CustomSwipeAdapter(Context ctx)
    {
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        return trivia.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position){
        layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        btnbenefitB = (Button)item_view.findViewById(R.id.benefit_babies);
        btnbenefitB.setOnClickListener(this);
        ImageView imageView = (ImageView)item_view.findViewById(R.id.image_view);
        imageView.setImageResource(trivia[position]);
        container.addView(item_view);

        return item_view;
    }
@Override
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((LinearLayout)object);
    }

    public int getCount(int[] x) {
        return x.length - 1;
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.benefit_babies:

                break;
        }
    }
}


问:
How to downsize images by percentage of themselves without using transform: scale()
I have a number of horizontally distributed and equally spaced logos (parent container set as display: flex, justify-content: space-between). So they can fit on the screen as viewport decreases, I scale them down using transform: scale(): that's not good because although the logos themselves are downsized, the space they normally take is preserved so they appear more and more apart from each other (in particular the far left and far right logos don't touch the edges of their parent container any more).

Catch: unlike the simplified markup below, my setup includes
 element that are hidden by CMS and it's not possible to know in advance which ones will be visible and which ones will be hidden.

Any way around this problem?

HTML:

```<code><ul>
  <li>
    <img src="image1.jpg" />
  </li>
  <li>
    <img src="image2.jpg" />
  </li>
  <li>
    <img src="image3.jpg" />
  </li>
  <li>
    <img src="image4.jpg" />
  </li>
</ul>
</code>```

CSS:

```<code>ul {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
}
li {
  transform: scale(0.5);
}
</code>```

答:
Use max-width: 100% on the images themselves to constrain them. Then use margin on the
s to space them.

ul {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  /*
  justify-content: space-around; <-- you might try this instead
  */
}
li {
  /*margin: 0 5px; no-no for OP use case*/
  text-align: center;
}
img {
  max-width: 96%; /* the margin workaround */
}

/* demo cleanup only */
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    <img src="http://fillmurray.com/200/300" />
  </li>
  <li>
    <img src="http://fillmurray.com/200/300" />
  </li>
  <!--
  <li></li>
  Oops, missing LI. -->
  <li>
    <img src="http://fillmurray.com/200/300" />
  </li>
</ul></code>```

Need to hit the 'Full Page' button when you run the snippet to test how it scales.

Edit re: no LI margin: You can move the margin to the images in a few different ways. Here, since the
 has text-align: center already, just reducing the max-width on the image should suffice. Also means the LIs will collapse completely. New HTML has a missing image.

Body:
I have a number of horizontally distributed and equally spaced logos (parent container set as display: flex, justify-content: space-between). So they can fit on the screen as viewport decreases, I scale them down using transform: scale(): that's not good because although the logos themselves are downsized, the space they normally take is preserved so they appear more and more apart from each other (in particular the far left and far right logos don't touch the edges of their parent container any more).

Catch: unlike the simplified markup below, my setup includes
 element that are hidden by CMS and it's not possible to know in advance which ones will be visible and which ones will be hidden.

Any way around this problem?

HTML:

CSS:

ul {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
}
li {
  transform: scale(0.5);
}

Body:
Use max-width: 100% on the images themselves to constrain them. Then use margin on the <li>s to space them.

ul {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  /*
  justify-content: space-around; <-- you might try this instead
  */
}
li {
  /*margin: 0 5px; no-no for OP use case*/
  text-align: center;
}
img {
  max-width: 96%; /* the margin workaround */
}

/* demo cleanup only */
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

<ul>
  <li>
    <img src="http://fillmurray.com/200/300" />
  </li>
  <li>
    <img src="http://fillmurray.com/200/300" />
  </li>
  <!--
  <li></li>
  Oops, missing LI. -->
  <li>
    <img src="http://fillmurray.com/200/300" />
  </li>
</ul>

Need to hit the 'Full Page' button when you run the snippet to test how it scales.

Edit re: no LI margin: You can move the margin to the images in a few different ways. Here, since the <li> has text-align: center already, just reducing the max-width on the image should suffice. Also means the LIs will collapse completely. New HTML has a missing image.


问:
Activating multiple worksheets for export using VBA
I am trying to code a routine which takes a user's choices of available worksheets from an Excel VBA form and exports them into one PDF document. I plan on using this with export to Word and to PowerPoint routines. I have tried several of the ideas from Stack Overflow which were said to have worked. I have had no luck. I have also tried various ideas from other sources...maybe I am blind to the obvious.

I tried using an array (arrSheets, still in the code, I have hopes that maybe I can still use it.). It populates with sheet objects, but using a dynamic array and the redim command haven't worked for me.

What I have here is code which appears to work well until it comes to the "ActiveSheet.ExportAsFixedFormat..." line. At that point I get "Application-defined or Object-defined error  (Run-time error 1004)"

The following code fires from a command button on a VBA form...

```<code>Private Sub cmdExport_Click()
    'Find the selected documents from the form's checkboxes and send to the export routine
Dim intArrayCounter, intSelectionNum As Integer
Dim bolFound As Boolean
Dim ctrl As control
Dim arrSheets(1 To 6) As Variant ' the array to hold the worksheet objects...

    intSelectionNum = 0 ' which checkbox is it
    intArrayCounter = 1 ' array index
    bolFound = False    ' was a checked box found?

    For Each ctrl In frmToPDF.Controls
        If TypeName(ctrl) = "CheckBox" Then
            intSelectionNum = intSelectionNum + 1 ' set the selection number
            If ctrl.Value = True Then
                bolFound = True '  found a selection set the flag to true

                    Set arrSheets(intArrayCounter) = Sheets(intSelectionNum)
                    ThisWorkbook.Sheets(intSelectionNum).Select

                ' increment the counter
                intArrayCounter = intArrayCounter + 1
            End If
        End If
    Next

    'Sheets(arrSheets).Select <---remmed out cause this throws an error

    If bolFound = False Then   ' if there is Nothing selected send a message, or do the deal...
        Call MsgBox("There is nothing selected to export!", vbOKOnly, "Nothing selected...")
    Else
        frmExport.Caption = "Processing the document...Please be patient!"

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\test.pdf", Quality:=xlQualityStandard, IgnorePrintAreas:=False, DisplayFileAfterPublish:=True
        'the above Activesheet routine throws "Application-defined or Object-defined error  (Run-time error 1004)"
    End If

    ThisWorkbook.Sheets(intSheet).Select

End Sub
</code>```

答:
I could not get the "ActiveSheet.ExportAsFixedFormat" to work. But I found this answer elsewhere on StackOverflow which works very well, and with very little code:
Use a method on multiple sheets simultaneously without using ActiveSheet or Select
Thank you all for your help...</p>

Body:
I am trying to code a routine which takes a user's choices of available worksheets from an Excel VBA form and exports them into one PDF document. I plan on using this with export to Word and to PowerPoint routines. I have tried several of the ideas from Stack Overflow which were said to have worked. I have had no luck. I have also tried various ideas from other sources...maybe I am blind to the obvious.

I tried using an array (arrSheets, still in the code, I have hopes that maybe I can still use it.). It populates with sheet objects, but using a dynamic array and the redim command haven't worked for me.

What I have here is code which appears to work well until it comes to the "ActiveSheet.ExportAsFixedFormat..." line. At that point I get "Application-defined or Object-defined error  (Run-time error 1004)"

The following code fires from a command button on a VBA form...

Private Sub cmdExport_Click()
    'Find the selected documents from the form's checkboxes and send to the export routine
Dim intArrayCounter, intSelectionNum As Integer
Dim bolFound As Boolean
Dim ctrl As control
Dim arrSheets(1 To 6) As Variant ' the array to hold the worksheet objects...

    intSelectionNum = 0 ' which checkbox is it
    intArrayCounter = 1 ' array index
    bolFound = False    ' was a checked box found?

    For Each ctrl In frmToPDF.Controls
        If TypeName(ctrl) = "CheckBox" Then
            intSelectionNum = intSelectionNum + 1 ' set the selection number
            If ctrl.Value = True Then
                bolFound = True '  found a selection set the flag to true

                    Set arrSheets(intArrayCounter) = Sheets(intSelectionNum)
                    ThisWorkbook.Sheets(intSelectionNum).Select

                ' increment the counter
                intArrayCounter = intArrayCounter + 1
            End If
        End If
    Next

    'Sheets(arrSheets).Select <---remmed out cause this throws an error

    If bolFound = False Then   ' if there is Nothing selected send a message, or do the deal...
        Call MsgBox("There is nothing selected to export!", vbOKOnly, "Nothing selected...")
    Else
        frmExport.Caption = "Processing the document...Please be patient!"

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\test.pdf", Quality:=xlQualityStandard, IgnorePrintAreas:=False, DisplayFileAfterPublish:=True
        'the above Activesheet routine throws "Application-defined or Object-defined error  (Run-time error 1004)"
    End If

    ThisWorkbook.Sheets(intSheet).Select

End Sub


问:
AttributeError: 'module' object has no attribute 'SFrame'
I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.

I get the following error,

```<code>import graphlab
sf = graphlab.SFrame('people-example.csv')
</code>```

AttributeError Traceback (most recent call last)
 in ()

----> 1 sf = graphlab.SFrame('people-example.csv')

AttributeError: 'module' object has no attribute 'SFrame'

How do I fix this error?I have the people-example.csv in the correct path and no spelling mistake on SFrame
Any help is greatly appreciated.Thank you.

答:
ok i was having the same problem today and no one can help me ... but i finally found the solution of this problem .... first when you write the code make sure of some important thing
1- s an f in sframe must be capital
2- the most important when you writing  people-example.csv   write first 4 letters and hit ((tap)) it will continue the word . and here you are every thing is ok :)</p>

Body:
I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.

I get the following error,

import graphlab
sf = graphlab.SFrame('people-example.csv')

AttributeError Traceback (most recent call last)
 in ()

----> 1 sf = graphlab.SFrame('people-example.csv')

AttributeError: 'module' object has no attribute 'SFrame'

How do I fix this error?I have the people-example.csv in the correct path and no spelling mistake on SFrame
Any help is greatly appreciated.Thank you.


问:
White screen for 2-3 seconds after integrating Akamai
I have integrated Akamai caching in my production web application for which I have provided extensions (HTML, CSS..) which needs to be cached. But after integrating, on production I am getting white screen for 2-3 seconds as soon as I launch application in browser. Not sure why.

Note: If application files are being cached by browser than it does not take time to launch nor it shows white screen. But once you clear browser cache, Akamai should deliver files from its cache quickly.

Any inputs would be appreciated. Thanks in advance!

答:
Akamai have special headers you can use in requests to determine if you're getting cache hits with them or if you're flowing all the way to your site, here's a couple of links to get you started with them:

https://community.akamai.com/community/web-performance/blog/2015/03/31/using-akamai-pragma-headers-to-investigate-or-troubleshoot-akamai-content-delivery

https://community.akamai.com/videos/1227

There's even chrome extensions that will add the headers for you, there's one example in the second link but I prefer this one:

https://chrome.google.com/webstore/detail/akamai-debug-headers/lcfphdldglgaodelggpckakfficpeefj?hl=en


问:
handling multi requests in react-native and redux and react-native-maps
I'm building a react-native app where i use react-native-maps package to show markers on the map with every region by sending request to my server to get some data

```<code><MapView
        followUserLocation
        initialRegion={region}
        ref={(ref) => { this.mapRef = ref; }}
        showsUserLocation
        style={styles.map}
        onRegionChange={this.onRegionChange.bind(this)}
/>
</code>```

on RegionChange i send a request to my server

```<code>onRegionChange(region) {
// send my request to my server
}
</code>```

but the user may make many region change in a very short time , how can i make sure that i'll get the correct response (i.e response related to the last region change ) ??

答:
There are several ways to achieve this.

Debounce

Use debounce for "onRegionChange". This way only the last change will be executed.

More info: Perform debounce in React.js

Cancelable promises

Some Promise libraries provide cancelable promises.

More info: http://bluebirdjs.com/docs/api/cancel.html

Body:
I'm building a react-native app where i use react-native-maps package to show markers on the map with every region by sending request to my server to get some data

<MapView
        followUserLocation
        initialRegion={region}
        ref={(ref) => { this.mapRef = ref; }}
        showsUserLocation
        style={styles.map}
        onRegionChange={this.onRegionChange.bind(this)}
/>

on RegionChange i send a request to my server

onRegionChange(region) {
// send my request to my server
}

but the user may make many region change in a very short time , how can i make sure that i'll get the correct response (i.e response related to the last region change ) ??


问:
How to run a macro daily using windows task scheduler
I have a macro which I want to run at a specified time daily (say 11 am) even if Excel is closed.

What I have found out is that I can do it by creating Windows Task Scheduler, but I'm new to Windows and don't know how this is created.

The following is my macro:

```<code>Sub Mail_Sheet_Outlook_Body()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set rng = Nothing
    Set rng = ActiveSheet.UsedRange
    'You can also use a sheet name
    'Set rng = Sheets("YourSheet").UsedRange

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Testing"
        .HTMLBody = RangetoHTML(rng)
        .Send   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function
</code>```

Can anyone tell me how to create the windows task scheduler to run this macro daily?

UPDATE:

Wrote the following vbs script:

```<code>Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open(“H:\excel.xlsm”, 0, True)

xlApp.Run "GetFiles"

xlbook.Save
xlBook.Close False
set xlBook = Nothing

xlApp.Quit
Set xlApp = Nothing

WScript.Echo "Finished."
WScript.Quit
</code>```

答:
Create a file and change extension to .vbs. You will be writing a small script to start open your xlsm file.

Put your starting function in the Private Sub Workbook_Open(), so your function will run when the file is open

Follow the instructions here to make Windows Task Scheduler fire off your vbs

Body:
I have a macro which I want to run at a specified time daily (say 11 am) even if Excel is closed.

What I have found out is that I can do it by creating Windows Task Scheduler, but I'm new to Windows and don't know how this is created.

The following is my macro:

Sub Mail_Sheet_Outlook_Body()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set rng = Nothing
    Set rng = ActiveSheet.UsedRange
    'You can also use a sheet name
    'Set rng = Sheets("YourSheet").UsedRange

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Testing"
        .HTMLBody = RangetoHTML(rng)
        .Send   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Can anyone tell me how to create the windows task scheduler to run this macro daily?

UPDATE:

Wrote the following vbs script:

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open(“H:\excel.xlsm”, 0, True)

xlApp.Run "GetFiles"

xlbook.Save
xlBook.Close False
set xlBook = Nothing

xlApp.Quit
Set xlApp = Nothing

WScript.Echo "Finished."
WScript.Quit


问:
Looking for a formal specification for .pbxproj files
I need to read / write Xcode project definition files (myproject.xcodeproj/project.pbxproj) - is there any formal specification of the file format which I can use to create a parser?

答:
pbxproj files seem to be implemented using some internal implementation of NSCoder; "isa" is Objective-C's internal name for a "class name", and the mention of "archive" reminds of NSArchiver/NSKeyedArchiver, concrete implementations of NSCoder.

pbxproj looks like an archive of a dictionary of objects which probably serve as Xcode's internal in-memory model of project. It refers to numerous class names which seem to be Xcode's model classes.

I am unaware of a formal spec of either the archive format nor the classes. That is what I came to ask on SO today in fact: which NSCoder is here used by Apple. On the other hand, writing something that would decode this object tree, and then identify the purpose and connections between objects, is how I was going to proceed.