问:
this.setState is not actually setting my state at all?
I am currently creating a small React app for a shopping list. I am attempting to hold the list items as state. Once the input is submitted, for adding a new item, a function is called, which sends the new list to the App and also attempts to reset the state to ''. For some reason this is not working. I checked through logging and also I can tell by the fact that my input does not reset.

Here is the code:

```<code>class List extends React.Component {
  state = {newItem: ''};

  addItem = event => {
    event.preventDefault();

    this.props.onSubmit(this.state.newItem);
    this.setState({newItem: ''});
  }

  render() {
      return (
        <div>
          {this.props.currentUser.shoppingList.map(item =>
            <ListItem
              {...item}
              updatedList={this.props.updatedList}
            />)}
            <form onSubmit={this.addItem}>
              <input type="text" placeholder="Add new item!"
                value={this.state.newItem}
                onChange={event => this.setState({newItem: event.target.value})}
              />
              <button>Save</button>
            </form>
        </div>
      );
    }
}
</code>```

答:
The problem is that you're not binding this to the addItem function.

Try changing <form onSubmit={this.addItem}>

To <form onSubmit={this.addItem.bind(this)}>

Body:
I am currently creating a small React app for a shopping list. I am attempting to hold the list items as state. Once the input is submitted, for adding a new item, a function is called, which sends the new list to the App and also attempts to reset the state to ''. For some reason this is not working. I checked through logging and also I can tell by the fact that my input does not reset.

Here is the code:

class List extends React.Component {
  state = {newItem: ''};

  addItem = event => {
    event.preventDefault();

    this.props.onSubmit(this.state.newItem);
    this.setState({newItem: ''});
  }

  render() {
      return (

          {this.props.currentUser.shoppingList.map(item =>
            <ListItem
              {...item}
              updatedList={this.props.updatedList}
            />)}
            <form onSubmit={this.addItem}>
              <input type="text" placeholder="Add new item!"
                value={this.state.newItem}
                onChange={event => this.setState({newItem: event.target.value})}
              />
              <button>Save</button>
            </form>

      );
    }
}


来源: stackexchange

问:
How do I identify a string using a wildcard using R?
I'd like to count the duration of some words containing the number "0" after a string, as shown in the picture (I inserted a red dot under the words with the character I'd like to work with).
Is there anything like a wildcard so that I can work only with the words containing this string?

[Picture]

答:
You should read the help returned by ?regex.  It will give you a summary of using regular expressions in R.  It will also refer you to a variety of functions that you can use the regex with.

For example, if your data above was in a dataframe, df:

```<code>grep(x=df$TextGridLabel, pattern="^.*0.+$")
</code>```

would return an index of all the values starting with anything, containing a 0 and having at least one character after the 0.

Cheers!

ContentLicense: CC BY-SA 4.0

Body:
You should read the help returned by ?regex.  It will give you a summary of using regular expressions in R.  It will also refer you to a variety of functions that you can use the regex with.

For example, if your data above was in a dataframe, df:

grep(x=df$TextGridLabel, pattern="^.*0.+$")

would return an index of all the values starting with anything, containing a 0 and having at least one character after the 0.

Cheers!

ContentLicense: CC BY-SA 3.0


问:
sns.distplot is plotting negative values for a only positive variable

Hello, I'm trying to plot the distribution of a variable in Python using the sns.distplot function.

For example, I create variable x as a random variable, with only positive values.

```<code>import pandas as pd
x = np.random.random(100)
</code>```

I then use the sns.distplot function and I get the following graph:

As you'll be able to see, it looks like there are negative values (-0.25). I check if there are negative values by doing the following:

```<code>x < 0
>>> array([False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False, False],       dtype=bool)
</code>```

I don't understand why x seems to have negative values in the plot. Does anyone knows why this is happening? I tried to look if I found more specifications about the sns.ditplot function, but I couldn't find anything that enlightened me.

Thank you!

答:
As you can see the plot only has values from zero. If you do not want to see the negative value in the plot you can set the xlim parameter.

```<code>import seaborn as sns
import numpy as np

x = np.random.random(100)
%matplotlib inline
sns.distplot(x).set(xlim=(0))
</code>```

which gives

Body:
Hello, I'm trying to plot the distribution of a variable in Python using the sns.distplot function.

For example, I create variable x as a random variable, with only positive values.

import pandas as pd
x = np.random.random(100)

I then use the sns.distplot function and I get the following graph:

As you'll be able to see, it looks like there are negative values (-0.25). I check if there are negative values by doing the following:

x < 0
>>> array([False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False,
   False, False, False, False, False, False, False, False, False, False],       dtype=bool)

I don't understand why x seems to have negative values in the plot. Does anyone knows why this is happening? I tried to look if I found more specifications about the sns.ditplot function, but I couldn't find anything that enlightened me.

Thank you!

Body:
As you can see the plot only has values from zero. If you do not want to see the negative value in the plot you can set the xlim parameter.

import seaborn as sns
import numpy as np

x = np.random.random(100)
%matplotlib inline
sns.distplot(x).set(xlim=(0))

which gives


问:
Sum every odd row in a single Column VBA
I have a code that searches an excel fill for the word distance, takes the value of the cell next to it, paste it into a new cell, then sums all the cells up. Which works great, but  i now need to find a way to only sum ever even row number. Does that make sense?

```<code>Sub Distance_Check()

Dim DistanceCheck As String

Dim DistanceNumber As String

Dim DistanceSum As String

Dim DistanceTotal As String

DistanceCheck = MsgBox("Would you like to check the distance?", vbYesNo)

If DistanceCheck = vbYes Then
If IsArray(fname) Then Workbooks.OpenText fname(1)

                        i = 1
                        findStr = "Distance"
                        Set foundCel = Range("A:A").Find(what:=findStr)
                        If Not foundCel Is Nothing Then
                            firstAddress = foundCel.Address
                            Do
                                Range("J" & i).Value = foundCel.Offset(0, 1).Value
                                Set foundCel = Range("A:A").FindNext(foundCel)
                                i = i + 1
                            Loop While Not foundCel Is Nothing And foundCel.Address <> firstAddress
                        End If
                        Set wkbSourceBook = ActiveWorkbook

            DistanceNumber = i - 2

            DistanceSum = WorksheetFunction.Sum(Range(Cells(2, 15), (Cells(DistanceNumber + 1, 15))))
            DistanceTotal = DistanceSum / DistanceNumber

            If DistanceNumber = Cells(2, 12) Then
            MsgBox ("No error found wihin distance")
            Else
            MsgBox ("Error found with distance")
            End If
Else
End If
Call Save_Data
End Sub
</code>```

Would the way youd go about this be using a for loop on the

```<code>cells(DistanceNumber(j,+1)
</code>```

Where j = 0,
      j = j +2 ,
Until j > DistanceNumber,

Would that work? If so how would you go about it?

Thanks

答:
A quick way to step through a loop in the desired increments is to use the Mod operator which divides two numbers and returns any remainder (e.g. 7 mod 2 = 1, as two sixes fit into seven, leaving one).

You can use the row property of the range you identify with the Find method, and since you want to jump by two the modulo should be zero:

```<code>If foundcel.Row Mod 2 = 0 Then Range("J" & i).value = foundcel.Offset(0, 1).Value
</code>```

That said, there is a 'built in' way to step through a loop if using a For loop like this

```<code>For x = 2 to 10 Step 2
     ' Do stuff
Next x
</code>```

You can also use this method to step backwards, e.g.

```<code>For x = 100 to 0 Step -10
     ' Do stuff backwards!
Next x
</code>```

Body:
I have a code that searches an excel fill for the word distance, takes the value of the cell next to it, paste it into a new cell, then sums all the cells up. Which works great, but  i now need to find a way to only sum ever even row number. Does that make sense?

Sub Distance_Check()

Dim DistanceCheck As String

Dim DistanceNumber As String

Dim DistanceSum As String

Dim DistanceTotal As String

DistanceCheck = MsgBox("Would you like to check the distance?", vbYesNo)

If DistanceCheck = vbYes Then
If IsArray(fname) Then Workbooks.OpenText fname(1)

                        i = 1
                        findStr = "Distance"
                        Set foundCel = Range("A:A").Find(what:=findStr)
                        If Not foundCel Is Nothing Then
                            firstAddress = foundCel.Address
                            Do
                                Range("J" & i).Value = foundCel.Offset(0, 1).Value
                                Set foundCel = Range("A:A").FindNext(foundCel)
                                i = i + 1
                            Loop While Not foundCel Is Nothing And foundCel.Address <> firstAddress
                        End If
                        Set wkbSourceBook = ActiveWorkbook

            DistanceNumber = i - 2

            DistanceSum = WorksheetFunction.Sum(Range(Cells(2, 15), (Cells(DistanceNumber + 1, 15))))
            DistanceTotal = DistanceSum / DistanceNumber

            If DistanceNumber = Cells(2, 12) Then
            MsgBox ("No error found wihin distance")
            Else
            MsgBox ("Error found with distance")
            End If
Else
End If
Call Save_Data
End Sub

Would the way youd go about this be using a for loop on the

