问:
sed variable substitution using string
How to pass argument to sed without input files. The sed is in single quote and has pipe in it already.

```<code>git filter-branch -f --index-filter \
      'git ls-files -s | sed -i "s-\t\"*-&dirname/-" |
                GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
                git update-index --index-info &&
       mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"' HEAD
</code>```

The above code works fine if dirname is hard-coded. But i need to pass the dirname from command line arguments to script. I am trying like below but no luck.

```<code> 'set subdir=$folder;git ls-files -s | sed -i "s-\t\"*-&$subdir/-" |
</code>```

The sed says input file is missing. I can not directly pass the input file to sed. I am seeing error like below.

```<code>Rewrite 9c86de42b7f3228e3d45a278c8caf7e24c8e55cf (1/2) (0 seconds passed, remaining 0 predicted)
sed: no input files
</code>```

答:
You have two choices here.  You can either evaluate $subdir to build up a fixed sed command that you then set as your filter; or you can evaluate a variable in the shell fragment that git filter-branch will invoke.

To understand the latter, realize that your --index-filter string becomes an ordinary shell variable:

```<code>--index-filter)
    filter_index="$OPTARG"
;;
</code>```

which is then passed to eval:

```<code>eval "$filter_index" < /dev/null ||
    die "index filter failed: $filter_index"
</code>```

The eval means that the expression in $filter_index, set from your --index-filter argument, has access to all the shell variables and functions in the filter-branch script.  Unfortunately, none of its private variables holds the expression you'd like—but you can access its environment variables, which means you can put the value into an environment variable.  In other words, you could supply subdir=<whatever> as an environment to your original expression.

In any case, as bk2204 answered, you need to remove the -i option.  Besides that, some versions of sed don't accept \t as a tab character (presumably yours does, just be aware of this).

To expand the variable earlier, just do that.  For instance:

```<code>... --index-filter \
    'git ls-files -s | sed "s-\t\"*-&'$folder'/-" | ...
</code>```

(I've removed the -i here myself).  Note how this exits single quotes, expands $folder, then re-enters single quotes.  If $folder might contain whitespace, be sure to use double quotes while expanding it here:

```<code>... --index-filter \
    'git ls-files -s | sed "s-\t\"*-&'"$folder"'/-" | ...
</code>```

The nesting of quotes here is pretty tricky: the stuff inside the single quotes is all one big string, provided as the argument that sets the variable $filter_index inside the filter-branch script.  The eval runs it through a second pass of evaluation, breaking up into the pipeline (git ls-files, piped to sed, piped to git update-index) and running the various multiple commands, all of which have their stdin redirected to /dev/null.

Title: sed variable substitution using string

Body:
How to pass argument to sed without input files. The sed is in single quote and has pipe in it already.

git filter-branch -f --index-filter \
      'git ls-files -s | sed -i "s-\t\"*-&dirname/-" |
                GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
                git update-index --index-info &&
       mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"' HEAD

The above code works fine if dirname is hard-coded. But i need to pass the dirname from command line arguments to script. I am trying like below but no luck.

 'set subdir=$folder;git ls-files -s | sed -i "s-\t\"*-&$subdir/-" |

The sed says input file is missing. I can not directly pass the input file to sed. I am seeing error like below.

Rewrite 9c86de42b7f3228e3d45a278c8caf7e24c8e55cf (1/2) (0 seconds passed, remaining 0 predicted)
sed: no input files

Body:
You have two choices here.  You can either evaluate $subdir to build up a fixed sed command that you then set as your filter; or you can evaluate a variable in the shell fragment that git filter-branch will invoke.

To understand the latter, realize that your --index-filter string becomes an ordinary shell variable:

--index-filter)
    filter_index="$OPTARG"
;;

which is then passed to eval:

eval "$filter_index" < /dev/null ||
    die "index filter failed: $filter_index"

The eval means that the expression in $filter_index, set from your --index-filter argument, has access to all the shell variables and functions in the filter-branch script.  Unfortunately, none of its private variables holds the expression you'd like—but you can access its environment variables, which means you can put the value into an environment variable.  In other words, you could supply subdir=<whatever> as an environment to your original expression.

In any case, as bk2204 answered, you need to remove the -i option.  Besides that, some versions of sed don't accept \t as a tab character (presumably yours does, just be aware of this).

To expand the variable earlier, just do that.  For instance:

... --index-filter \
    'git ls-files -s | sed "s-\t\"*-&'$folder'/-" | ...

(I've removed the -i here myself).  Note how this exits single quotes, expands $folder, then re-enters single quotes.  If $folder might contain whitespace, be sure to use double quotes while expanding it here:

... --index-filter \
    'git ls-files -s | sed "s-\t\"*-&'"$folder"'/-" | ...

The nesting of quotes here is pretty tricky: the stuff inside the single quotes is all one big string, provided as the argument that sets the variable $filter_index inside the filter-branch script.  The eval runs it through a second pass of evaluation, breaking up into the pipeline (git ls-files, piped to sed, piped to git update-index) and running the various multiple commands, all of which have their stdin redirected to /dev/null.


来源: stackexchange

问:
How to access universal link in iOS application?
I am working with universal link to open iOS application and on this basis of link data I have to open viewcontroller in my iOS application.

I am using Xcode 10.0. And running application on iOS 12.0 (iPhone 7 Plus).

This is my universal link: https://en5vz.app.goo.gl/kjvaHzXrLMNBEDtG7

When I tap on this link then application is launched but method given below is not being called:

```<code>private func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: @escaping ([Any]?) -> Void) -> Bool {

    print("\(#function) ---- \(userActivity.webpageURL)")
    if #available(iOS 11.0, *) {
        print("\(#function) ---- \(userActivity.referrerURL)")
    } else {
        // Fallback on earlier versions
    }

    if let incominURL = userActivity.webpageURL{

        let linkHandled = DynamicLinks.dynamicLinks()?.handleUniversalLink(incominURL, completion: { (dynamiclink, error) in

            if let dynamiclink = dynamiclink, let _ = dynamiclink.url{

                self.handleIncomingDynamicLink(dynamiclink: dynamiclink)
            }

        })
        return linkHandled!

    }

    return false

}
</code>```

I am not able to figure out what is the exact issue.

答:
This is an old question, but for anyone looking, the missing component here is the app-site-association file: https://developer.apple.com/documentation/uikit/core_app/allowing_apps_and_websites_to_link_to_your_content/enabling_universal_links

Take the following steps to associate your app and website for universal links:

Add the Associated Domains Entitlement to your app. Include all domains your app will support using the applinks service prefix. See Add the Associated Domains Entitlement.

Add an Apple App Site Association file to your website. See Add the Apple App Site Association File.

Add the applinks key to the Apple App Site Association file. Specify the sections of your website each of your apps will handle.

You've done step 1 (and step 0, which is setting up the code in your app), but steps 2 and 3 are missing.

ContentLicense: CC BY-SA 4.0

Body:
I am working with universal link to open iOS application and on this basis of link data I have to open viewcontroller in my iOS application.

I am using Xcode 10.0. And running application on iOS 12.0 (iPhone 7 Plus).

This is my universal link: https://en5vz.app.goo.gl/kjvaHzXrLMNBEDtG7

When I tap on this link then application is launched but method given below is not being called:

private func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: @escaping ([Any]?) -> Void) -> Bool {

    print("\(#function) ---- \(userActivity.webpageURL)")
    if #available(iOS 11.0, *) {
        print("\(#function) ---- \(userActivity.referrerURL)")
    } else {
        // Fallback on earlier versions
    }

    if let incominURL = userActivity.webpageURL{

        let linkHandled = DynamicLinks.dynamicLinks()?.handleUniversalLink(incominURL, completion: { (dynamiclink, error) in

            if let dynamiclink = dynamiclink, let _ = dynamiclink.url{

                self.handleIncomingDynamicLink(dynamiclink: dynamiclink)
            }

        })
        return linkHandled!

    }

    return false

}

I am not able to figure out what is the exact issue.


问:
Do I need to create multiple database connection in a loop?
I am using sqllite3 and want to insert data into the table. My code roughly looks like:

```<code>def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = sqlite3.connect(db)
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()
</code>```

As it can be seen, the database is connected and closed for each insertion of the data record. Is there a way to only connect and close the db once for all the data to be processed?

答:
This is a lot more efficient. Committing data after each record hurts performance a lot.

```<code>def fill_database(db):
    ...
    connection = sqlite3.connect(db)
    cursor = connection.cursor()

    for record in records:
        cursor.execute("...")

    connection.commit()
    connection.close()
</code>```

If you must have a separate function then pass the cursor as an argument instead of the db.

Body:
I am using sqllite3 and want to insert data into the table. My code roughly looks like:

def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = sqlite3.connect(db)
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()

As it can be seen, the database is connected and closed for each insertion of the data record. Is there a way to only connect and close the db once for all the data to be processed?

Body:
This is a lot more efficient. Committing data after each record hurts performance a lot.

def fill_database(db):
    ...
    connection = sqlite3.connect(db)
    cursor = connection.cursor()

    for record in records:
        cursor.execute("...")

    connection.commit()
    connection.close()

If you must have a separate function then pass the cursor as an argument instead of the db.


问:
How to shift value with inside nested ifelse statement?
my code

```<code>re$p_RID <- ifelse((re$group_UID & re$Amount_type=='Draw'),
                           shift(re$id), 'NA')
</code>```

my data frame look like this after I run the code:

```<code>id  user_id  Amount_type group_UID p_RID
30    11        Non        1        NA
31    11        Draw       1        30
54    5         Non        2        NA
322   5         Draw       2        54
21    5         Draw       2        322
13    5         Non        2        NA
2445  5         Draw       2        13
111   44        Non        3        NA
287   44        Draw       3        111
</code>```

I would like to use the id in first occurrence on amount_type of Non value for each p_RID column.(within the same group_UID, if there are many multiple occurrence of Non value, then treat each of them as the first occurrence) The result should look like this:

```<code>id  user_id  Amount_type group_UID p_RID
30    11        Non        1        NA
31    11        Draw       1        30
54    5         Non        2        NA
322   5         Draw       2        54
21    5         Draw       2        54 <- this is where I don't know how to edit
13    5         Non        2        NA
2445  5         Draw       2        13
111   44        Non        3        NA
287   44        Draw       3        111
</code>```