cells(DistanceNumber(j,+1)

Where j = 0,
      j = j +2 ,
Until j > DistanceNumber,

Would that work? If so how would you go about it?

Thanks

Body:
A quick way to step through a loop in the desired increments is to use the Mod operator which divides two numbers and returns any remainder (e.g. 7 mod 2 = 1, as two sixes fit into seven, leaving one).

You can use the row property of the range you identify with the Find method, and since you want to jump by two the modulo should be zero:

If foundcel.Row Mod 2 = 0 Then Range("J" & i).value = foundcel.Offset(0, 1).Value

That said, there is a 'built in' way to step through a loop if using a For loop like this

For x = 2 to 10 Step 2
     ' Do stuff
Next x

You can also use this method to step backwards, e.g.

For x = 100 to 0 Step -10
     ' Do stuff backwards!
Next x


问:
AS3 MVC game: Should I separate the data and the game rules in a model?
I feel like MVC misses a letter to describe the situation in a game. The model to me seems to consist of two distinct parts:

A group of vars that describe the current game state (these will have setters that send out events on change, and getters so that the view can access what changed)

The rules of the game that determine what happens once a certain input (i.e. shoot();) has been received by the controller (these will update the group of vars as deemed appropriate)

The view will exclusively be reading from 1 while the controller will be exclusively communicating with 2. This is why I make the distinction and want to divide them up into class1 and class2.

My questions:

I am unsure if I should be making this distinction, since I haven't seen it anywhere.

If I should; should I make two separate classes, or should I extend class1 with class2?

Finally, I am having trouble making sure that only class2 (and not the view) can change the variables in class1 (while still being able to send out an event when a value changes). Any suggestions?

答:
PureMVC has a StateMachine Utility. This is what you need to handle game state. Basically you define a Finite State Machine that describes all the states your game can be in, the valid transitions between them, and the actions that trigger those transitions.

Actions are sent to the state machine as notifications, and if the action is valid for the current state it will first send out a notification (if defined) for an exiting guard announcement (a notification you define). This gives any interested actor the chance to cancel the transition (i.e. you can't leave the room because you're chained to the floor). Then it sends an entering guard announcement (another optional notification you define). This is another chance for an interested actor to cancel the transition (i.e. you can't enter the room because you don't have the key). If not canceled, then it sends out a state-specific changed announcement, so that interested actors can perform activities specific to having entered this new state.

I haven't coded game logic since the early eighties (in 6502 assembly), so I decided it was time to have fun again. I just finished a touch-focused strategy game using PureMVC and the StateMachine utility, and I must say it was fun to use the tools I use daily on enterprise apps to do a game. Not too heavy, MVC does apply, and the StateMachine made it so crystal clear what was happening and when. It was built for the BB PlayBook, but thanks to AIR, you can check it out and install it on your desktop and try it.

Dungeon Joe: A Touch-focused strategy game.
http://dungeonjoe.com

-=Cliff>

ContentLicense: CC BY-SA 2.5


问:
math game difficulty setting

I'm trying to make simple math game that has adding right now, I want to add difficulties that so i can choose if i want numbers from 1-10 or 10-20, im using random for it. everything is console sided and i can write numbers for difficulties.

```<code>    Random numberGenerator = new Random();
    Console.WriteLine("what what difficulty you want?");
    Console.WriteLine("1 for 1-10\n2 for 10-20\n3 for 15-40");
    Console.Write("i want:");
    int hardness = Convert.ToInt32(Console.ReadLine());
    if (hardness == 1)
    {
        goto hardness1;
    }

hardness1:
    int num01 = numberGenerator.Next(1, 11);
    int num02 = numberGenerator.Next(1, 11);
    int num03 = numberGenerator.Next(1, 11);
    int num04 = numberGenerator.Next(1, 11);
    if (answer == 1) {
        goto startofadding;
    }

hardness2:
    int num01 = numberGenerator.Next(10, 21)
    int num02 = numberGenerator.Next(10, 21)
    int num03 = numberGenerator.Next(10, 21)
    int num04 = numberGenerator.Next(10, 21)
    if (answer == 1)
    {
        goto startofadding;
    }

startofadding:
    Console.WriteLine("num01 = " + num01 + " and num02 = " + num02 + " this is " + i + " loop ");
    Console.WriteLine("answer is " + (num01 + num02));

    Console.WriteLine("what is " + num01 + " + " + num02 + " ?");
    Console.Write("Answer is: ");
    int answer1 = Convert.ToInt32(Console.ReadLine());
    if (answer1 == num01 + num02)
    {
        Console.WriteLine("correct answer");
        Console.WriteLine("\n");
</code>```

I'm trying to use gotos so if the difficulty is chosen it can take numbers that it needs but it gives me:

A local variable or function named 'num01' is already defined in scope

error, I get what it is, but I don't know how to fix it. Am I doing something wrong or is there a better way to make it? ask for more details and more code if something is unclear, tried to explain it as good as i can

答:
A local variable or function named 'num01' is already defined in scope

You've already defined num01 it under the hardness1 label.

You can fix it by declaring the variable just once. Don't re-declare the same variables under the next label since it's in the same block scope.

Once you get it working, get rid of goto. A switch statement is probably the easiest way in this case.

You can replace the if conditions and the hardness0x blocks with:

```<code>switch(hardness)
{
    case 1:
    // code for hardness 1
    break;
    case 2:
    // code for hardness 2... etc.
    break;
}

// Code under startofadding follows. No need for goto or goto-labels
</code>```

You next step would be to try and get rid of the switch statement altogether, which will simplify your code a great deal.

Title: math game difficulty setting

Body:
I'm trying to make simple math game that has adding right now, I want to add difficulties that so i can choose if i want numbers from 1-10 or 10-20, im using random for it. everything is console sided and i can write numbers for difficulties.

    Random numberGenerator = new Random();
    Console.WriteLine("what what difficulty you want?");
    Console.WriteLine("1 for 1-10\n2 for 10-20\n3 for 15-40");
    Console.Write("i want:");
    int hardness = Convert.ToInt32(Console.ReadLine());
    if (hardness == 1)
    {
        goto hardness1;
    }

hardness1:
    int num01 = numberGenerator.Next(1, 11);
    int num02 = numberGenerator.Next(1, 11);
    int num03 = numberGenerator.Next(1, 11);
    int num04 = numberGenerator.Next(1, 11);
    if (answer == 1) {
        goto startofadding;
    }

hardness2:
    int num01 = numberGenerator.Next(10, 21)
    int num02 = numberGenerator.Next(10, 21)
    int num03 = numberGenerator.Next(10, 21)
    int num04 = numberGenerator.Next(10, 21)
    if (answer == 1)
    {
        goto startofadding;
    }

startofadding:
    Console.WriteLine("num01 = " + num01 + " and num02 = " + num02 + " this is " + i + " loop ");
    Console.WriteLine("answer is " + (num01 + num02));

    Console.WriteLine("what is " + num01 + " + " + num02 + " ?");
    Console.Write("Answer is: ");
    int answer1 = Convert.ToInt32(Console.ReadLine());
    if (answer1 == num01 + num02)
    {
        Console.WriteLine("correct answer");
        Console.WriteLine("\n");

I'm trying to use gotos so if the difficulty is chosen it can take numbers that it needs but it gives me:

A local variable or function named 'num01' is already defined in scope

error, I get what it is, but I don't know how to fix it. Am I doing something wrong or is there a better way to make it? ask for more details and more code if something is unclear, tried to explain it as good as i can

Body:
A local variable or function named 'num01' is already defined in scope

You've already defined num01 it under the hardness1 label.

You can fix it by declaring the variable just once. Don't re-declare the same variables under the next label since it's in the same block scope.

Once you get it working, get rid of goto. A switch statement is probably the easiest way in this case.

You can replace the if conditions and the hardness0x blocks with:

switch(hardness)
{
    case 1:
    // code for hardness 1
    break;
    case 2:
    // code for hardness 2... etc.
    break;
}

// Code under startofadding follows. No need for goto or goto-labels

You next step would be to try and get rid of the switch statement altogether, which will simplify your code a great deal.


问:
mean.io stack angular long running operations with http request
I am using the mean stack do develop a web application that performs several operations over several mongo db collections.

The systems overal intention is to perform data sinchronization between several systems. Each system data is stored in a different collections. Needless to say that these collection's documents have properties in common.

At the nodeJS, or the API level, I created get and post requests that will loop over the main collection asynchronouslye and will try to link documents on that collection with documents in other collections. Naturally this process takes for several minutes.

The documents that were possible to link are stored in a different mongodb collection. These will be later processed in another node js API call.

After the API is set I am creating a controller and a service with angular in order to connect to the api and perform the api get and post requests.

When I get to this point in the UI where I click in a button to perform this link operation, the operation starts without blocking the browser but eventually the browser get an ERR_EMPTY_RESPONSE because the operation is still undergoing so I never actually call the response.end().

What I thought could be a possible solution:

reply back as soon as the operation starts: PROBLEM -> I need to make sure this operation finishes in order to make other calls on the resulting collection. So I did this operation to finishs to allow others to be done on the resulting data set.

What can I do in order to avoid the browser to close the connection before the long running operation in the background is completed?

Code:

html-> Button which the user clicks to start linking records:

```<code><div>
    <md-button aria-label="link all records" ng-click="vm.linkRecords()">
        <md-icon class="mdi mdi-plus"></md-icon>Link Records
    </md-button>
</div>
</code>```

controller: the canLink, canGrade are all boolean variables so that When the server is undergoing one operation none of the others can be performed. Once the operation finishes, it returns true and all operations are allowed.

```<code>function linkRecords() {
    $state.go('app.records.link');
}// END linkRecords page

$scope.$on('linkRecords', function(event, batchSize){
    if ( canLink && canGrade) {
        showToast("Started linking records");
        canLink  = 0;
        canGrade = 0;
        recordService.linkRecords(batchSize).then(function(finished){
            canLink     = finished;
            canGrade    = finished;
        });
    }else if ( !canLink ){
        showToast('Cannot link records: - Currently undergoing grading records');
    }else if ( !canGrade ){
        showToast('Cannot link records: - Currently undergoing linking records');
    }
});//END linkingRecords
</code>```

Service

```<code>function linkRecords(batchSize){
    return $http.get(urlRoot+'/link/:'+batchSize);
}//END linkRecords
</code>```

Node js api:

routes.js:

```<code>//link all records
app.post('/link/:batchSize', function(req, res){
    var batchSize = req.params.batchSize;
    functions.linkRecords(batchSize, function(callback){
        res.end(true);
    });
});//END linkRecords
</code>```

functions.js:

```<code>linkRecords : function(batchSize, callback){
    //link all records in all collections a batchsize at a time
    async.parallel([
        function(callback){
            ...open cursor for collection1 and loops over the collections to stitch with other collections.
        },
        function(callback){
            ...open cursor for collection2 and loops over the collections to stitch with other collections.
        }
    ], function done(err, result){
        callback();
    });
}
</code>```

答:
I would piggy back on Mikelax's answer of using a queue system in order to manage. I have been using agenda to handle longer processes in the project I've been working on.

I think it's worth mentioning (possibly the root of your ERR_EMPTY_RESPONSE error) that Express has a default timeout of 2 minutes. So if you have processes that take several minutes, you should modify your timeout on the endpoint to handle the requests.

You can modify the timeout a couple different ways, there are middlewares, such as connect-timeout. You can also set timeouts via your env object or directly in your server.js file.

Body:
I am using the mean stack do develop a web application that performs several operations over several mongo db collections.

The systems overal intention is to perform data sinchronization between several systems. Each system data is stored in a different collections. Needless to say that these collection's documents have properties in common.

At the nodeJS, or the API level, I created get and post requests that will loop over the main collection asynchronouslye and will try to link documents on that collection with documents in other collections. Naturally this process takes for several minutes.

The documents that were possible to link are stored in a different mongodb collection. These will be later processed in another node js API call.

After the API is set I am creating a controller and a service with angular in order to connect to the api and perform the api get and post requests.

When I get to this point in the UI where I click in a button to perform this link operation, the operation starts without blocking the browser but eventually the browser get an ERR_EMPTY_RESPONSE because the operation is still undergoing so I never actually call the response.end().

What I thought could be a possible solution:

reply back as soon as the operation starts: PROBLEM -> I need to make sure this operation finishes in order to make other calls on the resulting collection. So I did this operation to finishs to allow others to be done on the resulting data set.

What can I do in order to avoid the browser to close the connection before the long running operation in the background is completed?

Code:

html-> Button which the user clicks to start linking records:

    <md-button aria-label="link all records" ng-click="vm.linkRecords()">
        <md-icon class="mdi mdi-plus"></md-icon>Link Records
    </md-button>

controller: the canLink, canGrade are all boolean variables so that When the server is undergoing one operation none of the others can be performed. Once the operation finishes, it returns true and all operations are allowed.

function linkRecords() {
    $state.go('app.records.link');
}// END linkRecords page

$scope.$on('linkRecords', function(event, batchSize){
    if ( canLink && canGrade) {
        showToast("Started linking records");
        canLink  = 0;
        canGrade = 0;
        recordService.linkRecords(batchSize).then(function(finished){
            canLink     = finished;
            canGrade    = finished;
        });
    }else if ( !canLink ){
        showToast('Cannot link records: - Currently undergoing grading records');
    }else if ( !canGrade ){
        showToast('Cannot link records: - Currently undergoing linking records');
    }
});//END linkingRecords

Service

function linkRecords(batchSize){
    return $http.get(urlRoot+'/link/:'+batchSize);
}//END linkRecords

Node js api:

routes.js:

//link all records
app.post('/link/:batchSize', function(req, res){
    var batchSize = req.params.batchSize;
    functions.linkRecords(batchSize, function(callback){
        res.end(true);
    });
});//END linkRecords

functions.js:

linkRecords : function(batchSize, callback){
    //link all records in all collections a batchsize at a time
    async.parallel([
        function(callback){
            ...open cursor for collection1 and loops over the collections to stitch with other collections.
        },
        function(callback){
            ...open cursor for collection2 and loops over the collections to stitch with other collections.
        }
    ], function done(err, result){
        callback();
    });
}


问:
emacs map key to command like vim
I set my own map :map <C-j> :tab split<CR>:exec "tjump ".expand("<cword>")<CR> in ~/.vimrc file to make ctrl + j as a shortcut to navigate to the definition, with tjump, if there is multiple match of the fuction that the cursor is on, then vim prompts to choose from all the matches, but when moving to emacs, I don't know how to do this, I google it, but did not get useful suggestions, can some veterens share how to do this?

答:
I'm not familiar with vim, but it sounds like you're asking to bind C-j to a command that will jump to the definition of the function name the cursor is on.

```<code>(global-set-key (kbd "C-j") #'xref-find-definitions)
</code>```

xref-find-definitions is bound to M-. by default.

Personally, I use GNU global, and the gxref package.  gxref just adds another backend to xref, so that it works with global in addition to etags.

Title: emacs map key to command like vim

Body:
I'm not familiar with vim, but it sounds like you're asking to bind C-j to a command that will jump to the definition of the function name the cursor is on.

(global-set-key (kbd "C-j") #'xref-find-definitions)

xref-find-definitions is bound to M-. by default.

Personally, I use GNU global, and the gxref package.  gxref just adds another backend to xref, so that it works with global in addition to etags.


问:
Unable to build Unity Container - Prism
I am trying to use prism in my WPF application. So far i have configured my container and View model locator like this:

```<code>   protected override void ConfigureContainer()
    {

        Container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());
        Container.RegisterType<IUnitOfWork, UnitOfWork>();
        Container.RegisterType<IDbFactory, DbFactory>();
        Container.RegisterType<IUnitOfWork, UnitOfWork>("UnitOfWork", new ContainerControlledLifetimeManager());
        Container.Resolve<IUnitOfWork>("UnitOfWork");
        Container.RegisterType<IDbFactory, DbFactory>("DbFactory", new ContainerControlledLifetimeManager());
        Container.Resolve<IDbFactory>("DbFactory");
        Container.RegisterType<IRegionManager, RegionManager>();
        Container.RegisterInstance<IRegionManager>(new RegionManager(), new ContainerControlledLifetimeManager());

        #region Register Repositories

        Container.RegisterType<IVendorRepository, VendorRepository>();

        Container.RegisterType<IUserRepository, UserRepository>();
        Container.RegisterType<IReceiveablesRepository, ReceiveablesRepository>();
        Container.RegisterType<IProductUnitsRepository, ProductUnitRepository>();
        Container.RegisterType<IPaymentRepository, PaymentRepository>();
        Container.RegisterType<IItemRepository, ItemRepository>();
        Container.RegisterType<IInvoiceMasterRepository, InvoiceMasterRepository>();
        Container.RegisterType<IInvoiceDetailRepository, InvoiceDetailRepository>();
        Container.RegisterType<IExpenseTypeRepository, ExpenseTypeRepository>();
        Container.RegisterType<IExpenseRepository, ExpenseRepository>();
        Container.RegisterType<ICustomerRepository, CustomerRepository>();
        Container.RegisterType<ICategoryRepository, CategoryRepository>();
        Container.RegisterType<IAddressesRepository, AddressesRepository>();
        #endregion
        #region Register Services

        Container.RegisterType<IVendorService, VendorService>();
        Container.RegisterType<IUserService, UserService>();
        Container.RegisterType<IReceiveablesService, ReceiveablesService>();
        Container.RegisterType<IProductUnitService, ProductUnitService>();
        Container.RegisterType<IPaymentService, PaymentService>();

        Container.RegisterType<IItemService, ItemService>();
        Container.RegisterType<InvoiceMasterService, InvoiceMasterService>();
        Container.RegisterType<IInvoiceDetailService, InvoiceDetailService>();
        Container.RegisterType<IExpenseTypeService, ExpenseTypeService>();
        Container.RegisterType<IExpenseService, ExpenseService>();
        Container.RegisterType<ICustomerService, CustomerService>();
        Container.RegisterType<ICategoryService, CategoryService>();
        Container.RegisterType<IAddressesService, AddressesService>();

        #endregion

        Container.RegisterType<IDbFactory, DbFactory>("DbFactory", new InjectionConstructor());
        Container.RegisterType<IUnitOfWork, UnitOfWork>();
        Container.RegisterType<IDbFactory, DbFactory>();
        //Container.RegisterType<IService, >();
        Container.RegisterType<IEventAggregator, EventAggregator>(new PerThreadLifetimeManager());

        Container.RegisterTypeForNavigation<Billing>();
        Container.RegisterTypeForNavigation<Sales>();
        Container.RegisterTypeForNavigation<Management>();
        Container.RegisterTypeForNavigation<Home>();
        Container.RegisterTypeForNavigation<Orders>();
        Container.RegisterTypeForNavigation<Purchases>();

    }
   protected override void ConfigureViewModelLocator()
    {
        base.ConfigureViewModelLocator();
        Container.RegisterInstance(new DbFactory());
        Container.RegisterInstance(new UnitOfWork(Container.Resolve<DbFactory>()));
        Container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());
        Container.RegisterType<IRegionManager, RegionManager>();
        Container.RegisterInstance(new UserRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new UserService(Container.Resolve<UnitOfWork>(),Container.Resolve<UserRepository>()));
        Container.RegisterInstance(new VendorRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new VendorService(Container.Resolve<UnitOfWork>(),Container.Resolve<VendorRepository>()));
        Container.RegisterInstance(new ReceiveablesRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ReceiveablesService(Container.Resolve<UnitOfWork>(),Container.Resolve<ReceiveablesRepository>()));
        Container.RegisterInstance(new ProductUnitRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ProductUnitService(Container.Resolve<UnitOfWork>(), Container.Resolve<ProductUnitRepository>()));
        Container.RegisterInstance(new PaymentRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new PaymentService(Container.Resolve<UnitOfWork>(), Container.Resolve<PaymentRepository>()));
        Container.RegisterInstance(new ItemRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ItemService(Container.Resolve<UnitOfWork>(), Container.Resolve<ItemRepository>()));
        Container.RegisterInstance(new InvoiceMasterRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new InvoiceMasterService(Container.Resolve<UnitOfWork>(), Container.Resolve<InvoiceMasterRepository>()));
        Container.RegisterInstance(new InvoiceDetailRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new InvoiceDetailService(Container.Resolve<UnitOfWork>(), Container.Resolve<InvoiceDetailRepository>()));
        Container.RegisterInstance(new ExpenseRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ExpenseService(Container.Resolve<UnitOfWork>(), Container.Resolve<ExpenseRepository>()));
        Container.RegisterInstance(new ExpenseTypeRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ExpenseTypeService(Container.Resolve<UnitOfWork>(), Container.Resolve<ExpenseTypeRepository>()));
        Container.RegisterInstance(new CustomerRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new CustomerService(Container.Resolve<UnitOfWork>(), Container.Resolve<CustomerRepository>()));
        Container.RegisterInstance(new CategoryRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new CategoryService(Container.Resolve<UnitOfWork>(), Container.Resolve<CategoryRepository>()));
        Container.RegisterInstance(new AddressesRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new AddressesService(Container.Resolve<UnitOfWork>(), Container.Resolve<AddressesRepository>()));
        Container.RegisterType<IRegionManager, RegionManager>();
        Container.RegisterInstance<IRegionManager>(new RegionManager(), new ContainerControlledLifetimeManager());

        ViewModelLocationProvider.SetDefaultViewModelFactory((o, type) => Container.Resolve(type));
    }
</code>```

after this when i try to run my application it breaks down on bootstrap.run() and following exception is throw:

Resolution of the dependency failed, type = "Microsoft.Practices.ServiceLocation.IServiceLocator", name = "(none)".
  Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving Microsoft.Practices.ServiceLocation.IServiceLocator,(none)

答:
The reason that you're getting errors is that you are using incompatible versions. Prism 6.3 is built against Unity 4.0.1 and CommonServiceLocator 1.3.0. The newer versions of of CommonServiceLocator and Unity contain several breaking changes that make it incompatible with Prism 6.3, including a change of namespaces.

Please update to the Prism 7 preview for compatibility with Unity 5 and CommonServiceLocator 2. You can get a full list of changes within Prism 7 itself here. I will say that there are a number of breaking changes that we've added particularly in the latest preview for WPF.

Title: Unable to build Unity Container - Prism

Body:
I am trying to use prism in my WPF application. So far i have configured my container and View model locator like this:

   protected override void ConfigureContainer()
    {

        Container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());
        Container.RegisterType<IUnitOfWork, UnitOfWork>();
        Container.RegisterType<IDbFactory, DbFactory>();
        Container.RegisterType<IUnitOfWork, UnitOfWork>("UnitOfWork", new ContainerControlledLifetimeManager());
        Container.Resolve<IUnitOfWork>("UnitOfWork");
        Container.RegisterType<IDbFactory, DbFactory>("DbFactory", new ContainerControlledLifetimeManager());
        Container.Resolve<IDbFactory>("DbFactory");
        Container.RegisterType<IRegionManager, RegionManager>();
        Container.RegisterInstance<IRegionManager>(new RegionManager(), new ContainerControlledLifetimeManager());

        #region Register Repositories

        Container.RegisterType<IVendorRepository, VendorRepository>();

        Container.RegisterType<IUserRepository, UserRepository>();
        Container.RegisterType<IReceiveablesRepository, ReceiveablesRepository>();
        Container.RegisterType<IProductUnitsRepository, ProductUnitRepository>();
        Container.RegisterType<IPaymentRepository, PaymentRepository>();
        Container.RegisterType<IItemRepository, ItemRepository>();
        Container.RegisterType<IInvoiceMasterRepository, InvoiceMasterRepository>();
        Container.RegisterType<IInvoiceDetailRepository, InvoiceDetailRepository>();
        Container.RegisterType<IExpenseTypeRepository, ExpenseTypeRepository>();
        Container.RegisterType<IExpenseRepository, ExpenseRepository>();
        Container.RegisterType<ICustomerRepository, CustomerRepository>();
        Container.RegisterType<ICategoryRepository, CategoryRepository>();
        Container.RegisterType<IAddressesRepository, AddressesRepository>();
        #endregion
        #region Register Services

        Container.RegisterType<IVendorService, VendorService>();
        Container.RegisterType<IUserService, UserService>();
        Container.RegisterType<IReceiveablesService, ReceiveablesService>();
        Container.RegisterType<IProductUnitService, ProductUnitService>();
        Container.RegisterType<IPaymentService, PaymentService>();

        Container.RegisterType<IItemService, ItemService>();
        Container.RegisterType<InvoiceMasterService, InvoiceMasterService>();
        Container.RegisterType<IInvoiceDetailService, InvoiceDetailService>();
        Container.RegisterType<IExpenseTypeService, ExpenseTypeService>();
        Container.RegisterType<IExpenseService, ExpenseService>();
        Container.RegisterType<ICustomerService, CustomerService>();
        Container.RegisterType<ICategoryService, CategoryService>();
        Container.RegisterType<IAddressesService, AddressesService>();

        #endregion

        Container.RegisterType<IDbFactory, DbFactory>("DbFactory", new InjectionConstructor());
        Container.RegisterType<IUnitOfWork, UnitOfWork>();
        Container.RegisterType<IDbFactory, DbFactory>();
        //Container.RegisterType<IService, >();
        Container.RegisterType<IEventAggregator, EventAggregator>(new PerThreadLifetimeManager());

        Container.RegisterTypeForNavigation<Billing>();
        Container.RegisterTypeForNavigation<Sales>();
        Container.RegisterTypeForNavigation<Management>();
        Container.RegisterTypeForNavigation<Home>();
        Container.RegisterTypeForNavigation<Orders>();
        Container.RegisterTypeForNavigation<Purchases>();

    }
   protected override void ConfigureViewModelLocator()
    {
        base.ConfigureViewModelLocator();
        Container.RegisterInstance(new DbFactory());
        Container.RegisterInstance(new UnitOfWork(Container.Resolve<DbFactory>()));
        Container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());
        Container.RegisterType<IRegionManager, RegionManager>();
        Container.RegisterInstance(new UserRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new UserService(Container.Resolve<UnitOfWork>(),Container.Resolve<UserRepository>()));
        Container.RegisterInstance(new VendorRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new VendorService(Container.Resolve<UnitOfWork>(),Container.Resolve<VendorRepository>()));
        Container.RegisterInstance(new ReceiveablesRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ReceiveablesService(Container.Resolve<UnitOfWork>(),Container.Resolve<ReceiveablesRepository>()));
        Container.RegisterInstance(new ProductUnitRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ProductUnitService(Container.Resolve<UnitOfWork>(), Container.Resolve<ProductUnitRepository>()));
        Container.RegisterInstance(new PaymentRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new PaymentService(Container.Resolve<UnitOfWork>(), Container.Resolve<PaymentRepository>()));
        Container.RegisterInstance(new ItemRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ItemService(Container.Resolve<UnitOfWork>(), Container.Resolve<ItemRepository>()));
        Container.RegisterInstance(new InvoiceMasterRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new InvoiceMasterService(Container.Resolve<UnitOfWork>(), Container.Resolve<InvoiceMasterRepository>()));
        Container.RegisterInstance(new InvoiceDetailRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new InvoiceDetailService(Container.Resolve<UnitOfWork>(), Container.Resolve<InvoiceDetailRepository>()));
        Container.RegisterInstance(new ExpenseRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ExpenseService(Container.Resolve<UnitOfWork>(), Container.Resolve<ExpenseRepository>()));
        Container.RegisterInstance(new ExpenseTypeRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new ExpenseTypeService(Container.Resolve<UnitOfWork>(), Container.Resolve<ExpenseTypeRepository>()));
        Container.RegisterInstance(new CustomerRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new CustomerService(Container.Resolve<UnitOfWork>(), Container.Resolve<CustomerRepository>()));
        Container.RegisterInstance(new CategoryRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new CategoryService(Container.Resolve<UnitOfWork>(), Container.Resolve<CategoryRepository>()));
        Container.RegisterInstance(new AddressesRepository(Container.Resolve<DbFactory>()),new ContainerControlledLifetimeManager());
        Container.RegisterInstance(new AddressesService(Container.Resolve<UnitOfWork>(), Container.Resolve<AddressesRepository>()));
        Container.RegisterType<IRegionManager, RegionManager>();
        Container.RegisterInstance<IRegionManager>(new RegionManager(), new ContainerControlledLifetimeManager());

        ViewModelLocationProvider.SetDefaultViewModelFactory((o, type) => Container.Resolve(type));
    }

after this when i try to run my application it breaks down on bootstrap.run() and following exception is throw:

Resolution of the dependency failed, type = "Microsoft.Practices.ServiceLocation.IServiceLocator", name = "(none)".
  Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving Microsoft.Practices.ServiceLocation.IServiceLocator,(none)


问:
How to stop AWS Lambda [Nodejs]
I have a function within AWS Lambda uses runtime Node.js 6.10. Lambda runs my code fine but continues "executing" even though the code is completed. What I would like to happen is that Lambda stops when the code is completed. I have my logs below to see if anyone can see what the issue is. Note my callback to end the function returns success

{
  "errorMessage": "2017-12-07T17:50:55.618Z e4a5bb77-db76-11e7-b2e6-514284a81613 Task timed out after 120.09 seconds"
}

START RequestId: e4a5bb77-db76-11e7-b2e6-514284a81613 Version: $LATEST
2017-12-07T17:48:55.527Z    e4a5bb77-db76-11e7-b2e6-514284a81613    -L-llvVALjYpyUV0M6EG //gotten from code
2017-12-07T17:48:58.652Z    e4a5bb77-db76-11e7-b2e6-514284a81613    http://www.loopnewsbarbados.com/content/bitcoin-worth-millions-stolen-days-us-exchange-opens-1 //gotten from code
2017-12-07T17:49:01.150Z    e4a5bb77-db76-11e7-b2e6-514284a81613    crisis, //gotten from code
2017-12-07T17:49:01.232Z    e4a5bb77-db76-11e7-b2e6-514284a81613    success //successful callback
END RequestId: e4a5bb77-db76-11e7-b2e6-514284a81613
REPORT RequestId: e4a5bb77-db76-11e7-b2e6-514284a81613  Duration: 120093.31 ms  Billed Duration: 120000 ms  Memory Size: 128 MB Max Memory Used: 34 MB

2017-12-07T17:50:55.618Z e4a5bb77-db76-11e7-b2e6-514284a81613 Task timed out after 120.09 seconds

答:
You need to return in the function after context.succeed or context.fail, to prevent further execution.

If you are using callback(null, result)/(err) in the handler instead of context.succeed()/fail() you need to set callbackWaitsForEmptyEventLoop to false.

see https://gist.github.com/hassy/eaea5a958067211f2fed02ead13c2678

Title: How to stop AWS Lambda [Nodejs]


问:
Where is this error message coming from?
This error message in Visual Studio Code 1.12.2 looks very important.

Transcription: Syntax error in selector "angular:animation" at position 8: Expected "declaration", "expression", "function",
  "pattern" or "statement" but "a" ... [Tooltip hover text reads: Syntax
  error in selector "angular:animation" at position 8: Expected
  "declaration", "expression", "function", "pattern" or "statement" but
  "a" found.]

However, I have no idea what I can do about it.

Is an extension displaying it? If so, which could it be? I have about 30, and don't want to disable them all and individually enable each one.

Which file is this problem found in? It's not the file that I have open in my editor window.

The Problems window is blank.

I've checked all of the Output windows using the dropdown filter.

The Debug Console is blank.

How would I even begin to figure out the answer to my questions?

TO BE CLEAR: I don't need the error explained to me. My very first computer error was a syntax error way back in 1981. I have learned what those mean pretty well by now.

答:
Since I posted this, Visual Studio Code has been updated to indicate the extension that displays the message:

It still doesn't help that the eslint module doesn't tell me which file is mentioned. The only messages in the Output window are not helpful, either, but that's another problem.


问:
Issues with the "setdiff" command in R
I have a questions regarding an issue I have been having with the "setdiff" command in R.

I have loaded 2 excel files into R by using the following commands:

```<code>data.x<- read_excel("c:/Users/User/Dropbox/excel til R/X.xlsx", col_names=FALSE)
data.y<- read_excel("c:/Users/User/Dropbox/excel til R/Y.xlsx", col_names=FALSE)
</code>```

I then proceed to use the following command:

```<code>setdiff(data.y, data.x)
</code>```

Here I hoped it would just tell me what variables was absent in "data.x". But instead it just shows me the data that is present in "data.y", as if I simply used the command: "data.y".

Am I doing something wrong or am I missing something?

Any help would be greatly appreciated.

答:
Without access to the files noted in your question I'll present examples using

```<code>mtcars_1 <- mtcars[-1, ][, -1]
mtcars_2 <- mtcars[-2, ][, -2]

# common column names
intersect(names(mtcars_1), names(mtcars_2))

# columns names only in mtcars_0 and not in mtcars_2
setdiff(names(mtcars_1), names(mtcars_2))

# columns only in mtcars_2 and not in mtcars_1
setdiff(names(mtcars_2), names(mtcars_1))
</code>```

To get the varaibles absent in data.x with respect to data.y you would use
setdiff(data.y, data.x)

If you are looking for the rows of data.x that are not in data.y consider using the
anti_join and/or semi_join functions form the dplyr package

```<code>‘semi_join()’ return all rows from ‘x’ where there are matching
     values in ‘y’, keeping just columns from ‘x’.

     A semi join differs from an inner join because an inner join
     will return one row of ‘x’ for each matching row of ‘y’, where a
     semi join will never duplicate rows of ‘x’.

‘anti_join()’ return all rows from ‘x’ where there are not matching
     values in ‘y’, keeping just columns from ‘x’.
</code>```

```<code>dplyr::semi_join(mtcars_1, mtcars_2)
dplyr::semi_join(mtcars_2, mtcars_1)

dplyr::anti_join(mtcars_1, mtcars_2)
#   cyl disp  hp drat    wt  qsec vs am gear carb
# 1   6  160 110  3.9 2.875 17.02  0  1    4    4

dplyr::anti_join(mtcars_2, mtcars_1)
#   mpg disp  hp drat   wt  qsec vs am gear carb
# 1  21  160 110  3.9 2.62 16.46  0  1    4    4
</code>```

Title: Issues with the "setdiff" command in R

Body:
I have a questions regarding an issue I have been having with the "setdiff" command in R.

I have loaded 2 excel files into R by using the following commands:

data.x<- read_excel("c:/Users/User/Dropbox/excel til R/X.xlsx", col_names=FALSE)
data.y<- read_excel("c:/Users/User/Dropbox/excel til R/Y.xlsx", col_names=FALSE)

I then proceed to use the following command:

setdiff(data.y, data.x)

Here I hoped it would just tell me what variables was absent in "data.x". But instead it just shows me the data that is present in "data.y", as if I simply used the command: "data.y".

Am I doing something wrong or am I missing something?

Any help would be greatly appreciated.

Body:
Without access to the files noted in your question I'll present examples using

mtcars_1 <- mtcars[-1, ][, -1]
mtcars_2 <- mtcars[-2, ][, -2]

# common column names
intersect(names(mtcars_1), names(mtcars_2))

# columns names only in mtcars_0 and not in mtcars_2
setdiff(names(mtcars_1), names(mtcars_2))

# columns only in mtcars_2 and not in mtcars_1
setdiff(names(mtcars_2), names(mtcars_1))

To get the varaibles absent in data.x with respect to data.y you would use
setdiff(data.y, data.x)

If you are looking for the rows of data.x that are not in data.y consider using the
anti_join and/or semi_join functions form the dplyr package

‘semi_join()’ return all rows from ‘x’ where there are matching
     values in ‘y’, keeping just columns from ‘x’.

     A semi join differs from an inner join because an inner join
     will return one row of ‘x’ for each matching row of ‘y’, where a
     semi join will never duplicate rows of ‘x’.

‘anti_join()’ return all rows from ‘x’ where there are not matching
     values in ‘y’, keeping just columns from ‘x’.

dplyr::semi_join(mtcars_1, mtcars_2)
dplyr::semi_join(mtcars_2, mtcars_1)

dplyr::anti_join(mtcars_1, mtcars_2)
#   cyl disp  hp drat    wt  qsec vs am gear carb
# 1   6  160 110  3.9 2.875 17.02  0  1    4    4

dplyr::anti_join(mtcars_2, mtcars_1)
#   mpg disp  hp drat   wt  qsec vs am gear carb
# 1  21  160 110  3.9 2.62 16.46  0  1    4    4


问:
Contaminated Remote master branch or Anti-Cherry-Pick
I have a situation where the remote repository has some "bad" commits.
e.g.

```<code>... o ---- C ---- A ---- B  origin/master
</code>```

Where A is bad (but B is good)
I want the remote to become...

```<code>... o ---- C ---- B  origin/master
                   \
                    A  origin/dev
</code>```

It is not obvious to me how to do this.

In the case where a rebase is inappropriate a different result is needed.

```<code>... o ---- C ---- A ---- B ---- ~A origin/master
                          \
                           -  origin/dev
</code>```

This results in a dev branch containing the A commit and the master not containing the A commit.
The revised question is:
How to do an anti-cherry-pick?
So rather than generating a patch which changes the repository from state C to A apply a patch which changes B to A.

答:
Pull so that you have the same repository locally.

Use git rebase --interactive (see this rundown if you are unfamiliar with interactive rebase) to reorder the A and B commits, so that you now have

```<code>... o ---- o ---- B ---- A  master
</code>```

Checkout a new branch dev from that spot, so you get

```<code>... o ---- o ---- B ---- A  master, dev
</code>```

Switch to the master branch, do a git reset --hard HEAD^ to rewind that branch one commit. You now have

```<code>... o ---- o ---- B  master
                   \
                    A  dev
</code>```

Now git push --force --all and you should be golden. (You need --force because you are rewriting history in the remote repository, which is dangerous and not recommended if other developers have already pulled from it.)

Body:
I have a situation where the remote repository has some "bad" commits.
e.g.

... o ---- C ---- A ---- B  origin/master

Where A is bad (but B is good)
I want the remote to become...

... o ---- C ---- B  origin/master
                   \
                    A  origin/dev

It is not obvious to me how to do this.

In the case where a rebase is inappropriate a different result is needed.

... o ---- C ---- A ---- B ---- ~A origin/master
                          \
                           -  origin/dev

This results in a dev branch containing the A commit and the master not containing the A commit.
The revised question is:
How to do an anti-cherry-pick?
So rather than generating a patch which changes the repository from state C to A apply a patch which changes B to A.

Body:
Pull so that you have the same repository locally.

Use git rebase --interactive (see this rundown if you are unfamiliar with interactive rebase) to reorder the A and B commits, so that you now have

... o ---- o ---- B ---- A  master

Checkout a new branch dev from that spot, so you get

... o ---- o ---- B ---- A  master, dev

Switch to the master branch, do a git reset --hard HEAD^ to rewind that branch one commit. You now have

... o ---- o ---- B  master
                   \
                    A  dev

Now git push --force --all and you should be golden. (You need --force because you are rewriting history in the remote repository, which is dangerous and not recommended if other developers have already pulled from it.)


问:
Param I'm trying to pass through hidden field is showing as an object?
I am trying to use a hidden field in a form to pass a param with a value of 1 to a method in my controller, which will add the value to the quantity of an order item in a shopping cart. When I check what I'm getting with a binding pry, I see that for params the :update_by param I am trying to pass is showing as an object "order_items=>{"update_by"=>"1"}. So, when I try to grab the param in the method using params[:update_by], I get nil (or 0 if .to_i). Why is the param an object?

Please see the html for the form

```<code><% if @order_items.any? %>
  <% @order_items.each do |item| %>
    <%= form_for item do |f| %>
      <%= f.hidden_field :update_by, value: 1 %>
        <%= button_tag type:"submit", class: "cart_quantity_button"
        do %>
        <i class="fa fa-plus-circle" aria-hidden="true"></i>
      <% end %>
    <% end %>
<% end %>
</code>```

And the method in the controller

```<code>def update
  @order = current_order
  @item = OrderItem.find(params[:id])
  @item.update(:quantity=> @item.quantity + params[:update_by].to_i)
  @item.save!
  redirect_to cart_path
end

private

def item_params
  params.require(:order_item).permit(:quantity, :product_id,
  :user_id, :update_by)
  end
end
</code>```

I am grabbing the data I want from the other varaiables in my method. The problem is that I can't grab the value of :update_by if it's an object, right? Let me know if you need any more information. Thanks!

答:
My friend found a solution for me by moving the value of the param to the button instead of a hidden form field.

```<code>  <%= form_for (item) do |f| %>
    <% button_tag type:"submit", :value => item.quantity.to_i + 1, class: "cart_quantity_button" do %>
      <p><i class="fa fa-plus-circle" aria-hidden="true"></i></p>
    <% end %>
  <% end %>

  <%= form_for (item) do |f| %>
    <% button_tag type:"submit", :value => item.quantity.to_i - 1, class: "cart_quantity_button" do %>
      <p><i class="fa fa-minus-circle" aria-hidden="true"></i></p>
    <% end %>
  <% end %>
</code>```

If you have an explanation for this solution, please let me know. We are both noobs. Thanks!

Body:
I am trying to use a hidden field in a form to pass a param with a value of 1 to a method in my controller, which will add the value to the quantity of an order item in a shopping cart. When I check what I'm getting with a binding pry, I see that for params the :update_by param I am trying to pass is showing as an object "order_items=>{"update_by"=>"1"}. So, when I try to grab the param in the method using params[:update_by], I get nil (or 0 if .to_i). Why is the param an object?

Please see the html for the form

<% if @order_items.any? %>
  <% @order_items.each do |item| %>
    <%= form_for item do |f| %>
      <%= f.hidden_field :update_by, value: 1 %>
        <%= button_tag type:"submit", class: "cart_quantity_button"
        do %>

      <% end %>
    <% end %>
<% end %>

And the method in the controller

def update
  @order = current_order
  @item = OrderItem.find(params[:id])
  @item.update(:quantity=> @item.quantity + params[:update_by].to_i)
  @item.save!
  redirect_to cart_path
end

private

def item_params
  params.require(:order_item).permit(:quantity, :product_id,
  :user_id, :update_by)
  end
end

I am grabbing the data I want from the other varaiables in my method. The problem is that I can't grab the value of :update_by if it's an object, right? Let me know if you need any more information. Thanks!

Body:
My friend found a solution for me by moving the value of the param to the button instead of a hidden form field.

  <%= form_for (item) do |f| %>
    <% button_tag type:"submit", :value => item.quantity.to_i + 1, class: "cart_quantity_button" do %>
      <p><i class="fa fa-plus-circle" aria-hidden="true"></i></p>
    <% end %>
  <% end %>

  <%= form_for (item) do |f| %>
    <% button_tag type:"submit", :value => item.quantity.to_i - 1, class: "cart_quantity_button" do %>
      <p><i class="fa fa-minus-circle" aria-hidden="true"></i></p>
    <% end %>
  <% end %>

If you have an explanation for this solution, please let me know. We are both noobs. Thanks!


问:
Lucene query modification
I have a requirement where I want to modify string formatted lucene query values.
I am taking lucene query as input from user interface and passing it to elastic.

For e.g.

Input : name:"abc" and age:26

Output expected: name: "abcmodified" and userage:26

How do I parse and modify string formatted lucene query in java?

答:
Have you tried looking into org.apache.lucene.queryparser.classic.QueryParser? It has functionality to return a Lucene Query Object from an input string. For example:

```<code>String rawQuery = "name:abc AND age:26";
QueryParser parser = new QueryParser(Version.LUCENE_45, null, new WhitespaceAnalyzer(Version.LUCENE_45));
BooleanQuery query = (BooleanQuery) praser.parse(rawQuery);
query.clauses().get(0).setQuery(new TermQuery(new Term("name", "abcmodified")));
query.clauses().get(1).setQuery(new TermQuery(new Term("userage", "26")));
System.out.println(query);
</code>```

Will print +name:abcmodified +userage:26, which is essentially what you want. Obviously you can have smarter processing using a recursive method that traverses the query based on the query type (Boolean, Prefix, Term, Fuzzy etc...)

Hope this helps!

Title: Lucene query modification

Body:
Have you tried looking into org.apache.lucene.queryparser.classic.QueryParser? It has functionality to return a Lucene Query Object from an input string. For example:

String rawQuery = "name:abc AND age:26";
QueryParser parser = new QueryParser(Version.LUCENE_45, null, new WhitespaceAnalyzer(Version.LUCENE_45));
BooleanQuery query = (BooleanQuery) praser.parse(rawQuery);
query.clauses().get(0).setQuery(new TermQuery(new Term("name", "abcmodified")));
query.clauses().get(1).setQuery(new TermQuery(new Term("userage", "26")));
System.out.println(query);

Will print +name:abcmodified +userage:26, which is essentially what you want. Obviously you can have smarter processing using a recursive method that traverses the query based on the query type (Boolean, Prefix, Term, Fuzzy etc...)

Hope this helps!


问:
Django REST framework serialization error on pk field
In my Django REST framework project i have this model:

```<code>class ml_request(models.Model):
    model_id = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now=True)
    p_country = models.CharField(max_length=100, blank=False, default='')
    p_description = models.TextField(null=False, blank=False)
    p_designation = models.CharField(max_length=200, blank=False, default='')
    p_points = models.IntegerField(default=00)
    p_price = models.IntegerField(default=00, blank=False)
    p_province = models.CharField(max_length=100, blank=False, default='')
    p_region_1 = models.CharField(max_length=100, blank=False, default='')
    p_region_2 = models.CharField(max_length=100, blank=False, default='')
    p_variety = models.CharField(max_length=100, blank=False, default='')
    p_winery = models.CharField(max_length=100, blank=False, default='')
    owner = models.ForeignKey('auth.User', related_name='req_owner',
on_delete=models.CASCADE)
    highlighted = models.TextField()

class Meta:
    ordering = ('created',)
</code>```

then i create my serializer like this:

```<code>from rest_framework import serializers
from botoapi.models import ml_request, ml_response, LANGUAGE_CHOICES,
STYLE_CHOICES, ml_logs
from django.contrib.auth.models import User

class RequestSerializer(serializers.HyperlinkedModelSerializer):

    id = serializers.IntegerField(label='ID', read_only=True)
    highlight = serializers.HyperlinkedIdentityField(view_name='request-highlight', format='html')
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = ml_request
        fields = ('id', 'model_id', 'highlight', 'created', 'p_country',
'p_description', 'p_designation',
              'p_points', 'p_price', 'p_province', 'p_region_1', 'p_region_2',
'p_variety', 'p_winery', 'owner')

        def create(self, validated_data):
            log_save = ml_logs(l_verbose=validated_data, l_method="CREATE",
             l_action=validated_data.get("model_id", None))
            log_save.save()
            return validated_data
</code>```

and is my view code:

```<code>class RequestViewSet(viewsets.ModelViewSet):
    queryset = ml_request.objects.all()
    serializer_class = RequestSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,
                      IsOwnerOrReadOnly,)

    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
</code>```

bur when i run it and try to add values django return this error:

AttributeError at /requests/
  'dict' object has no attribute 'pk'
  Request Method: POST
  Request URL:    http://127.0.0.1:8000/requests/
  Django Version: 1.11.7
  Exception Type: AttributeError
  Exception Value:

  'dict' object has no attribute 'pk'

i have the id as PK and i add it in my serializer, someone can help me to wonder why this happens?

Thanks in advance

答:
From 3.x onwards,

If you want to add django auto 'id' explicitly in HyperlinkedModelSerializer, you need to use ReadOnlyField (not an IntegerField). Or else you can include it in 'fields'.

```<code>class RequestSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()
</code>```

And by default the serializer will include a url field instead of a primary key field. You can explicitly include the primary key by adding it to the fields option.

The name of the URL field defaults to 'url'. You can override this
  globally, by using the URL_FIELD_NAME setting.

Body:
In my Django REST framework project i have this model:

class ml_request(models.Model):
    model_id = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now=True)
    p_country = models.CharField(max_length=100, blank=False, default='')
    p_description = models.TextField(null=False, blank=False)
    p_designation = models.CharField(max_length=200, blank=False, default='')
    p_points = models.IntegerField(default=00)
    p_price = models.IntegerField(default=00, blank=False)
    p_province = models.CharField(max_length=100, blank=False, default='')
    p_region_1 = models.CharField(max_length=100, blank=False, default='')
    p_region_2 = models.CharField(max_length=100, blank=False, default='')
    p_variety = models.CharField(max_length=100, blank=False, default='')
    p_winery = models.CharField(max_length=100, blank=False, default='')
    owner = models.ForeignKey('auth.User', related_name='req_owner',
on_delete=models.CASCADE)
    highlighted = models.TextField()

class Meta:
    ordering = ('created',)

then i create my serializer like this:

from rest_framework import serializers
from botoapi.models import ml_request, ml_response, LANGUAGE_CHOICES,
STYLE_CHOICES, ml_logs
from django.contrib.auth.models import User

class RequestSerializer(serializers.HyperlinkedModelSerializer):

    id = serializers.IntegerField(label='ID', read_only=True)
    highlight = serializers.HyperlinkedIdentityField(view_name='request-highlight', format='html')
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = ml_request
        fields = ('id', 'model_id', 'highlight', 'created', 'p_country',
'p_description', 'p_designation',
              'p_points', 'p_price', 'p_province', 'p_region_1', 'p_region_2',
'p_variety', 'p_winery', 'owner')

        def create(self, validated_data):
            log_save = ml_logs(l_verbose=validated_data, l_method="CREATE",
             l_action=validated_data.get("model_id", None))
            log_save.save()
            return validated_data

and is my view code:

class RequestViewSet(viewsets.ModelViewSet):
    queryset = ml_request.objects.all()
    serializer_class = RequestSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,
                      IsOwnerOrReadOnly,)

    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

bur when i run it and try to add values django return this error:

AttributeError at /requests/
  'dict' object has no attribute 'pk'
  Request Method: POST
  Request URL:    http://127.0.0.1:8000/requests/
  Django Version: 1.11.7
  Exception Type: AttributeError
  Exception Value:

  'dict' object has no attribute 'pk'