答:
Using dplyr one way is to group_by group_UID and occurrence of "Non" value and assign NA to first row and first id in each group otherwise.

```<code>library(dplyr)

df %>%
  group_by(group_UID, group = cumsum(Amount_type == "Non")) %>%
  mutate(p_RID = ifelse(row_number() == 1, NA, id[1L])) %>%
  ungroup() %>%
  select(-group)

#    id user_id Amount_type group_UID  p_RID
#   <int>   <int> <fct>           <int> <int>
#1    30      11 Non                 1    NA
#2    31      11 Draw                1    30
#3    54       5 Non                 2    NA
#4   322       5 Draw                2    54
#5    21       5 Draw                2    54
#6    13       5 Non                 2    NA
#7  2445       5 Draw                2    13
#8   111      44 Non                 3    NA
#9   287      44 Draw                3   111
</code>```

Another way would be

```<code>df %>%
  group_by(group_UID, group = cumsum(Amount_type == "Non")) %>%
  mutate(p_RID = ifelse(Amount_type == "Non", NA, first(id))) %>%
  ungroup() %>%
  select(-group)
</code>```

We can also use base R ave here

```<code>with(df, ave(id, group_UID, cumsum(Amount_type == "Non"), FUN = function(x)
    ifelse(seq_along(x) == 1, NA, x[1L])))

#[1]  NA  30  NA  54  54  NA  13  NA 111
</code>```

Body:
my code

re$p_RID <- ifelse((re$group_UID & re$Amount_type=='Draw'),
                           shift(re$id), 'NA')

my data frame look like this after I run the code:

id  user_id  Amount_type group_UID p_RID
30    11        Non        1        NA
31    11        Draw       1        30
54    5         Non        2        NA
322   5         Draw       2        54
21    5         Draw       2        322
13    5         Non        2        NA
2445  5         Draw       2        13
111   44        Non        3        NA
287   44        Draw       3        111

I would like to use the id in first occurrence on amount_type of Non value for each p_RID column.(within the same group_UID, if there are many multiple occurrence of Non value, then treat each of them as the first occurrence) The result should look like this:

id  user_id  Amount_type group_UID p_RID
30    11        Non        1        NA
31    11        Draw       1        30
54    5         Non        2        NA
322   5         Draw       2        54
21    5         Draw       2        54 <- this is where I don't know how to edit
13    5         Non        2        NA
2445  5         Draw       2        13
111   44        Non        3        NA
287   44        Draw       3        111

Body:
Using dplyr one way is to group_by group_UID and occurrence of "Non" value and assign NA to first row and first id in each group otherwise.

library(dplyr)

df %>%
  group_by(group_UID, group = cumsum(Amount_type == "Non")) %>%
  mutate(p_RID = ifelse(row_number() == 1, NA, id[1L])) %>%
  ungroup() %>%
  select(-group)

#    id user_id Amount_type group_UID  p_RID
#   <int>   <int> <fct>           <int> <int>
#1    30      11 Non                 1    NA
#2    31      11 Draw                1    30
#3    54       5 Non                 2    NA
#4   322       5 Draw                2    54
#5    21       5 Draw                2    54
#6    13       5 Non                 2    NA
#7  2445       5 Draw                2    13
#8   111      44 Non                 3    NA
#9   287      44 Draw                3   111

Another way would be

df %>%
  group_by(group_UID, group = cumsum(Amount_type == "Non")) %>%
  mutate(p_RID = ifelse(Amount_type == "Non", NA, first(id))) %>%
  ungroup() %>%
  select(-group)

We can also use base R ave here

with(df, ave(id, group_UID, cumsum(Amount_type == "Non"), FUN = function(x)
    ifelse(seq_along(x) == 1, NA, x[1L])))

#[1]  NA  30  NA  54  54  NA  13  NA 111


问:
how to only show number with truncate or css
I want to display S1 only instead of season 1. Thus I need to truncate season and put only 1 and add "S" at the front.

```<code><a href="{% url 'season_detail' slug=all_episode.season.slug %}">
    {{ all_episode.season}}
</a>
</code>```

How do I truncate the word "season"?

Edit:
Here's what I did again

I created templatetag folder inside my app
then added init.py and seasonify.py
and inside seasonify.py I added

```<code>from django import template

register = template.Library()

@register.filter
def seasonify(value):
    return value.replace('season', 'S')
</code>```

then inside my template
I added

```<code>{% load seasonify %}
and {% episode.season|seasonify %}
</code>```

答:
Your best bet is to write a custom template filter. The logic is simple:

```<code>@register.filter
def seasonify(value):
    return value.replace('season', 'S')
</code>```

then simply use it in your templates:

```<code>{{ all_episode.season | seasonify }}
</code>```

See Django docs for details on where to put this code.

Body:
I want to display S1 only instead of season 1. Thus I need to truncate season and put only 1 and add "S" at the front.

    {{ all_episode.season}}

How do I truncate the word "season"?

Edit:
Here's what I did again

I created templatetag folder inside my app
then added init.py and seasonify.py
and inside seasonify.py I added

from django import template

register = template.Library()

@register.filter
def seasonify(value):
    return value.replace('season', 'S')

then inside my template
I added

{% load seasonify %}
and {% episode.season|seasonify %}

Body:
Your best bet is to write a custom template filter. The logic is simple:

@register.filter
def seasonify(value):
    return value.replace('season', 'S')

then simply use it in your templates:

{{ all_episode.season | seasonify }}

See Django docs for details on where to put this code.


问:
How to pass data (like TestCase ID, status) from scenario to after scenario
I have to update the results of each scenario to third party application and to achieve it, i am calling a feature (updateResults.feature) in after scenario. But i dont know how to pass the scenario status(pass, fail) to after scenario.
Note: Using Karate version 0.8.0.RC3</p>

答:
See the example, hooks.feature you can pass arguments:

```<code>karate.call('after-scenario.feature', { caller: info.featureFileName });
</code>```

Refer the docs for karate.call(): https://github.com/intuit/karate#karate-call

Body:
See the example, hooks.feature you can pass arguments:

karate.call('after-scenario.feature', { caller: info.featureFileName });

Refer the docs for karate.call(): https://github.com/intuit/karate#karate-call


问:
What is in the meaning of `return "DONE"` at the end of a function in Python?
For context, this code is written on a video within the channel Numberphile by Matt Parker talking about multiplication persistence. The code is written in Python 2, and my question is about the line return "DONE".

Evidently, this prevents an infinite loop from being generated, as it is clear running an example (below) with and without that line:

```<code>def per(n, steps = 0):
    if len(str(n)) == 1:
        print "TOTAL STEPS " + str(steps)
        return "DONE"

    steps += 1
    digits = [int(i) for i in str(n)]

    result = 1
    for j in digits:
        result *= j
    print result
    per (result, steps)

per(27)

# 14
# 4
# TOTAL STEPS 2
</code>```

Now, the same code without the line return "DONE" would not end the loop, and yield:

```<code>14
4
TOTAL STEPS 2
4
TOTAL STEPS 3
4
TOTAL STEPS 4
4
TOTAL STEPS 5
4
TOTAL STEPS 6
4
TOTAL STEPS 7
4
TOTAL STEPS 8
4
TOTAL STEPS 9
4
TOTAL STEPS 10
4
TOTAL STEPS 11
4
TOTAL STEPS 12
4
TOTAL STEPS 13
4
TOTAL STEPS 14
4
...
</code>```

My question is about the meaning of 'return "HOME"'. Does it simply mean STOP. Is there any meaning of "HOME" in there?

答:
If you were to run the function in a variable assignment you would literally get "DONE". I'm assuming you mean "DONE" instead of "HOME" since there is no return "HOME" in your example.

For instance:

```<code>x = per(7)
print(x)
</code>```

Would print the usual output and also print DONE when you called print(x). Because 7 is a single digit the condition if len(str(n)) == 1 is met on the first run..

```<code>TOTAL STEPS 0
DONE
</code>```

This function calls itself though, which makes it a confusing choice to learn about this stuff since that's fairly unusual. If we run the script with a number with more than one digit, we'll get None instead.. because it never runs the return statement, it's return value is the python default, which is a NoneType:

```<code>x = per(27)
print(x)
</code>```

Result:

```<code>14
4
TOTAL STEPS 2
None
</code>```

Because 27 doesn't meet the condition of having a single digit.. the script calls itself with the results it's printing out.. until it finally uses 4.. which meets the condition and prints out the TOTAL STEPS line.

To see this value we have to modify the function:

```<code>def per(n, steps = 0):
    if len(str(n)) == 1:
        print("TOTAL STEPS " + str(steps))
        return "DONE"

    steps += 1
    digits = [int(i) for i in str(n)]

    result = 1
    for j in digits:
        result *= j
    print(result)
    x = per(result, steps)
    print("Inner return", x)

x = per(27)
print("Outer return", x)
</code>```

Result:

```<code>14
4
TOTAL STEPS 2
Inner return DONE
Inner return None
Outer return None
</code>```

Thankfully you don't have to worry too much about return values.. since you aren't capturing the return value in a variable in your example.. just using return by itself would have the same result. Which is to stop running the function at that point, and to move on to the line after per(27) if there was one.. it can be a useful way to see what's happening in this function though.

Using variable assignment with = is not the only way to use a return value.. just the easiest way to demonstrate what's happening.
for instance just running print(per(27)) would have the same result as my example.

Body:
For context, this code is written on a video within the channel Numberphile by Matt Parker talking about multiplication persistence. The code is written in Python 2, and my question is about the line return "DONE".

Evidently, this prevents an infinite loop from being generated, as it is clear running an example (below) with and without that line:

def per(n, steps = 0):
    if len(str(n)) == 1:
        print "TOTAL STEPS " + str(steps)
        return "DONE"

    steps += 1
    digits = [int(i) for i in str(n)]

    result = 1
    for j in digits:
        result *= j
    print result
    per (result, steps)

per(27)

# 14
# 4
# TOTAL STEPS 2

Now, the same code without the line return "DONE" would not end the loop, and yield:

14
4
TOTAL STEPS 2
4
TOTAL STEPS 3
4
TOTAL STEPS 4
4
TOTAL STEPS 5
4
TOTAL STEPS 6
4
TOTAL STEPS 7
4
TOTAL STEPS 8
4
TOTAL STEPS 9
4
TOTAL STEPS 10
4
TOTAL STEPS 11
4
TOTAL STEPS 12
4
TOTAL STEPS 13
4
TOTAL STEPS 14
4
...

My question is about the meaning of 'return "HOME"'. Does it simply mean STOP. Is there any meaning of "HOME" in there?

Body:
If you were to run the function in a variable assignment you would literally get "DONE". I'm assuming you mean "DONE" instead of "HOME" since there is no return "HOME" in your example.

For instance:

x = per(7)
print(x)

Would print the usual output and also print DONE when you called print(x). Because 7 is a single digit the condition if len(str(n)) == 1 is met on the first run..

TOTAL STEPS 0
DONE

This function calls itself though, which makes it a confusing choice to learn about this stuff since that's fairly unusual. If we run the script with a number with more than one digit, we'll get None instead.. because it never runs the return statement, it's return value is the python default, which is a NoneType:

x = per(27)
print(x)

Result:

14
4
TOTAL STEPS 2
None

Because 27 doesn't meet the condition of having a single digit.. the script calls itself with the results it's printing out.. until it finally uses 4.. which meets the condition and prints out the TOTAL STEPS line.

To see this value we have to modify the function:

def per(n, steps = 0):
    if len(str(n)) == 1:
        print("TOTAL STEPS " + str(steps))
        return "DONE"

    steps += 1
    digits = [int(i) for i in str(n)]

    result = 1
    for j in digits:
        result *= j
    print(result)
    x = per(result, steps)
    print("Inner return", x)

x = per(27)
print("Outer return", x)

Result:

14
4
TOTAL STEPS 2
Inner return DONE
Inner return None
Outer return None

Thankfully you don't have to worry too much about return values.. since you aren't capturing the return value in a variable in your example.. just using return by itself would have the same result. Which is to stop running the function at that point, and to move on to the line after per(27) if there was one.. it can be a useful way to see what's happening in this function though.

Using variable assignment with = is not the only way to use a return value.. just the easiest way to demonstrate what's happening.
for instance just running print(per(27)) would have the same result as my example.


问:
How to get absolute mouse position with WM_INPUT set up?
I'm working on Direct3D Game engine, I got my mouse and keyboard setup from my previous project, but recently ran into problem:

The thing is, my engine is for a shooter/slasher game, so it requires a direct input, which was set in previous project using RAWMOUSE and WM_INPUT message parsing.

```<code>    case WM_INPUT:
        if (wParam == RIM_INPUT)
        {
            dword dwSize = 48;
            RAWINPUT raw;

            if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, &raw, &dwSize,
                sizeof(RAWINPUTHEADER)) != dwSize)
                OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));

            if (raw.header.dwType == RIM_TYPEMOUSE)
            {
                this->mouse.TranslateMouseInput(raw.data.mouse);
            }
            break;
        }
</code>```

Problem is, that code returns only relative movement of mouse, it's useful in setting up a camera lookup, but when it comes to menu or basic GUI, which are controlled by mouse (buttons etc...) things go bad: GUI and other controls require cursor position to be calculated relative to client rectangle.

Closest thing I found to answer in WinAPI is GetCursorPos() combined with GetWindowRect(), but if window has a title bar relative offset of it does not count and (0,0) coordinate is set at the top of the title bar, but not on the client region.

How do I solve the issue without losing a relative mouse movement?

-Should I try parsing WM_MOUSEMOVE messages with WM_INPUT?

I've looked for a popular input solution for game engines, but didn't find any particular one.

Additional Info:

Mouse.cpp file

Mouse.h

答:
Your best option when you need absolute mouse position is to use standard WM_MOUSE* messages, and only use WM_INPUT for relative mouse position. Typically you have a mode transition when bringing up a UI or some other aspect for getting in/out of relative 'look' mode.

WM_INPUT provides only relative information in most cases, and if you attempt to emulate absolute yourself you will be missing a lot of pointer ballistics that makes it feel really off.

Note that if you want your game to support use via remote desktop (typically for testing), then you need to deal with emulating relative input from absolute position because in the case of a virtual desktop you never get relative, only absolute, from WM_INPUT. This is indicated by MOUSE_VIRTUAL_DESKTOP.

You may want to take a look at the Mouse class implementation in DirectX Tool Kit.

Body:
I'm working on Direct3D Game engine, I got my mouse and keyboard setup from my previous project, but recently ran into problem:

The thing is, my engine is for a shooter/slasher game, so it requires a direct input, which was set in previous project using RAWMOUSE and WM_INPUT message parsing.

    case WM_INPUT:
        if (wParam == RIM_INPUT)
        {
            dword dwSize = 48;
            RAWINPUT raw;

            if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, &raw, &dwSize,
                sizeof(RAWINPUTHEADER)) != dwSize)
                OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));

            if (raw.header.dwType == RIM_TYPEMOUSE)
            {
                this->mouse.TranslateMouseInput(raw.data.mouse);
            }
            break;
        }

Problem is, that code returns only relative movement of mouse, it's useful in setting up a camera lookup, but when it comes to menu or basic GUI, which are controlled by mouse (buttons etc...) things go bad: GUI and other controls require cursor position to be calculated relative to client rectangle.

Closest thing I found to answer in WinAPI is GetCursorPos() combined with GetWindowRect(), but if window has a title bar relative offset of it does not count and (0,0) coordinate is set at the top of the title bar, but not on the client region.

How do I solve the issue without losing a relative mouse movement?

-Should I try parsing WM_MOUSEMOVE messages with WM_INPUT?

I've looked for a popular input solution for game engines, but didn't find any particular one.

Additional Info:

Mouse.cpp file

Mouse.h


问:
Closing a CallableStatement
```<code>public void XXX(){
    Connection conn = ~~;
    CallableStatement cstmt = conn.prepareCall("{call XXX");
    cstmt.executeUpdate();
    cstmt.close();
}
</code>```

All methods that CallableStatement is described in close() line by line by the method like the above-mentioned.
Cannot how to do close() in each method by the automatic operation be done?

Does the method that can be achieved with java5 or java6 exist?

Please tell me a better expression, because, I'm Japanese.

答:
try-with-resources

The modern approach uses the try-with-resources feature added to Java 7. A “resource” here means any object of a class implementing the AutoCloseable interface with its single method close. See Oracle Tutorial.

The try-with-resources syntax inserts a pair of parentheses between the try and its curly braces. Inside those parens you declare and initialize your resource object(s). You can have more than one resource within those parens. Each resource is declared and initialized on a statement line. Each line ends in a semicolon like any Java statement though the last semicolon is optional.

```<code>try (
    Connection conn = myDataSource.getConnection() ;
    Callable cstmt = conn.prepareCall( sql ) ;
) {
    cstmt.executeUpdate() ;
} catch ( … ) {
    …
}
</code>```

By the way, in Java 9 and later you can declare and initialize your resource object outside the parens, earlier in your code. In this case, just put the resource’s variable name inside the parens to have it automatically closed.

Notice that we need not bother with a finally. The try-with-resources will call close on any of the resources that were successfully instantiated even if an exception is thrown at some point. The resources are closed in the reverse order in which they were declared.

ContentLicense: CC BY-SA 2.5

Title: Closing a CallableStatement

Body:
public void XXX(){
    Connection conn = ~~;
    CallableStatement cstmt = conn.prepareCall("{call XXX");
    cstmt.executeUpdate();
    cstmt.close();
}

All methods that CallableStatement is described in close() line by line by the method like the above-mentioned.
Cannot how to do close() in each method by the automatic operation be done?

Does the method that can be achieved with java5 or java6 exist?

Please tell me a better expression, because, I'm Japanese.

Body:
try-with-resources

The modern approach uses the try-with-resources feature added to Java 7. A “resource” here means any object of a class implementing the AutoCloseable interface with its single method close. See Oracle Tutorial.

The try-with-resources syntax inserts a pair of parentheses between the try and its curly braces. Inside those parens you declare and initialize your resource object(s). You can have more than one resource within those parens. Each resource is declared and initialized on a statement line. Each line ends in a semicolon like any Java statement though the last semicolon is optional.

try (
    Connection conn = myDataSource.getConnection() ;
    Callable cstmt = conn.prepareCall( sql ) ;
) {
    cstmt.executeUpdate() ;
} catch ( … ) {
    …
}

By the way, in Java 9 and later you can declare and initialize your resource object outside the parens, earlier in your code. In this case, just put the resource’s variable name inside the parens to have it automatically closed.

Notice that we need not bother with a finally. The try-with-resources will call close on any of the resources that were successfully instantiated even if an exception is thrown at some point. The resources are closed in the reverse order in which they were declared.


问:
Preventing progressive download of mp3?
I'm looking for some solutions for creating an mp3 player in flash; one that either uses streaming or some kind of obfuscation to prevent users from downloading the source mp3. If I used a server/solution that used the RMTP: protocol, would that prevent the download? Are there any possibilities for using Amazon S3 server for serving the files but hiding the actual URL of the file?</p>

答:
jw media player supports this.

http://www.longtailvideo.com/players/jw-flv-player/

OwnerDisplayName: TypeOneError

Title: Preventing progressive download of mp3?

OwnerDisplayName: BenBruscella


问:
How to get part of a URL?
How can I remove all the parts from url except base url and first part. There is no certainty in number of parts. Base url is variable. I tried some regex but in vain. </p>

<pre class="lang-php prettyprint-override"><code>$url =  http://www.example.com/part1/part2/part3/part4;
base_url = parse_url($url, PHP_URL_HOST); // Outputs www.example.com

$desired_output = http://www.example.com/part1;
</code>```

答:
Here we can use a preg_replace, with a simple expression, maybe similar to:

```<code>(.+\.com\/.+?\/).+
</code>```

where we are capturing our desired output using this capturing group:

```<code>(.+\.com\/.+?\/)
</code>```

and then we swipe to the end of string and replace it with $1.

Test

```<code>$re = '/(.+\.com\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

For all domains .com or not, we might be able to solve it with this expression:

```<code>(.+\..+?\/.+?\/).+
</code>```

Test

```<code>$re = '/(.+\..+?\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;
</code>```

Demo

Title: How to get part of a URL?

Body:
How can I remove all the parts from url except base url and first part. There is no certainty in number of parts. Base url is variable. I tried some regex but in vain.

$url =  http://www.example.com/part1/part2/part3/part4;
base_url = parse_url($url, PHP_URL_HOST); // Outputs www.example.com

$desired_output = http://www.example.com/part1;

Body:
Here we can use a preg_replace, with a simple expression, maybe similar to:

(.+\.com\/.+?\/).+

where we are capturing our desired output using this capturing group:

(.+\.com\/.+?\/)

and then we swipe to the end of string and replace it with $1.

Test

$re = '/(.+\.com\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

For all domains .com or not, we might be able to solve it with this expression:

(.+\..+?\/.+?\/).+

Test

$re = '/(.+\..+?\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;

Demo


问:
Slickgrid changes the ID from my data and dont clean up the empty row
Im trying to update my grid without the need for refreshing! Right now, it updates only the grid, but dont know why, it changes the id to the last one inserted and dont "clean up" the empty row! When I try to insert data, it clears it .
Im kinda new with ajax and slickgrid! I've tried to see the ajax example from slickgrid, but I got some errors!
Do I need to re-upload the onCellChange and so on ? I just wanted to update th grid with the new data.
Any help?

Thanks in advance

So, I've tried re-draw the table re-using my actual drawning code, but im failling to re-draw with correct data.

Function to re-draw grid

```<code>function desenhaGrid() {
    $("#myGrid").ready(function () {
        $(function () {
            $.ajax({
                type: "GET",
                url: '/SlickGrid/GetData',
                dataType: 'json',
                success: function (jsonResult) {
                    for (var key in jsonResult) {
                        if (jsonResult.hasOwnProperty(key)) {
                            //print table
                            var d = (data[key] = {});
                            for (var i = 0; i < data.length; i++) {
                                d["#"] = i + 1;
                            }
                            d["id"] = jsonResult[key].id;
                            d["t_nome"] = jsonResult[key].t_nome;
                            d["t_prof"] = jsonResult[key].t_prof;
                            d["t_data"] = jsonResult[key].t_data;
                            d["t_morada"] = jsonResult[key].t_morada;
                            d["t_percCompleto"] = jsonResult[key].t_percCompleto;
                        }
                    }

                    grid = new Slick.Grid("#myGrid", dataView, columns, options);

                   dataView.beginUpdate();
                   grid.invalidateAllRows();
                   dataView.setItems(data);
                   grid.render();
                   dataView.endUpdate();
                                       }
            });

        });
    });
}
</code>```

and this is my onAddNewRow

```<code>        grid.onAddNewRow.subscribe(function (e, args) {
            var idData = jsonResult[key].id + 1;
            var item = { "id": idData, "t_nome": '', "t_prof": '', "t_data": '', "t_morada": '', "t_percCompleto": '' };
            $.extend(item, args.item);
            dataView.addItem(item);
            //if user press enter
            grid.onKeyDown.subscribe(function (e) {
                var keyPressed = event.keyCode || event.which;
                if (keyPressed == 13) {
                    alert("add");
                    var myJSON = JSON.stringify(item);
                    $.post("/SlickGrid/addGridEnter", $("input[name=mydata]").val(myJSON));
                    console.log(myJSON);
                    desenhaGrid();
                }
            });

        });
</code>```

I expected it to re-draw my grid with all the data. Instead, its changing all the id's to the last one inserted and when I try to insert data in the last row, wont let me (it clears it after I leave the cell).

UPDATE:

I've udpate the function to draw the grid

```<code>function desenhaGrid() {
    $("#myGrid").load(function () {
        $(function () {
            $.ajax({
                type: "GET",
                url: '/SlickGrid/GetData',
                dataType: 'json',
                success: function (jsonResult) {
                    dataView.beginUpdate();
                    grid.invalidateAllRows();
                    dataView.setItems(jsonResult);
                    dataView.endUpdate();
                    grid.render();
                }
            });

        });
    });
}
</code>```

答:
I don't think this is a SlickGrid issue. There are all kind of problems with the javascript. For example:

why are you using $("#myGrid").ready( ? the ready event only fires when the DOM has finished loading

the entire copy operation from jsonResult to data just ends up with the same data. why not use jsonResult directly?

the section for (var i = 0; i < data.length; i++) { d["#"] = i + 1; }
runs once for each row added to data, it should just run once at the end, outside of the loop

you are subscribing to the keydown event once for each row added to the grid. you should just subscribe once. listening for an Enter key is also a very poor method of determining if a row has been entered. what if someone clicks on another row before pressing Enter?

Slickgrid is a client-side grid. This means data does not need to be persisted after every change. It's a common approach to use a 'save' button, or detect if the active row has changed.

Body:
Im trying to update my grid without the need for refreshing! Right now, it updates only the grid, but dont know why, it changes the id to the last one inserted and dont "clean up" the empty row! When I try to insert data, it clears it .
Im kinda new with ajax and slickgrid! I've tried to see the ajax example from slickgrid, but I got some errors!
Do I need to re-upload the onCellChange and so on ? I just wanted to update th grid with the new data.
Any help?

Thanks in advance

So, I've tried re-draw the table re-using my actual drawning code, but im failling to re-draw with correct data.

Function to re-draw grid

function desenhaGrid() {
    $("#myGrid").ready(function () {
        $(function () {
            $.ajax({
                type: "GET",
                url: '/SlickGrid/GetData',
                dataType: 'json',
                success: function (jsonResult) {
                    for (var key in jsonResult) {
                        if (jsonResult.hasOwnProperty(key)) {
                            //print table
                            var d = (data[key] = {});
                            for (var i = 0; i < data.length; i++) {
                                d["#"] = i + 1;
                            }
                            d["id"] = jsonResult[key].id;
                            d["t_nome"] = jsonResult[key].t_nome;
                            d["t_prof"] = jsonResult[key].t_prof;
                            d["t_data"] = jsonResult[key].t_data;
                            d["t_morada"] = jsonResult[key].t_morada;
                            d["t_percCompleto"] = jsonResult[key].t_percCompleto;
                        }
                    }

                    grid = new Slick.Grid("#myGrid", dataView, columns, options);

                   dataView.beginUpdate();
                   grid.invalidateAllRows();
                   dataView.setItems(data);
                   grid.render();
                   dataView.endUpdate();
                                       }
            });

        });
    });
}

and this is my onAddNewRow

        grid.onAddNewRow.subscribe(function (e, args) {
            var idData = jsonResult[key].id + 1;
            var item = { "id": idData, "t_nome": '', "t_prof": '', "t_data": '', "t_morada": '', "t_percCompleto": '' };
            $.extend(item, args.item);
            dataView.addItem(item);
            //if user press enter
            grid.onKeyDown.subscribe(function (e) {
                var keyPressed = event.keyCode || event.which;
                if (keyPressed == 13) {
                    alert("add");
                    var myJSON = JSON.stringify(item);
                    $.post("/SlickGrid/addGridEnter", $("input[name=mydata]").val(myJSON));
                    console.log(myJSON);
                    desenhaGrid();
                }
            });

        });

I expected it to re-draw my grid with all the data. Instead, its changing all the id's to the last one inserted and when I try to insert data in the last row, wont let me (it clears it after I leave the cell).

UPDATE:

I've udpate the function to draw the grid

function desenhaGrid() {
    $("#myGrid").load(function () {
        $(function () {
            $.ajax({
                type: "GET",
                url: '/SlickGrid/GetData',
                dataType: 'json',
                success: function (jsonResult) {
                    dataView.beginUpdate();
                    grid.invalidateAllRows();
                    dataView.setItems(jsonResult);
                    dataView.endUpdate();
                    grid.render();
                }
            });

        });
    });
}


问:
Can you load standard zeppelin interpreter settings from S3?
Our company is building up a suite of common internal Spark functions and jobs, and  I'd like to make sure that our data scientists have access to all of these when they prototype in Zeppelin.

Ideally, I'd like a way for them to start up a Zeppelin notebook on AWS EMR, and have the dependency jar we build automatically loaded onto it without them having to manually type in the maven information manually every time (private repo location/credentials, package info, etc).

Right now we have the dependency jar loaded on S3, and with some work we could get a private maven repository to host it on.

I see that ZEPPELIN_INTERPRETER_DIR saves off interpreter settings, but I don't think it can load from a common default location (like S3, or something)

Is there a way to tell Zeppelin on an EMR cluster to load it's interpreter settings from a common location? I can't be the first person to want this.

Other thoughts I've had but have not tried yet:

Have a script that uses aws cmd line options to start a EMR cluster with all the necessary settings pre-made for you. (Could also upload the .jar dependency if we can't get maven to work)

Use a infrastructure-as-code framework to start up the clusters with the required settings.

答: I don't believe it's possible to tell EMR to load settings from a common location. The first thought you included is the way to go imo - you would aws emr create ... and that create would include a shell script step to replace /etc/zeppelin/conf.dist/interpreter.json by downloading the interpreter.json of interest from S3, and then hard restart zeppelin (sudo stop zeppelin; sudo start zeppelin).


问:
PHP Exception memory leak
In my console application, I replaced displaying all PHP built-in error types with throwing ErrorException:

```<code>set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }

    throw new ErrorException($message, 0, $severity, $file, $line);
});
</code>```

It works great, but there's one problem. Consider the following snippet:

```<code>for ($id = 1;; $id += 1) {
    try {
        $html = file_get_contents('https://stackoverflow.com/boo/' . $id);
    } catch (Exception $exception) {
        // Failed
    }
}
</code>```

Every ErrorException thrown keeps the stack history. In real-life example, some IDs are missing and that causes, so after thousands of iterations, eventually the memory leak occurs.

What can be done to fix this problem? Is throwing and catching exceptions is a loop wrong? Or maybe I could disable the stacking behavior somehow?

答:
You can unset the Exception object once you've used it on each iteration:

```<code>function getLevels($start_idx,$levels = 9){
   try {
            return $this->getBinaryTree($levels);
        } catch (Exception $e) {
            switch($e->getMessage()){
            case "Almost out of memory":
               $max_tree_depth = (int)($levels/2);
               if($max_tree_depth >= 2){
                    unset($e); // <------------------------ RIGHT HERE!
                    return $this->getLevels($start_idx,$max_tree_depth);
               }else{
                    throw new Exception("Out of memory even after getting tree with 2 levels");
               }
               break;
            default:
               throw $e;
         }
     }
}
</code>```

I found the solution on the link below:

https://stuporglue.org/php-memory-leak-when-throwing-catching-and-recursing/

ContentLicense: CC BY-SA 3.0

Title: PHP Exception memory leak

Body:
In my console application, I replaced displaying all PHP built-in error types with throwing ErrorException:

set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }

    throw new ErrorException($message, 0, $severity, $file, $line);
});