i have the id as PK and i add it in my serializer, someone can help me to wonder why this happens?

Thanks in advance

Body:
From 3.x onwards,

If you want to add django auto 'id' explicitly in HyperlinkedModelSerializer, you need to use ReadOnlyField (not an IntegerField). Or else you can include it in 'fields'.

class RequestSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()

And by default the serializer will include a url field instead of a primary key field. You can explicitly include the primary key by adding it to the fields option.

The name of the URL field defaults to 'url'. You can override this
  globally, by using the URL_FIELD_NAME setting.


问:
Turn off automatic pagination of Django Rest Framework ModelViewSet
I am using Django Rest Framework's ModelViewSet for one of my views. ModelViewSet uses the ListModelMixin which automatically paginates the results but I do not want the results paginated. In my API call I say how many results I want returned but as it stands I can't get back more than 10 results in one call.

Is there a way to turn off the automatic pagination and so I can have as many results as I want returned?

答:
ModelViewSet or mixins.ListModelMixin automatically create pagination for us. You can stop it by
paginator = None

```<code>class NotesViewSet(viewsets.ModelViewSet):
     queryset = Notes.objects.all()
     serializer_class = NotesWriteSerializer
     paginator = None
</code>```

Body:
ModelViewSet or mixins.ListModelMixin automatically create pagination for us. You can stop it by
paginator = None