It works great, but there's one problem. Consider the following snippet:

for ($id = 1;; $id += 1) {
    try {
        $html = file_get_contents('https://stackoverflow.com/boo/' . $id);
    } catch (Exception $exception) {
        // Failed
    }
}

Every ErrorException thrown keeps the stack history. In real-life example, some IDs are missing and that causes, so after thousands of iterations, eventually the memory leak occurs.

What can be done to fix this problem? Is throwing and catching exceptions is a loop wrong? Or maybe I could disable the stacking behavior somehow?

Body:
You can unset the Exception object once you've used it on each iteration:

function getLevels($start_idx,$levels = 9){
   try {
            return $this->getBinaryTree($levels);
        } catch (Exception $e) {
            switch($e->getMessage()){
            case "Almost out of memory":
               $max_tree_depth = (int)($levels/2);
               if($max_tree_depth >= 2){
                    unset($e); // <------------------------ RIGHT HERE!
                    return $this->getLevels($start_idx,$max_tree_depth);
               }else{
                    throw new Exception("Out of memory even after getting tree with 2 levels");
               }
               break;
            default:
               throw $e;
         }
     }
}

I found the solution on the link below:

https://stuporglue.org/php-memory-leak-when-throwing-catching-and-recursing/


问:
GTK application don't run in windows
I develop a little test to study C# and GTK. In linux, this works perfectly, but when I try to run this in windows never works. The project is a simple calc.

In these windows I install:

dotNetx45_Full

gtk2runtime-2.24.10-2012-10-10

gtk-sharp-2.12.45

At this moment when I run in windows the feedback in windows events is:

```<code>Application: Calculadora.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Information: System.DllNotFoundException
Stack:
   in GLib.Object.gtksharp_register_type (IntPtr, IntPtr)
   in GLib.Object.RegisterGType (System.Type)
   in GLib.Object.LookupGType (System.Type)
   in GLib.Object.LookupGType ()
   in GLib.Object.CreateNativeObject (IntPtr [], GLib.Value [], Int32)
   in Gtk.Window..ctor (Gtk.WindowType)
   in Calculator.MainClass.Main (System.String [])
</code>```

Thanks for all help!

答: That is odd. Gtk# says it targets gnome 2.20. It may be that you have some conflict between the versions in Gtk# and those in the Gtk2 runtime which look newer (2.24). I believe you should not need this runtime as the Gtk# installer should come with a runtime. It looks like the version of glib being loaded at runtime knows nothing about IntPtr. Could you have downloaded the mono version of gtk# rather than the .Net version? Try https://dl.xamarin.com/GTKforWindows/Windows/gtk-sharp-2.12.45.msi</p>

Title: GTK application don't run in windows

Body:
I develop a little test to study C# and GTK. In linux, this works perfectly, but when I try to run this in windows never works. The project is a simple calc.

In these windows I install:

dotNetx45_Full

gtk2runtime-2.24.10-2012-10-10

gtk-sharp-2.12.45

At this moment when I run in windows the feedback in windows events is:

Application: Calculadora.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Information: System.DllNotFoundException
Stack:
   in GLib.Object.gtksharp_register_type (IntPtr, IntPtr)
   in GLib.Object.RegisterGType (System.Type)
   in GLib.Object.LookupGType (System.Type)
   in GLib.Object.LookupGType ()
   in GLib.Object.CreateNativeObject (IntPtr [], GLib.Value [], Int32)
   in Gtk.Window..ctor (Gtk.WindowType)
   in Calculator.MainClass.Main (System.String [])

Thanks for all help!


问:
Why my jQuery ajax call is not successful
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

```<code>$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })
</code>```

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

----------------EDIT---------------

Hi, I changed to use localhost request like:

```<code>$.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'xml',
            data: {id: 43},
            success: function(data) {

                alert(data);

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

But I got the same error... more suggestions please... thank you.

答:
This is possibly due to cross domain access control. You are accessing the site which is on your machine which tries to connect to another website. This is not allowed unless you define Access-Control-Allow-Origin headers.

Also as @Craig said, content type as xml is needs to be changed.

Body:
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

----------------EDIT---------------

Hi, I changed to use localhost request like:

$.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'xml',
            data: {id: 43},
            success: function(data) {

                alert(data);

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

But I got the same error... more suggestions please... thank you.


问:
How to run a function before all handlers?
Is it possible to execute a function before any handlers in a web application using the net/http package or any of the gorilla libraries?

This would be useful, for instance, to check if the incoming request is from a blacklisted IP address before proceeding to the actual request handlers.

答:
If you want to use the default muxer, which i find is common, you can create middleware like so:

```<code>func mustBeLoggedIn(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        // Am i logged in?
        if ...not logged in... {
            http.Error(w, err.Error(), http.StatusUnauthorized)
            return
        }
        // Pass through to the original handler.
        handler(w, r)
    }
}
</code>```

Use it like so:

```<code>http.HandleFunc("/some/priveliged/action", mustBeLoggedIn(myVanillaHandler))
http.ListenAndServe(":80", nil)
</code>```

Body:
If you want to use the default muxer, which i find is common, you can create middleware like so:

func mustBeLoggedIn(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        // Am i logged in?
        if ...not logged in... {
            http.Error(w, err.Error(), http.StatusUnauthorized)
            return
        }
        // Pass through to the original handler.
        handler(w, r)
    }
}

Use it like so:

http.HandleFunc("/some/priveliged/action", mustBeLoggedIn(myVanillaHandler))
http.ListenAndServe(":80", nil)


问:
How to transfer some data to another Fragment?
How to transfer some data to another Fragment likewise it was done with extras for intents?

答:
From Activity Class:

Send the data using bundle arguments to the fragment and load the fragment

```<code>   Fragment fragment = new myFragment();
   Bundle bundle = new Bundle();
   bundle.putString("pName", personName);
   bundle.putString("pEmail", personEmail);
   bundle.putString("pId", personId);
   fragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    fragment).commit();
</code>```

From myFragment Class:

Get the arguments from the bundle and set them to xml

```<code>    Bundle arguments = getArguments();
    String personName = arguments.getString("pName");
    String personEmail = arguments.getString("pEmail");
    String personId = arguments.getString("pId");

    nameTV = v.findViewById(R.id.name);
    emailTV = v.findViewById(R.id.email);
    idTV = v.findViewById(R.id.id);

    nameTV.setText("Name: "+ personName);
    emailTV.setText("Email: "+ personEmail);
    idTV.setText("ID: "+ personId);
</code>```

Body:
From Activity Class:

Send the data using bundle arguments to the fragment and load the fragment

   Fragment fragment = new myFragment();
   Bundle bundle = new Bundle();
   bundle.putString("pName", personName);
   bundle.putString("pEmail", personEmail);
   bundle.putString("pId", personId);
   fragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    fragment).commit();

From myFragment Class:

Get the arguments from the bundle and set them to xml

    Bundle arguments = getArguments();
    String personName = arguments.getString("pName");
    String personEmail = arguments.getString("pEmail");
    String personId = arguments.getString("pId");

    nameTV = v.findViewById(R.id.name);
    emailTV = v.findViewById(R.id.email);
    idTV = v.findViewById(R.id.id);

    nameTV.setText("Name: "+ personName);
    emailTV.setText("Email: "+ personEmail);
    idTV.setText("ID: "+ personId);


问:
Deploying web app from Visual Studio Code to Azure but leave out a data folder
I am building a very small Node/Express API app in Azure using Twilio to route communication for a small group.  I initially built out a data structure for users in CosmosDB but found out it's minimum $24 per month, which is way over budget for something that will likely hold 20 or so records.  Because of this, is seems much more reasonable to just build this into a json file that sits in a ./json subfolder.  However, it has occurred to me that whenever I deploy, I would be overwriting this file with the default file I have locally. I have been working via the Azure App Service tool in Visual Studio Code and can't figure out a way to make it ignore the file.

I can go into Kudu and copy the file down each time before I deploy, but I will eventually forget and this sounds like a very brittle process.

I added a json/ line to .gitignore, but that has no effect on the deployment (as expected).

I also added "appService.zipIgnorePattern": ["json{,/**}"] to the settings.json file, but instead of just ignoring that folder on the server, it erases it on deploy (the zip ignores it and then it wipes/replaces the whole wwwsite folder).  Looking for the file gives me {"Message":"'D:\\home\\site\\wwwroot\\json\\users.json' not found."}

I was hoping there is a setting that would deploy, replacing all folders in the package, and ignoring all content in the ./json folder.  Does this exist?

答: Using VS Code right+click deploy will deploy the contents of the folder. I was able to work around this by adding Azure as a remote branch and using .gitignore. I placed my json file inside a random folder (content/json) then placed /content/json in my .gitignore file.


问:
How do I ensure keys of a key-value mapping are unique in SHACL?
Suppose my data models a key-value-mapping, for example, I run a fancy hotel and want to keep track of my guests' orders for every meal. How do I ensure that for each meal, I get every guest's order (i.e. all keys are present) and per guest I only have one order (i.e. all keys are unique)?

Example code to get us started:

Shapes:

```<code>ex:MealShape
    a sh:NodeShape ;
    sh:targetClass ex:Meal ;
    sh:property [
        sh:path ex:orders ;
        sh:minCount 2 ;
        sh:maxCount 2 ;
        sh:node ex:OrderShape ;
    ] .