class NotesViewSet(viewsets.ModelViewSet):
     queryset = Notes.objects.all()
     serializer_class = NotesWriteSerializer
     paginator = None


问:
Replacing opening and closing parenthesis of a certain strucure?
I'm trying to replace the parenthesis inside a certain tag to just outside of the tag i.e. if there is a opening parenthesis immediately after the tag or a closing parenthesis immediately before the closing tag. Example:

```<code><italic>(When a parenthetical sentence stands on its own)</italic>
<italic>(When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own)</italic>
</code>```

Those lines should be after replace:

```<code>(<italic>When a parenthetical sentence stands on its own</italic>)
(<italic>When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own</italic>)
</code>```

However, strings like the the next three below should stay untouched.

```<code><italic>(When) a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its (own)</italic>
<italic>When a parenthetical sentence stands (on) its own</italic>
</code>```

But the following strings:

```<code><italic>((When) a parenthetical sentence stands on its own</italic>
<italic>((When) a parenthetical sentence stands on its own)</italic>
<italic>(When) a parenthetical sentence stands on its own)</italic>
<italic>When a parenthetical sentence stands on its (own))</italic>
<italic>(When a parenthetical sentence stands on its (own)</italic>
</code>```

should be after the replace(s):

```<code>(<italic>(When) a parenthetical sentence stands on its own</italic>
(<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>When a parenthetical sentence stands on its (own)</italic>)
(<italic>When a parenthetical sentence stands on its (own)</italic>
</code>```

There could be nested tags inside the <italic>...</italic> tags and a line can contain multiple <italic>...</italic> strings.
Also if there is a nested tag <inline-formula>...</inline-formula> inside <italic>...</italic> then those should be ignored.

Can I do this using regex? If not what other way can I do this?

My approach is this (I am still not sure if it covers all possible cases):

1st step: <italic>( ---> (<italic>
find <italic>( if the tag is not followed by a matching pair of parenthesis immediately not followed by a closing tag
The match is allowed only within a single line.

Find what: (<(italic)>)(?!(\((?>(?:(?![()\r\n]).)++|(?3))*+\))(?!</$2\b))(\()
Replace with: $4$1

2nd step: )</italic> ---> </italic>)
find )</italic> if the tag is not preceded by a matching pair of parenthesis immediately not preceded by an opening tag
The match is allowed only within a single line.

(\))(?<!(?<!<(italic)>)(\((?>(?:(?![()\r\n]).)++|(?3))*+\)))(</2\b>)

答:
You could do this a few different ways, I would start by defining when a tag is replaceable.

We can replace the opening tag if the text in the tag starts with ( and is either closed right before the closing tag, or is unclosed

We can replace the closing tag if the text in the tag ends with ) and it was opened right after the opening tag, or it was unopened

This problem seems like it lends itself to a parser approach and keeping track of the parenthesis state (was there a parenthesis at the beginning of the tag text, and how nested are the parenthesis at the current point). Writing a parser would let us do the replacement in a constructive manner as opposed to searching with a regex, and replacing substrings and would be naturally recursive which would handle nesting. Doing this with a regex seems a bit convoluted. Here's what I came up with.