ex:OrderShape
    a sh:NodeShape ;
    sh:targetClass ex:Order ;
    sh:property [
        sh:path ex:guest ;
        # The guest list! Code maintenance should happen here.
        sh:in ( "James" "Margaret" ) ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:order ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] .
</code>```

Data:

```<code>## Guests
ex:james ex:name "James" .
ex:margaret ex:name "Margaret" .

## Meals
### Valid meal
ex:breakfast
    a ex:Meal ;
    ex:orders [ ex:guest "James" ; ex:order "Eggs" ] ;
    ex:orders [ ex:guest "Margaret" ; ex:order "Cereal" ] .

### DESIRED TO BE invalid meal
### currently does not cause a validation result
ex:lunch
    a ex:Meal ;
    ex:orders [ ex:guest "James" ; ex:order "Salad" ] ;
    # Problem: James placed two orders, Maggie placed zero
    ex:orders [ ex:guest "James" ; ex:order "Burger" ] .
</code>```

One solution I am aware of is to use qualifiedShape and its minCount and maxCount constraints separately for each key in the list. However, for larger "guest lists" this becomes hard to maintain. In my work, I have a list of roughly 40 keys. With 40 blocks of qualifiedShape statements, it becomes impractical to inspect the list (and I have already scripted the generation of those statements in the first place).

I have searched the documentation but could not find a kind of "sh:disjointInScope" or "sh:uniqueFromList" statement I wanted (crucially, the constraint should not force the value to be unique in the entire data graph, since e.g. James might appear in several orders). How do I get the desired behavior in human-readable SHACL code?

答:
If I understand your particular scenario correctly, then this should give you the violation:

```<code>ex:MealShape
  sh:property [
      sh:path ( ex:orders ex:guest ) ;
      sh:maxCount 2 ;
      sh:minCount 2 ;
  ] ...
</code>```

The mechanism here is that a path expression (ex:orders/ex:guest in SPARQL notation) is used to state that there need to be exactly two distinct guests per Meal, which also implies that each of them can only be part of one order. Combined with the sh:in, this makes sure that only the allowed keys are present, and all of them. You need to however align the length of the sh:in list with the sh:min/max counts, so I am not sure how manageable that would be.

You can probably further generalize this pattern with the help of SHACL-SPARQL, e.g. to introduce the higher-level constraint components that you are talking about.

Body:
Suppose my data models a key-value-mapping, for example, I run a fancy hotel and want to keep track of my guests' orders for every meal. How do I ensure that for each meal, I get every guest's order (i.e. all keys are present) and per guest I only have one order (i.e. all keys are unique)?

Example code to get us started:

Shapes:

ex:MealShape
    a sh:NodeShape ;
    sh:targetClass ex:Meal ;
    sh:property [
        sh:path ex:orders ;
        sh:minCount 2 ;
        sh:maxCount 2 ;
        sh:node ex:OrderShape ;
    ] .

ex:OrderShape
    a sh:NodeShape ;
    sh:targetClass ex:Order ;
    sh:property [
        sh:path ex:guest ;
        # The guest list! Code maintenance should happen here.
        sh:in ( "James" "Margaret" ) ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:order ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] .

Data:

## Guests
ex:james ex:name "James" .
ex:margaret ex:name "Margaret" .

## Meals
### Valid meal
ex:breakfast
    a ex:Meal ;
    ex:orders [ ex:guest "James" ; ex:order "Eggs" ] ;
    ex:orders [ ex:guest "Margaret" ; ex:order "Cereal" ] .

### DESIRED TO BE invalid meal
### currently does not cause a validation result
ex:lunch
    a ex:Meal ;
    ex:orders [ ex:guest "James" ; ex:order "Salad" ] ;
    # Problem: James placed two orders, Maggie placed zero
    ex:orders [ ex:guest "James" ; ex:order "Burger" ] .

One solution I am aware of is to use qualifiedShape and its minCount and maxCount constraints separately for each key in the list. However, for larger "guest lists" this becomes hard to maintain. In my work, I have a list of roughly 40 keys. With 40 blocks of qualifiedShape statements, it becomes impractical to inspect the list (and I have already scripted the generation of those statements in the first place).

I have searched the documentation but could not find a kind of "sh:disjointInScope" or "sh:uniqueFromList" statement I wanted (crucially, the constraint should not force the value to be unique in the entire data graph, since e.g. James might appear in several orders). How do I get the desired behavior in human-readable SHACL code?

Body:
If I understand your particular scenario correctly, then this should give you the violation:

ex:MealShape
  sh:property [
      sh:path ( ex:orders ex:guest ) ;
      sh:maxCount 2 ;
      sh:minCount 2 ;
  ] ...

The mechanism here is that a path expression (ex:orders/ex:guest in SPARQL notation) is used to state that there need to be exactly two distinct guests per Meal, which also implies that each of them can only be part of one order. Combined with the sh:in, this makes sure that only the allowed keys are present, and all of them. You need to however align the length of the sh:in list with the sh:min/max counts, so I am not sure how manageable that would be.

You can probably further generalize this pattern with the help of SHACL-SPARQL, e.g. to introduce the higher-level constraint components that you are talking about.


问:
WIX Installer - Unable to change and save the platform to 64 bit

IDE:- VS.NET 2013 (Update 2)

WIX version used : 3.9

Windows service MSI :- I am unable to change the platform to x64 bit and save it. If i change it to x64 option and save the build properties and close the property window, then reopen the property window again. The x86 option pops up again.. Although, the DLL's used in the project are coming as 64 bit based.

It is very annoying and frustrating. After i hit the Build on the ServiceSetup project, the .MSI file get generated. The MSI contains the windows service .exe file which unfortunately is 32 bit based. I want the windows service .exe file to be 64 bit.

Please suggest any soln.

答:
I had this same issue. It was very frustrating.
Somehow I got around it by:

Open configuration Manager

Create a new "x64" solution platform, without copying settings from the x86 and "Create new solution platforms" checked.

Ensure in this configuration manager window, the Active solution platform and the platform dropdown for the project are both x64 .. If needed, delete the x86 options from the configuration manager

Go to the Project Properties> Build tab

Ensure the platform dropbox says Active(x64), if not, select it.

Re-open the Build tab and check it still has the Active(x64). Sometimes the build active platform would switch to x86 when I put it as x64, but you first need to ensure step 3 is set.


问:
Clang and Gcc disagree on explicit specialization after instantiation
In some code I am reviewing I ran into a case where Clang and Gcc disagree. After looking around awhile I cant seem to figure out who is right.

Disclaimer:  I know there is a better Singleton pattern, but this is the one used in the code.

Notes:

gcc 7.4.0 on Ubuntu (No error)

clang 6.0.0 on Ubuntu (Throws error)

Difference appears to exist for all post C++11 ISO versions, but I did not try earlier.

foo.hh

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

class Foo {
    public:
    Foo();
    ~Foo();
    static Foo *getSingleton(){
        return singleton<Foo>::instance();
    }
};
</code>```

foo.cc

```<code>include "foo.hh"
//removing this line results in the error for clang disappearing
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
int main(){};
</code>```

sing.hh

```<code>template<typename T>
class singleton{
    typedef T *(*GetInstance)(void);
public:

  static GetInstance instance;

};
</code>```

Results:

```<code>$ clang++  foo.cc
foo.cc:3:56: error: explicit specialization of 'instance' after instantiation
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
                                                       ^
./foo.hh:10:32: note: implicit instantiation first required here
        return singleton<Foo>::instance();
                               ^
1 error generated.

$ g++  foo.cc <- No Errors
</code>```

答:
Neither compiler is technically wrong. The code is invalid, but C++ implementations are not required to give a diagnostic message about this type of error.

Standard [temp.expl.spec]/6 says (emphasis mine):

If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.

You can fix this by declaring the explicit specialization immediately after the definition of singleton in sing.hh:

```<code>struct Foo;
template<> singleton<Foo>::GetInstance singleton<Foo>::instance;
</code>```

Or, if you want all specializations to initialize as null pointers, you can just define the member of the general class template, again probably in sing.hh.  Then there's no need for explicit specializations, unless you want a different initializer for some certain type(s).

```<code>template<typename T>
typename singleton<T>::GetInstance singleton<T>::instance = nullptr;
</code>```

Body:
In some code I am reviewing I ran into a case where Clang and Gcc disagree. After looking around awhile I cant seem to figure out who is right.

Disclaimer:  I know there is a better Singleton pattern, but this is the one used in the code.

Notes:

gcc 7.4.0 on Ubuntu (No error)

clang 6.0.0 on Ubuntu (Throws error)

Difference appears to exist for all post C++11 ISO versions, but I did not try earlier.

foo.hh

#include "sing.hh"

class Foo {
    public:
    Foo();
    ~Foo();
    static Foo *getSingleton(){
        return singleton<Foo>::instance();
    }
};

foo.cc

include "foo.hh"
//removing this line results in the error for clang disappearing
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
int main(){};

sing.hh

template<typename T>
class singleton{
    typedef T *(*GetInstance)(void);
public:

  static GetInstance instance;

};

Results:

$ clang++  foo.cc
foo.cc:3:56: error: explicit specialization of 'instance' after instantiation
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
                                                       ^
./foo.hh:10:32: note: implicit instantiation first required here
        return singleton<Foo>::instance();
                               ^
1 error generated.

$ g++  foo.cc <- No Errors

Body:
Neither compiler is technically wrong. The code is invalid, but C++ implementations are not required to give a diagnostic message about this type of error.

Standard [temp.expl.spec]/6 says (emphasis mine):

If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.

You can fix this by declaring the explicit specialization immediately after the definition of singleton in sing.hh:

struct Foo;
template<> singleton<Foo>::GetInstance singleton<Foo>::instance;

Or, if you want all specializations to initialize as null pointers, you can just define the member of the general class template, again probably in sing.hh.  Then there's no need for explicit specializations, unless you want a different initializer for some certain type(s).

template<typename T>
typename singleton<T>::GetInstance singleton<T>::instance = nullptr;


问:
react-bootstrap how to collapse menu when item is selected
How do you make the menu collapse after item is selected?

I dont know how to make it work on fiddle, but this is what I would do?
https://jsfiddle.net/vjeux/kb3gN/