```<code>using System;
using System.IO;
using System.Text;

namespace ParenParser {
    public class Program
    {
        public static Stream GenerateStreamFromString(string s)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(s);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }

        public static String Process(StreamReader s) { // root
            StringBuilder output = new StringBuilder();
            while (!s.EndOfStream) {
                var ch = Convert.ToChar(s.Read());
                if (ch == '<') {
                    output.Append(ProcessTag(s, true));
                } else {
                    output.Append(ch);
                }
            }

            return output.ToString();
        }

        public static String ProcessTag(StreamReader s, bool skipOpeningBracket = true) {
            int currentParenDepth = 0;
            StringBuilder openingTag = new StringBuilder(), allTagText = new StringBuilder(), closingTag = new StringBuilder();
            bool inOpeningTag = false, inClosingTag = false;
            if (skipOpeningBracket) {
                inOpeningTag = true;
                openingTag.Append('<');
                skipOpeningBracket = false;
            }

            while (!s.EndOfStream) {
                var ch = Convert.ToChar(s.Read());
                if (ch == '<') { // start of a tag
                    var nextCh = Convert.ToChar(s.Peek());
                    if (nextCh == '/') { // closing tag!
                        closingTag.Append(ch);
                        inClosingTag = true;
                    } else if (openingTag.ToString().Length != 0) { // already seen a tag, recurse
                        allTagText.Append(ProcessTag(s, true));
                        continue;
                    } else {
                        openingTag.Append(ch);
                        inOpeningTag = true;
                    }
                }
                else if (inOpeningTag) {
                    openingTag.Append(ch);
                    if (ch == '>') {
                        inOpeningTag = false;
                    }
                }
                else if (inClosingTag) {
                    closingTag.Append(ch);
                    if (ch == '>') {
                        // Done!
                        var allTagTextString = allTagText.ToString();
                        if (allTagTextString.Length > 0 && allTagTextString[0] == '(' && allTagTextString[allTagTextString.Length - 1] == ')' && currentParenDepth == 0) {
                            return "(" + openingTag.ToString() + allTagTextString.Substring(1, allTagTextString.Length - 2) + closingTag.ToString() + ")";
                        } else if (allTagTextString.Length > 0 && allTagTextString[0] == '(' && currentParenDepth > 0) { // unclosed
                            return "(" + openingTag.ToString() + allTagTextString.Substring(1, allTagTextString.Length - 1) + closingTag.ToString();
                        } else if (allTagTextString.Length > 0 && allTagTextString[allTagTextString.Length - 1] == ')' && currentParenDepth < 0) { // unopened
                            return openingTag.ToString() + allTagTextString.Substring(0, allTagTextString.Length - 1) + closingTag.ToString() + ")";
                        } else {
                            return openingTag.ToString() + allTagTextString + closingTag.ToString();
                        }
                    }
                }
                else
                {
                    allTagText.Append(ch);
                    if (ch == '(') {
                        currentParenDepth++;
                    }
                    else if (ch == ')') {
                        currentParenDepth--;
                    }
                }
            }

            return openingTag.ToString() + allTagText.ToString() + closingTag.ToString();
        }

        public static void Main()
        {
            var testCases = new String[] {
                // Should change
                "<italic>(When a parenthetical sentence stands on its own)</italic>",
                "<italic>(When a parenthetical sentence stands on its own</italic>",
                "<italic>When a parenthetical sentence stands on its own)</italic>",

                // Should remain unchanged
                "<italic>(When) a parenthetical sentence stands on its own</italic>",
                "<italic>When a parenthetical sentence stands on its (own)</italic>",
                "<italic>When a parenthetical sentence stands (on) its own</italic>",

                // Should be changed
                "<italic>((When) a parenthetical sentence stands on its own</italic>",
                "<italic>((When) a parenthetical sentence stands on its own)</italic>",
                "<italic>(When) a parenthetical sentence stands on its own)</italic>",
                "<italic>When a parenthetical sentence stands on its (own))</italic>",
                "<italic>(When a parenthetical sentence stands on its (own)</italic>",

                // Other cases
                "<italic>(Try This on!)</italic>",
                "<italic><italic>(Try This on!)</italic></italic>",
                "<italic></italic>",
                "",
                "()",
                "<italic>()</italic>",
                "<italic>"
            };

            foreach(var testCase in testCases) {
                using(var testCaseStreamReader = new StreamReader(GenerateStreamFromString(testCase))) {
                    Console.WriteLine(testCase + " --> " + Process(testCaseStreamReader));
                }
            }
        }
    }
}
</code>```

The test case results look something like