```<code>import React from 'react';
import {Navbar, Nav, NavItem, NavDropdown, DropdownButton, MenuItem, CollapsibleNav} from 'react-bootstrap';

export default class App extends React.Component {

    constructor(props) {
      super(props);
      this.onSelect = this.onSelect.bind(this);
      this.toggleNav = this.toggleNav.bind(this);
      // this.state = {navExpanded: false};
    }

    onSelect(e){
        console.log('OnSelect')
        // console.log(this.state.navExpanded);
        // this.setState({navExpanded: false});
    }

    toggleNav(){console.log('toggle...')};

    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} onToggle={() => this.toggleNav()}>
    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} >

    render() {
        return (

          <Navbar inverse fixedTop toggleNavKey={0} >
            <Nav right eventKey={0} onSelect={this.onSelect} > {/* This is the eventKey referenced */}
              <NavItem eventKey={1} href="#">Link</NavItem>
              <NavItem eventKey={2} href="#">Link</NavItem>
            </Nav>
          </Navbar>

      )

    }

    componentDidMount() {

    }
}

React.render(<App />, document.getElementById('example'));
</code>```

答: <Navbar collapseOnSelect ... > should do the job, but it works unstable :(

Body:
How do you make the menu collapse after item is selected?

I dont know how to make it work on fiddle, but this is what I would do?
https://jsfiddle.net/vjeux/kb3gN/

import React from 'react';
import {Navbar, Nav, NavItem, NavDropdown, DropdownButton, MenuItem, CollapsibleNav} from 'react-bootstrap';

export default class App extends React.Component {

    constructor(props) {
      super(props);
      this.onSelect = this.onSelect.bind(this);
      this.toggleNav = this.toggleNav.bind(this);
      // this.state = {navExpanded: false};
    }

    onSelect(e){
        console.log('OnSelect')
        // console.log(this.state.navExpanded);
        // this.setState({navExpanded: false});
    }

    toggleNav(){console.log('toggle...')};

    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} onToggle={() => this.toggleNav()}>
    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} >

    render() {
        return (

          <Navbar inverse fixedTop toggleNavKey={0} >
             {/* This is the eventKey referenced */}
              <NavItem eventKey={1} href="#">Link</NavItem>
              <NavItem eventKey={2} href="#">Link</NavItem>

          </Navbar>

      )

    }

    componentDidMount() {

    }
}

React.render(<App />, document.getElementById('example'));


问:
npm ERR! No git binary found in $PATH
I can't seem to get zenbot to install I am new to node.js, so please be kind. I am getting all kinds of error I do have git installed. I followed the install instructions and I really don't know where to start. I am a Java and C programming trying to cut my teeth on something new and learn through the bumps and bruises.

```<code>C:\zenbot>npm install
npm ERR! code ENOGIT
npm ERR! No git binary found in $PATH
npm ERR!
npm ERR! Failed using git.
npm ERR! Please check if you have git installed and in your PATH.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\\AppData\Roaming\npm-cache\_logs\2017-12-25T08_17_27_513Z-debug.log

----- Log file--
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\nodejs\\node.exe',
1 verbose cli   'C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install' ]
2 info using npm@5.5.1
3 info using node@v8.9.3
4 verbose npm-session 5167d752483581f2
5 silly install runPreinstallTopLevelLifecycles
6 silly preinstall zenbot4@4.0.5
7 info lifecycle zenbot4@4.0.5~preinstall: zenbot4@4.0.5
8 silly install loadCurrentTree
9 silly install readLocalPackageData
10 silly install loadIdealTree
11 silly install cloneCurrentTreeToIdealTree
12 silly install loadShrinkwrap
13 silly fetchPackageMetaData error for forex.analytics@github:mkmarek/forex.analytics#7bc278987700d4204e959af17de61495941d1a14 No git binary found in $PATH
14 verbose stack Error: No git binary found in $PATH
14 verbose stack     at checkGit (C:\nodejs\node_modules\npm\node_modules\pacote\lib\util\git.js:199:17)
14 verbose stack     at spawnGit (C:\nodejs\node_modules\npm\node_modules\pacote\lib\util\git.js:178:10)
14 verbose stack     at pinflight (C:\nodejs\node_modules\npm\node_modules\pacote\lib\util\git.js:110:12)
14 verbose stack     at C:\nodejs\node_modules\npm\node_modules\promise-inflight\inflight.js:29:24
14 verbose stack     at Promise._execute (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\debuggability.js:300:9)
14 verbose stack     at Promise._resolveFromExecutor (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:483:18)
14 verbose stack     at new Promise (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:79:10)
14 verbose stack     at _inflight (C:\nodejs\node_modules\npm\node_modules\promise-inflight\inflight.js:28:25)
14 verbose stack     at C:\nodejs\node_modules\npm\node_modules\promise-inflight\inflight.js:22:14
14 verbose stack     at tryCatcher (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
14 verbose stack     at Promise._settlePromiseFromHandler (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
14 verbose stack     at Promise._settlePromise (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
14 verbose stack     at Promise._settlePromiseCtx (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:606:10)
14 verbose stack     at Async._drainQueue (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:138:12)
14 verbose stack     at Async._drainQueues (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
14 verbose stack     at Immediate.Async.drainQueues (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
15 verbose cwd C:\zenbot
16 verbose Windows_NT 10.0.15063
17 verbose argv "C:\\nodejs\\node.exe" "C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
18 verbose node v8.9.3
19 verbose npm  v5.5.1
20 error code ENOGIT
21 error No git binary found in $PATH
22 error Failed using git.
22 error Please check if you have git installed and in your PATH.
23 verbose exit [ 1, true ]
</code>```

```<code>C:\WINDOWS\system32>git -v Unknown option: -v usage: git [--version] [--help] [-C <path>] [-c name=value] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p | --paginate | --no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] <command> [<args>] –
</code>```

答:
Looks like it's missing from the alpine image.
npm install is kinda fundamental to node and git is required to install certain dependencies.

Including

```<code>RUN apk update && apk upgrade && \
    apk add --no-cache git
</code>```

in the dockerfile will fix it.

Title: npm ERR! No git binary found in $PATH

Body:
I can't seem to get zenbot to install I am new to node.js, so please be kind. I am getting all kinds of error I do have git installed. I followed the install instructions and I really don't know where to start. I am a Java and C programming trying to cut my teeth on something new and learn through the bumps and bruises.

C:\zenbot>npm install
npm ERR! code ENOGIT
npm ERR! No git binary found in $PATH
npm ERR!
npm ERR! Failed using git.
npm ERR! Please check if you have git installed and in your PATH.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\\AppData\Roaming\npm-cache\_logs\2017-12-25T08_17_27_513Z-debug.log