```<code><italic>(When a parenthetical sentence stands on its own</italic> --> (<italic>When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own)</italic> --> <italic>When a parenthetical sentence stands on its own</italic>)
<italic>(When) a parenthetical sentence stands on its own</italic> --> <italic>(When) a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its (own)</italic> --> <italic>When a parenthetical sentence stands on its (own)</italic>
<italic>When a parenthetical sentence stands (on) its own</italic> --> <italic>When a parenthetical sentence stands (on) its own</italic>
<italic>((When) a parenthetical sentence stands on its own</italic> --> (<italic>(When) a parenthetical sentence stands on its own</italic>
<italic>((When) a parenthetical sentence stands on its own)</italic> --> (<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>(When) a parenthetical sentence stands on its own)</italic> --> <italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>When a parenthetical sentence stands on its (own))</italic> --> <italic>When a parenthetical sentence stands on its (own)</italic>)
<italic>(When a parenthetical sentence stands on its (own)</italic> --> (<italic>When a parenthetical sentence stands on its (own)</italic>
<italic>(Try This on!)</italic> --> (<italic>Try This on!</italic>)
<italic><italic>(Try This on!)</italic></italic> --> (<italic><italic>Try This on!</italic></italic>)
<italic></italic> --> <italic></italic>
 -->
() --> ()
<italic>()</italic> --> (<italic></italic>)
<italic> --> <italic>
</code>```

Body:
I'm trying to replace the parenthesis inside a certain tag to just outside of the tag i.e. if there is a opening parenthesis immediately after the tag or a closing parenthesis immediately before the closing tag. Example:

<italic>(When a parenthetical sentence stands on its own)</italic>
<italic>(When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own)</italic>

Those lines should be after replace:

(<italic>When a parenthetical sentence stands on its own</italic>)
(<italic>When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own</italic>)

However, strings like the the next three below should stay untouched.

<italic>(When) a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its (own)</italic>
<italic>When a parenthetical sentence stands (on) its own</italic>

But the following strings:

<italic>((When) a parenthetical sentence stands on its own</italic>
<italic>((When) a parenthetical sentence stands on its own)</italic>
<italic>(When) a parenthetical sentence stands on its own)</italic>
<italic>When a parenthetical sentence stands on its (own))</italic>
<italic>(When a parenthetical sentence stands on its (own)</italic>

should be after the replace(s):

(<italic>(When) a parenthetical sentence stands on its own</italic>
(<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>When a parenthetical sentence stands on its (own)</italic>)
(<italic>When a parenthetical sentence stands on its (own)</italic>

There could be nested tags inside the <italic>...</italic> tags and a line can contain multiple <italic>...</italic> strings.
Also if there is a nested tag <inline-formula>...</inline-formula> inside <italic>...</italic> then those should be ignored.

Can I do this using regex? If not what other way can I do this?

My approach is this (I am still not sure if it covers all possible cases):

1st step: <italic>( ---> (<italic>
find <italic>( if the tag is not followed by a matching pair of parenthesis immediately not followed by a closing tag
The match is allowed only within a single line.

Find what: (<(italic)>)(?!(\((?>(?:(?![()\r\n]).)++|(?3))*+\))(?!</$2\b))(\()
Replace with: $4$1

2nd step: )</italic> ---> </italic>)
find )</italic> if the tag is not preceded by a matching pair of parenthesis immediately not preceded by an opening tag
The match is allowed only within a single line.

(\))(?<!(?<!<(italic)>)(\((?>(?:(?![()\r\n]).)++|(?3))*+\)))(</2\b>)

Body:
You could do this a few different ways, I would start by defining when a tag is replaceable.

We can replace the opening tag if the text in the tag starts with ( and is either closed right before the closing tag, or is unclosed

We can replace the closing tag if the text in the tag ends with ) and it was opened right after the opening tag, or it was unopened

This problem seems like it lends itself to a parser approach and keeping track of the parenthesis state (was there a parenthesis at the beginning of the tag text, and how nested are the parenthesis at the current point). Writing a parser would let us do the replacement in a constructive manner as opposed to searching with a regex, and replacing substrings and would be naturally recursive which would handle nesting. Doing this with a regex seems a bit convoluted. Here's what I came up with.

using System;
using System.IO;
using System.Text;

namespace ParenParser {
    public class Program
    {
        public static Stream GenerateStreamFromString(string s)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(s);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }

        public static String Process(StreamReader s) { // root
            StringBuilder output = new StringBuilder();
            while (!s.EndOfStream) {
                var ch = Convert.ToChar(s.Read());
                if (ch == '<') {
                    output.Append(ProcessTag(s, true));
                } else {
                    output.Append(ch);
                }
            }

            return output.ToString();
        }

        public static String ProcessTag(StreamReader s, bool skipOpeningBracket = true) {
            int currentParenDepth = 0;
            StringBuilder openingTag = new StringBuilder(), allTagText = new StringBuilder(), closingTag = new StringBuilder();
            bool inOpeningTag = false, inClosingTag = false;
            if (skipOpeningBracket) {
                inOpeningTag = true;
                openingTag.Append('<');
                skipOpeningBracket = false;
            }

            while (!s.EndOfStream) {
                var ch = Convert.ToChar(s.Read());
                if (ch == '<') { // start of a tag
                    var nextCh = Convert.ToChar(s.Peek());
                    if (nextCh == '/') { // closing tag!
                        closingTag.Append(ch);
                        inClosingTag = true;
                    } else if (openingTag.ToString().Length != 0) { // already seen a tag, recurse
                        allTagText.Append(ProcessTag(s, true));
                        continue;
                    } else {
                        openingTag.Append(ch);
                        inOpeningTag = true;
                    }
                }
                else if (inOpeningTag) {
                    openingTag.Append(ch);
                    if (ch == '>') {
                        inOpeningTag = false;
                    }
                }
                else if (inClosingTag) {
                    closingTag.Append(ch);
                    if (ch == '>') {
                        // Done!
                        var allTagTextString = allTagText.ToString();
                        if (allTagTextString.Length > 0 && allTagTextString[0] == '(' && allTagTextString[allTagTextString.Length - 1] == ')' && currentParenDepth == 0) {
                            return "(" + openingTag.ToString() + allTagTextString.Substring(1, allTagTextString.Length - 2) + closingTag.ToString() + ")";
                        } else if (allTagTextString.Length > 0 && allTagTextString[0] == '(' && currentParenDepth > 0) { // unclosed
                            return "(" + openingTag.ToString() + allTagTextString.Substring(1, allTagTextString.Length - 1) + closingTag.ToString();
                        } else if (allTagTextString.Length > 0 && allTagTextString[allTagTextString.Length - 1] == ')' && currentParenDepth < 0) { // unopened
                            return openingTag.ToString() + allTagTextString.Substring(0, allTagTextString.Length - 1) + closingTag.ToString() + ")";
                        } else {
                            return openingTag.ToString() + allTagTextString + closingTag.ToString();
                        }
                    }
                }
                else
                {
                    allTagText.Append(ch);
                    if (ch == '(') {
                        currentParenDepth++;
                    }
                    else if (ch == ')') {
                        currentParenDepth--;
                    }
                }
            }

            return openingTag.ToString() + allTagText.ToString() + closingTag.ToString();
        }

        public static void Main()
        {
            var testCases = new String[] {
                // Should change
                "<italic>(When a parenthetical sentence stands on its own)</italic>",
                "<italic>(When a parenthetical sentence stands on its own</italic>",
                "<italic>When a parenthetical sentence stands on its own)</italic>",

                // Should remain unchanged
                "<italic>(When) a parenthetical sentence stands on its own</italic>",
                "<italic>When a parenthetical sentence stands on its (own)</italic>",
                "<italic>When a parenthetical sentence stands (on) its own</italic>",

                // Should be changed
                "<italic>((When) a parenthetical sentence stands on its own</italic>",
                "<italic>((When) a parenthetical sentence stands on its own)</italic>",
                "<italic>(When) a parenthetical sentence stands on its own)</italic>",
                "<italic>When a parenthetical sentence stands on its (own))</italic>",
                "<italic>(When a parenthetical sentence stands on its (own)</italic>",

                // Other cases
                "<italic>(Try This on!)</italic>",
                "<italic><italic>(Try This on!)</italic></italic>",
                "<italic></italic>",
                "",
                "()",
                "<italic>()</italic>",
                "<italic>"
            };

            foreach(var testCase in testCases) {
                using(var testCaseStreamReader = new StreamReader(GenerateStreamFromString(testCase))) {
                    Console.WriteLine(testCase + " --> " + Process(testCaseStreamReader));
                }
            }
        }
    }
}

The test case results look something like

<italic>(When a parenthetical sentence stands on its own</italic> --> (<italic>When a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its own)</italic> --> <italic>When a parenthetical sentence stands on its own</italic>)
<italic>(When) a parenthetical sentence stands on its own</italic> --> <italic>(When) a parenthetical sentence stands on its own</italic>
<italic>When a parenthetical sentence stands on its (own)</italic> --> <italic>When a parenthetical sentence stands on its (own)</italic>
<italic>When a parenthetical sentence stands (on) its own</italic> --> <italic>When a parenthetical sentence stands (on) its own</italic>
<italic>((When) a parenthetical sentence stands on its own</italic> --> (<italic>(When) a parenthetical sentence stands on its own</italic>
<italic>((When) a parenthetical sentence stands on its own)</italic> --> (<italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>(When) a parenthetical sentence stands on its own)</italic> --> <italic>(When) a parenthetical sentence stands on its own</italic>)
<italic>When a parenthetical sentence stands on its (own))</italic> --> <italic>When a parenthetical sentence stands on its (own)</italic>)
<italic>(When a parenthetical sentence stands on its (own)</italic> --> (<italic>When a parenthetical sentence stands on its (own)</italic>
<italic>(Try This on!)</italic> --> (<italic>Try This on!</italic>)
<italic><italic>(Try This on!)</italic></italic> --> (<italic><italic>Try This on!</italic></italic>)
<italic></italic> --> <italic></italic>
 -->
() --> ()
<italic>()</italic> --> (<italic></italic>)
<italic> --> <italic>


问:
BSD Root Error Virtualbox install Mac OSX
I am trying to install Mac OSX on Windows XP using virtualbox and keep getting this message: BSD root: disk1s3, major 14, minor 3.  I have assigned an 80gb virtual hard drive and have tried other iso files, but get the same message.

答: Technically installing MAC OSX on a virtual machine is against the EULA. That being said it's not a trivial operation to get OSX running on a VM. You might want to check out The OSX86 Project </p>