----- Log file--
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\nodejs\\node.exe',
1 verbose cli   'C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install' ]
2 info using npm@5.5.1
3 info using node@v8.9.3
4 verbose npm-session 5167d752483581f2
5 silly install runPreinstallTopLevelLifecycles
6 silly preinstall zenbot4@4.0.5
7 info lifecycle zenbot4@4.0.5~preinstall: zenbot4@4.0.5
8 silly install loadCurrentTree
9 silly install readLocalPackageData
10 silly install loadIdealTree
11 silly install cloneCurrentTreeToIdealTree
12 silly install loadShrinkwrap
13 silly fetchPackageMetaData error for forex.analytics@github:mkmarek/forex.analytics#7bc278987700d4204e959af17de61495941d1a14 No git binary found in $PATH
14 verbose stack Error: No git binary found in $PATH
14 verbose stack     at checkGit (C:\nodejs\node_modules\npm\node_modules\pacote\lib\util\git.js:199:17)
14 verbose stack     at spawnGit (C:\nodejs\node_modules\npm\node_modules\pacote\lib\util\git.js:178:10)
14 verbose stack     at pinflight (C:\nodejs\node_modules\npm\node_modules\pacote\lib\util\git.js:110:12)
14 verbose stack     at C:\nodejs\node_modules\npm\node_modules\promise-inflight\inflight.js:29:24
14 verbose stack     at Promise._execute (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\debuggability.js:300:9)
14 verbose stack     at Promise._resolveFromExecutor (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:483:18)
14 verbose stack     at new Promise (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:79:10)
14 verbose stack     at _inflight (C:\nodejs\node_modules\npm\node_modules\promise-inflight\inflight.js:28:25)
14 verbose stack     at C:\nodejs\node_modules\npm\node_modules\promise-inflight\inflight.js:22:14
14 verbose stack     at tryCatcher (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
14 verbose stack     at Promise._settlePromiseFromHandler (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
14 verbose stack     at Promise._settlePromise (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
14 verbose stack     at Promise._settlePromiseCtx (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:606:10)
14 verbose stack     at Async._drainQueue (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:138:12)
14 verbose stack     at Async._drainQueues (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
14 verbose stack     at Immediate.Async.drainQueues (C:\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
15 verbose cwd C:\zenbot
16 verbose Windows_NT 10.0.15063
17 verbose argv "C:\\nodejs\\node.exe" "C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
18 verbose node v8.9.3
19 verbose npm  v5.5.1
20 error code ENOGIT
21 error No git binary found in $PATH
22 error Failed using git.
22 error Please check if you have git installed and in your PATH.
23 verbose exit [ 1, true ]

C:\WINDOWS\system32>git -v Unknown option: -v usage: git [--version] [--help] [-C <path>] [-c name=value] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p | --paginate | --no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] <command> [<args>] –

Body:
Looks like it's missing from the alpine image.
npm install is kinda fundamental to node and git is required to install certain dependencies.

Including

RUN apk update && apk upgrade && \
    apk add --no-cache git

in the dockerfile will fix it.


问:
Using R, if values in either variable A or B are 'NA', to then use values in variables C and D instead?
I am trying to calculate the mean of two variables and outputting it as a new variable. For example:

```<code>data$Average <- (data$Visit1 + data$Visit2) / 2
</code>```

However, there are NA values for both 'Visit 1' and 'Visit 2' variables across the dataset.

How can I write some code such that I am able to identify if NA values exist in either Visit 1 or 2, then I would use the corresponding row's values but for 'Visit 3' and 'Visit 4' instead, to calculate the average? And if 'Visit 3' and 'Visit 4' values were NA, to use 'Visit 5' and 'Visit 6' instead?

Basically, the priority is to use Visits 1 and 2 data, but if those do not exist (NA), to use   Visits 3 and 4, and finally, last priority being Visits 5 and 6.

Many thanks!

答:
You can use coalesce() from dplyr. coalesce() will use the first non-missing value at each position. I think this has better readability than ifelse() or case_when().

```<code>data %>%
  mutate(
    Average = coalesce(
      as.numeric((data$Visit1 + data$Visit2) / 2),
      as.numeric((data$Visit3 + data$Visit4) / 2),
      as.numeric((data$Visit5 + data$Visit6) / 2)
    )
  )
</code>```

Body:
I am trying to calculate the mean of two variables and outputting it as a new variable. For example:

data$Average <- (data$Visit1 + data$Visit2) / 2

However, there are NA values for both 'Visit 1' and 'Visit 2' variables across the dataset.

How can I write some code such that I am able to identify if NA values exist in either Visit 1 or 2, then I would use the corresponding row's values but for 'Visit 3' and 'Visit 4' instead, to calculate the average? And if 'Visit 3' and 'Visit 4' values were NA, to use 'Visit 5' and 'Visit 6' instead?

Basically, the priority is to use Visits 1 and 2 data, but if those do not exist (NA), to use   Visits 3 and 4, and finally, last priority being Visits 5 and 6.

Many thanks!

Body:
You can use coalesce() from dplyr. coalesce() will use the first non-missing value at each position. I think this has better readability than ifelse() or case_when().

data %>%
  mutate(
    Average = coalesce(
      as.numeric((data$Visit1 + data$Visit2) / 2),
      as.numeric((data$Visit3 + data$Visit4) / 2),
      as.numeric((data$Visit5 + data$Visit6) / 2)
    )
  )


问:
return insert id on none laravel db set up
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.

This is the insert I am using.

```<code>$results = DB::insert("
            SELECT * FROM insrdata.add_user(
                :assocID,
                :accountID,
                :firstName,
                :middleName,
                :lastName,
                :address1,
                :address2,
                :city,
                :state,
                :zipCode,
                :phone,
                :email,
                :birthDateMMDDYYYY,
                :gradeLevelID,
                :commentText
            )
        ",
        [
            'assocID' => $request->input('assocID'),
            'accountID' => $request->input('accountID'),
            'firstName' => $request->input('firstName'),
            'middleName' => $request->input('middleName'),
            'lastName' => $request->input('lastName'),
            'address1' => $request->input('address1'),
            'address2' => $request->input('address2'),
            'city' => $request->input('city'),
            'state' => $request->input('state'),
            'zipCode' => $request->input(''),
            'phone' => $request->input(''),
            'email' => $request->input('email'),
            'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
            'gradeLevelID' => $request->input('gradeLevelID'),
            'commentText' => $request->input('commentText')
        ]
    );

if($results) {
    $return_array = array(
        'p_contact_id' => "",
        'p_result' => "O.K."
    );
}
</code>```

I need to get the id of the insert.

答: I think if the insert is successful, you can query for it by accountID (which i suppose unique for each inssured person) and get its id.

Body:
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.

This is the insert I am using.

$results = DB::insert("
            SELECT * FROM insrdata.add_user(
                :assocID,
                :accountID,
                :firstName,
                :middleName,
                :lastName,
                :address1,
                :address2,
                :city,
                :state,
                :zipCode,
                :phone,
                :email,
                :birthDateMMDDYYYY,
                :gradeLevelID,
                :commentText
            )
        ",
        [
            'assocID' => $request->input('assocID'),
            'accountID' => $request->input('accountID'),
            'firstName' => $request->input('firstName'),
            'middleName' => $request->input('middleName'),
            'lastName' => $request->input('lastName'),
            'address1' => $request->input('address1'),
            'address2' => $request->input('address2'),
            'city' => $request->input('city'),
            'state' => $request->input('state'),
            'zipCode' => $request->input(''),
            'phone' => $request->input(''),
            'email' => $request->input('email'),
            'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
            'gradeLevelID' => $request->input('gradeLevelID'),
            'commentText' => $request->input('commentText')
        ]
    );

if($results) {
    $return_array = array(
        'p_contact_id' => "",
        'p_result' => "O.K."
    );
}

I need to get the id of the insert.


问:
How to extract part of a string with slash constraints?
Hello I have some strings named like this:

BURGERDAY / PPA / This is a burger fest

I've tried using regex to get it but I can't seem to get it right.

The output should just get the final string of This is a burger fest (without the first whitespace)

答:
Here, we can capture our desired output after we reach to the last slash followed by any number of spaces:

```<code>.+\/\s+(.+)
</code>```

where (.+) collects what we wish to return.

const regex = /.+\/\s+(.+)/gm;
const str = `BURGERDAY / PPA / This is a burger fest`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```
</div>
</div>
</p>
<h3>DEMO</h3>
<h3>Advices</h3>
<p>Based on revo's advice, we can also use this expression, which is much better:</p>
```\/ +([^\/]*)$
```
<hr />
<p>According to Bohemian's advice, it may not be required to escape the forward slash, based on the language we wish to use and this would work for JavaScript:</p>
```.+/\s+(.+)
```

Also, we assume in target content, we would not have forward slash, otherwise we can change our constraints based on other possible inputs/scenarios.

Body:
Here, we can capture our desired output after we reach to the last slash followed by any number of spaces:

.+\/\s+(.+)

where (.+) collects what we wish to return.

const regex = /.+\/\s+(.+)/gm;
const str = `BURGERDAY / PPA / This is a burger fest`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

DEMO

Advices

Based on revo's advice, we can also use this expression, which is much better:

\/ +([^\/]*)$

According to Bohemian's advice, it may not be required to escape the forward slash, based on the language we wish to use and this would work for JavaScript:

.+/\s+(.+)

Also, we assume in target content, we would not have forward slash, otherwise we can change our constraints based on other possible inputs/scenarios.


问:
Using template for array constructor as a function return type
I'm a little new to the template function in c++ and encounter a problem that I cannot find any result by googling.

Trying to use a template here for generating different dimensions of arrays. The code is shown below:

```<code> template <size_t T>
 vector<array<float, T>> poissonSample(size_t T, float r) {
    array<float, T> x_min, x_max;

    return samples;
  }
</code>```

The definition of the function seems fine, however, when I try to call the function with something like:

```<code>poissonSample(4, 0.3f);
</code>```

The compiler will report "no instance of function template matches the argument list.

What is the problem here?

答:
Here is the code I compiled at onlinegdb.com

```<code>#include <vector>
#include <array>

using namespace std;

template <size_t T>
vector<array<float, T>> poissonSample(size_t T, float r);

int main()
{
    auto res = poissonSample(4, 1.0f)
    return 0;
}
</code>```

Here is the full text of the error messages:

```<code>main.cpp:17:46: error: declaration of ‘size_t T’ shadows template parameter
 vector<array<float, T>> poissonSample(size_t T, float r);
                                              ^
main.cpp:16:11: note: template parameter ‘T’ declared here
 template <size_t T>
           ^~~~~~
main.cpp: In function ‘int main()’:
main.cpp:21:37: error: no matching function for call to ‘poissonSample(int, float)’
     auto res = poissonSample(4, 1.0f)
                                     ^
main.cpp:17:25: note: candidate: template std::vector > poissonSample(size_t, float)
 vector<array<float, T>> poissonSample(size_t T, float r);
                         ^~~~~~~~~~~~~
main.cpp:17:25: note:   template argument deduction/substitution failed:
main.cpp:21:37: note:   couldn't deduce template parameter ‘T’
     auto res = poissonSample(4, 1.0f)
</code>```

As you can see, the root problem is that the size_t T in the function parameters and size_t T in template parameters are unrelated. One is a compile-time construct, the other is a run-time construct.

The secondary problem is

```<code>main.cpp:17:25: note:   template argument deduction/substitution failed:
</code>```

The compiler cannot figure out your T.

The correct usage would be:

```<code>template <size_t T>
vector<array<float, T>> poissonSample(float r);

int main()
{
    auto res = poissonSample<4>(1.0f);
    return 0;
}
</code>```

(this gives only a linker error, provide your own implementation)

Body:
I'm a little new to the template function in c++ and encounter a problem that I cannot find any result by googling.

Trying to use a template here for generating different dimensions of arrays. The code is shown below:

 template <size_t T>
 vector<array<float, T>> poissonSample(size_t T, float r) {
    array<float, T> x_min, x_max;

    return samples;
  }

The definition of the function seems fine, however, when I try to call the function with something like:

poissonSample(4, 0.3f);

The compiler will report "no instance of function template matches the argument list.

What is the problem here?

Body:
Here is the code I compiled at onlinegdb.com

#include <vector>
#include <array>

using namespace std;

template <size_t T>
vector<array<float, T>> poissonSample(size_t T, float r);

int main()
{
    auto res = poissonSample(4, 1.0f)
    return 0;
}

Here is the full text of the error messages:

main.cpp:17:46: error: declaration of ‘size_t T’ shadows template parameter
 vector<array<float, T>> poissonSample(size_t T, float r);
                                              ^
main.cpp:16:11: note: template parameter ‘T’ declared here
 template <size_t T>
           ^~~~~~
main.cpp: In function ‘int main()’:
main.cpp:21:37: error: no matching function for call to ‘poissonSample(int, float)’
     auto res = poissonSample(4, 1.0f)
                                     ^
main.cpp:17:25: note: candidate: template std::vector > poissonSample(size_t, float)
 vector<array<float, T>> poissonSample(size_t T, float r);
                         ^~~~~~~~~~~~~
main.cpp:17:25: note:   template argument deduction/substitution failed:
main.cpp:21:37: note:   couldn't deduce template parameter ‘T’
     auto res = poissonSample(4, 1.0f)

As you can see, the root problem is that the size_t T in the function parameters and size_t T in template parameters are unrelated. One is a compile-time construct, the other is a run-time construct.

The secondary problem is

main.cpp:17:25: note:   template argument deduction/substitution failed:

The compiler cannot figure out your T.

The correct usage would be:

template <size_t T>
vector<array<float, T>> poissonSample(float r);

int main()
{
    auto res = poissonSample<4>(1.0f);
    return 0;
}

(this gives only a linker error, provide your own implementation)