问:
npm - How to actually use package-lock.json for installing based on locked versions?
Just updated from npm 3 to 5, to use this feature.

Sorry, I must be missing something totally obvious, but how do make npm respect the pinned versions in package-lock.json file when installing?

Let's say I have a package.json with a fair bit of outdated packages.  Doing an npm install will pull in new stuff and breaks my app.

For example, the main package I want to stabilize is bootstrap - I want to block its version at bootstrap@4.0.0-alpha.6 for now, but npm install finds 4.0.0-beta.28.

If I npm update any package, package-lock.json gets updated.

Let's go to my development directory.

This is my package.json entry for bootstrap:

"bootstrap": "^4.0.0-alpha.6"

And this is what I see for my installed packages and meta data:

```<code>$ npm list 2>/dev/null | grep bootstrap
├─┬ bootstrap@4.0.0-alpha.6
├─┬ bootstrap-vue@0.16.1
│ ├── bootstrap@4.0.0-alpha.6 deduped

(env) jluc@py$ grep bootstrap package.json package-lock.json
package.json:    "bootstrap": "^4.0.0-alpha.6",
package.json:    "bootstrap-vue": "^0.16.1",
package-lock.json:    "bootstrap": {
package-lock.json:      "version": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.0.0-alpha.6.tgz",
package-lock.json:    "bootstrap-vue": {
package-lock.json:      "version": "https://registry.npmjs.org/bootstrap-vue/-/bootstrap-vue-0.16.1.tgz",
package-lock.json:        "bootstrap": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.0.0-alpha.6.tgz",
</code>```

Looks good.  Lock is bootstrap-4.0.0-alpha.6.

But how I use actually use that package-lock.json?

Here's what I did:

created a brand new directory

copied in package.json and package-lock.json

ran npm install.

No good.  npm again found bootstrap beta and package-lock.json had no effect, in fact it was rewritten from what npm install did.   Which is consistent with the behavior you want in dev, but doesn't tell me how I would use the lockfile to stabilize my packages.

```<code>(env) jluc@trynpmlock$ npm list 2>/dev/null | grep bootstrap
├── bootstrap@4.0.0-beta.2
├─┬ bootstrap-vue@0.16.1
│ ├── bootstrap@4.0.0-beta.2 deduped

(env) jluc@trynpmlock$ grep bootstrap package.json package-lock.json
package.json:    "bootstrap": "^4.0.0-alpha.6",
package.json:    "bootstrap-vue": "^0.16.1",
package-lock.json:    "bootstrap": {
package-lock.json:      "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.0.0-beta.2.tgz",
package-lock.json:    "bootstrap-vue": {
package-lock.json:      "resolved": "https://registry.npmjs.org/bootstrap-vue/-/bootstrap-vue-0.16.1.tgz",
package-lock.json:        "bootstrap": "4.0.0-beta.2",
</code>```

If I delete the package.json and only have a directory with package-lock.json, then npm install installs very little and leaves me with a truncated package-lock.json

npm install has a --no-package-lock option, but that prevents updating the package-lock.json.

Basically how do I tell npm install everything from package.json, but respect locks in package-lock.json?  Do I use a different command than npm install?  Is it because npm install's doc refers to locks in the context of a package installation, but locks don't apply when you install the package.json in its entirety?

Yes, I know I can specify "bootstrap": "4.0.0-alpha.6", minus the ^, to pin the version manually.

My environment:

```<code>(env) jluc@py$ npm -v
5.5.1
</code>```

答:
Update: As Dave pointed out, the command for this situation is now npm ci.  It will install from package-lock.json and will not update it. See the documentation for more information.

According to this comment by a member of the npm CLI team, what you are describing is a "high priority bug".

If you have a package.json and you run npm i we generate a package-lock.json from it.

If you run npm i against that package.json and package-lock.json, the latter will never be updated, even if the package.json would be happy with newer versions.

If you manually edit your package.json to have different ranges and run npm i and those ranges aren't compatible with your package-lock.json then the latter will be updated with version that are compatible with your package.json. Further runs of npm i will be as with 2 above.

If you do run into a case where npm@^5.4.2 mutates a package-lock.json that was otherwise compatible with the paired package.json please open a new issue. This sort of thing would constitute a high priority bug.

Body:
Just updated from npm 3 to 5, to use this feature.

Sorry, I must be missing something totally obvious, but how do make npm respect the pinned versions in package-lock.json file when installing?

Let's say I have a package.json with a fair bit of outdated packages.  Doing an npm install will pull in new stuff and breaks my app.

For example, the main package I want to stabilize is bootstrap - I want to block its version at bootstrap@4.0.0-alpha.6 for now, but npm install finds 4.0.0-beta.28.

If I npm update any package, package-lock.json gets updated.

Let's go to my development directory.

This is my package.json entry for bootstrap:

"bootstrap": "^4.0.0-alpha.6"

And this is what I see for my installed packages and meta data:

$ npm list 2>/dev/null | grep bootstrap
├─┬ bootstrap@4.0.0-alpha.6
├─┬ bootstrap-vue@0.16.1
│ ├── bootstrap@4.0.0-alpha.6 deduped

(env) jluc@py$ grep bootstrap package.json package-lock.json
package.json:    "bootstrap": "^4.0.0-alpha.6",
package.json:    "bootstrap-vue": "^0.16.1",
package-lock.json:    "bootstrap": {
package-lock.json:      "version": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.0.0-alpha.6.tgz",
package-lock.json:    "bootstrap-vue": {
package-lock.json:      "version": "https://registry.npmjs.org/bootstrap-vue/-/bootstrap-vue-0.16.1.tgz",
package-lock.json:        "bootstrap": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.0.0-alpha.6.tgz",

Looks good.  Lock is bootstrap-4.0.0-alpha.6.

But how I use actually use that package-lock.json?

Here's what I did:

created a brand new directory

copied in package.json and package-lock.json

ran npm install.

No good.  npm again found bootstrap beta and package-lock.json had no effect, in fact it was rewritten from what npm install did.   Which is consistent with the behavior you want in dev, but doesn't tell me how I would use the lockfile to stabilize my packages.

(env) jluc@trynpmlock$ npm list 2>/dev/null | grep bootstrap
├── bootstrap@4.0.0-beta.2
├─┬ bootstrap-vue@0.16.1
│ ├── bootstrap@4.0.0-beta.2 deduped

(env) jluc@trynpmlock$ grep bootstrap package.json package-lock.json
package.json:    "bootstrap": "^4.0.0-alpha.6",
package.json:    "bootstrap-vue": "^0.16.1",
package-lock.json:    "bootstrap": {
package-lock.json:      "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.0.0-beta.2.tgz",
package-lock.json:    "bootstrap-vue": {
package-lock.json:      "resolved": "https://registry.npmjs.org/bootstrap-vue/-/bootstrap-vue-0.16.1.tgz",
package-lock.json:        "bootstrap": "4.0.0-beta.2",

If I delete the package.json and only have a directory with package-lock.json, then npm install installs very little and leaves me with a truncated package-lock.json

npm install has a --no-package-lock option, but that prevents updating the package-lock.json.

Basically how do I tell npm install everything from package.json, but respect locks in package-lock.json?  Do I use a different command than npm install?  Is it because npm install's doc refers to locks in the context of a package installation, but locks don't apply when you install the package.json in its entirety?

Yes, I know I can specify "bootstrap": "4.0.0-alpha.6", minus the ^, to pin the version manually.

My environment:

(env) jluc@py$ npm -v
5.5.1


来源: stackexchange

问:
Allow read to only accept two lengths
I am trying to add to a script I'm writing a restriction to the input where the user can only input 9 or 10 characters I set it up like this but when I run it, it doesn't work the way I want it to. Everything I type in comes back as 10 characters even if I just put one number. What is wrong with my code?</p>

```<code>#!/bin/bash
#

echo "Please input numbers only"
read inputline
if read -n10 inputline
then
    echo "10 chars"
else
    if read -n9 inputline
    then
    echo "9 chars"
else
    echo "invalid input length"
fi
</code>```

答:
Use the offset Parameter Expansion to truncate whatever they enter to a max of 10 chars like so:</p>

```<code>$ num="123456789012"; echo ${num::10}
1234567890
</code>```

ContentLicense: CC BY-SA 3.0

Title: Allow read to only accept two lengths

Body:
I am trying to add to a script I'm writing a restriction to the input where the user can only input 9 or 10 characters I set it up like this but when I run it, it doesn't work the way I want it to. Everything I type in comes back as 10 characters even if I just put one number. What is wrong with my code?

#!/bin/bash
#

echo "Please input numbers only"
read inputline
if read -n10 inputline
then
    echo "10 chars"
else
    if read -n9 inputline
    then
    echo "9 chars"
else
    echo "invalid input length"
fi

Body:
Use the offset Parameter Expansion to truncate whatever they enter to a max of 10 chars like so:

$ num="123456789012"; echo ${num::10}
1234567890

ContentLicense: CC BY-SA 2.5


问:
Two text strings are showing up as different in Excel, causing a macro to read false
I have two cells in a spreadsheet, A3 and A4. Each has "AHU-2" in it. I copied the A3 content to A4, to make it the same thing.

I have a macro that reads these two cells, and if they are the same, copies a different cell to a different sheet. This macro runs several times right now, to copy several different "Tag Value Category: Tag Value" pairs. Such as CFM: 50, and EAT: 78F.

Right now, the macro reads A3 and A4 as different values, does not select the EAT cell, keeps the last cell (50) copied, and puts that where the EAT value should be in the new sheet.

Anybody know how to fix this?

This is part of my current code.

```<code>Sheets("08-Attribute").Select
Range("I3").Select
Selection.Copy
Sheets("JCX").Select
Range("T2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheets("08-Attribute").Select
Range("K3").Select
Selection.Copy
Sheets("JCX").Select
Range("U2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Sheets("08-Attribute").Select
If ("A3" = "A4") Then Range("I4").Select
Selection.Copy
Sheets("JCX").Select
Range("V2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheets("08-Attribute").Select
If ("A3" = "A4") Then Range("K4").Select
Selection.Copy
Sheets("JCX").Select
Range("W2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
</code>```

答:
It is imperative that you read up on how to avoid Select. Your syntax is also off (If ("A3" = "A4")). Also you can transfer values directly which is rather more efficient than copying and pasting values.</p>

```<code>With Sheets("08-Attribute")
    Sheets("JCX").Range("T2").Value = .Range("I3").Value
    Sheets("JCX").Range("U2").Value = .Range("K3").Value
    If .Range("A3").Value = .Range("A4").Value Then
        Sheets("JCX").Range("V2").Value = .Range("I4").Value
        Sheets("JCX").Range("W2").Value = .Range("K4").Value
    End If
End With
</code>```

Body:
I have two cells in a spreadsheet, A3 and A4. Each has "AHU-2" in it. I copied the A3 content to A4, to make it the same thing.

I have a macro that reads these two cells, and if they are the same, copies a different cell to a different sheet. This macro runs several times right now, to copy several different "Tag Value Category: Tag Value" pairs. Such as CFM: 50, and EAT: 78F.

Right now, the macro reads A3 and A4 as different values, does not select the EAT cell, keeps the last cell (50) copied, and puts that where the EAT value should be in the new sheet.

Anybody know how to fix this?

This is part of my current code.

Sheets("08-Attribute").Select
Range("I3").Select
Selection.Copy
Sheets("JCX").Select
Range("T2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheets("08-Attribute").Select
Range("K3").Select
Selection.Copy
Sheets("JCX").Select
Range("U2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Sheets("08-Attribute").Select
If ("A3" = "A4") Then Range("I4").Select
Selection.Copy
Sheets("JCX").Select
Range("V2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheets("08-Attribute").Select
If ("A3" = "A4") Then Range("K4").Select
Selection.Copy
Sheets("JCX").Select
Range("W2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Body:
It is imperative that you read up on how to avoid Select. Your syntax is also off (If ("A3" = "A4")). Also you can transfer values directly which is rather more efficient than copying and pasting values.

With Sheets("08-Attribute")
    Sheets("JCX").Range("T2").Value = .Range("I3").Value
    Sheets("JCX").Range("U2").Value = .Range("K3").Value
    If .Range("A3").Value = .Range("A4").Value Then
        Sheets("JCX").Range("V2").Value = .Range("I4").Value
        Sheets("JCX").Range("W2").Value = .Range("K4").Value
    End If
End With


问:
Quotes error when passing php string value to javascript onClick
I want to passing variable from php to Javascript. But it can only passing integer type. When I pass value that is not integer, the variable value is undefined.

```<code><?php
$sqlCall="SELECT * FROM table";
$resCall=mysqli_query($con, $sqlCall);
while($row=mysqli_fetch_array($resCall)){
  echo "<tr>";
  echo "<td>".$row[id]."</td>";
  echo "<td>".$row[name]."</td>";
  echo "<a onclick='edit(".$row['id'].",'".$row['name']."')'>Edit</a>"
?>
</code>```

and here is my JavaScript:

```<code><script>
function edit(id, name){
  document.getElementById('edit_id').value = id;
  document.getElementById('edit_name').value = name;
}
</script>
</code>```

答:
The problem comes from the single quotes ' use " instead like :

```<code>"<a onclick='edit(".$row['id'].","".$row['name']."")'>Edit</a>"
</code>```

Body:
I want to passing variable from php to Javascript. But it can only passing integer type. When I pass value that is not integer, the variable value is undefined.

<?php
$sqlCall="SELECT * FROM table";
$resCall=mysqli_query($con, $sqlCall);
while($row=mysqli_fetch_array($resCall)){
  echo "
";
  echo "".$row[id]."	";
  echo "".$row[name]."	";
  echo "Edit"
?>

and here is my JavaScript:

Body:
The problem comes from the single quotes ' use &quot; instead like :

"<a onclick='edit(".$row['id'].",&quot;".$row['name']."&quot;)'>Edit</a>"

ContentLicense: CC BY-SA 4.0


问:
enzyme wrapper.find(..).simulate keypress doesnt trigger event listener
I am trying to press enter on one of the input boxes. Doing it manually triggers the event listener, however, while trying with enzyme, the event listener is not triggered. What am I doing wrong here?

Event Listener

```<code>this.input.addEventListener('keypress', function(event){
            debugger;
            onEnter(event);
        });
</code>```

Enzyme

```<code>function setup(store, props) {
    return mount(<Provider store={store}>
            <component{...props}/>
        </Provider>
    );
}

beforeEach(() => {
        wrapper = setup(store, {});
        searchBar = wrapper.find('searchBar');
        searchInput = searchBar.find("input");
    });

it("when enter is pressed, event should be triggered", ()=> {
            let wait = false;
            runs(()=> {
                searchInput.simulate('change', {target: {value: 'helloWorld'}});
                searchInput.simulate('keyPress', {which: 13});
                setTimeout(()=> {
                    wait = true;
                }, 1000);
            })

            waitsFor(()=> {
                return wait;
            }, "", 1500);
        })
</code>```

答:
I was struggling with this problem too. But now I`ve found a solution.
In addition to { which: 13 } parameter, you need to specify at least key parameter, so your simulate expression will be like:

```<code>searchInput.simulate('keyPress', {
    key: 'Enter',
    keyCode: 13,
    which: 13,
});
</code>```

Body:
I am trying to press enter on one of the input boxes. Doing it manually triggers the event listener, however, while trying with enzyme, the event listener is not triggered. What am I doing wrong here?

Event Listener

this.input.addEventListener('keypress', function(event){
            debugger;
            onEnter(event);
        });

Enzyme

function setup(store, props) {
    return mount(<Provider store={store}>
            <component{...props}/>
        </Provider>
    );
}

beforeEach(() => {
        wrapper = setup(store, {});
        searchBar = wrapper.find('searchBar');
        searchInput = searchBar.find("input");
    });

it("when enter is pressed, event should be triggered", ()=> {
            let wait = false;
            runs(()=> {
                searchInput.simulate('change', {target: {value: 'helloWorld'}});
                searchInput.simulate('keyPress', {which: 13});
                setTimeout(()=> {
                    wait = true;
                }, 1000);
            })

            waitsFor(()=> {
                return wait;
            }, "", 1500);
        })

Body:
I was struggling with this problem too. But now I`ve found a solution.
In addition to { which: 13 } parameter, you need to specify at least key parameter, so your simulate expression will be like:

searchInput.simulate('keyPress', {
    key: 'Enter',
    keyCode: 13,
    which: 13,
});


问:
l[:] performance problem
Recently I was debugging a code like following

```<code>def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])
</code>```

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?

答:
The code that you are showing would run in the 0.1 microseconds that it would take to raise an exception:

```<code>org_list = getList()
list = orgList[:]#this line cause cpu problems.
</code>```

orgList should be org_list. Show the minimal code that actually reproduces the problem.

Also, that kills the list built-in function. Don't do that.

Update Another thought: A common response to "My Django app runs slowly!" is "turn off the debug flag" ... evidently it doesn't free up memory in debug mode.

Update2 about """I found out that when you slice a list. it actually works as a view to that list and just call original list methods to get actual item.""" Where did you get that idea? That can't be the case with a plain old list! Have you redefined list somewhere?

In your getList function:

(1) put in print type(list)

(2) replace result = list() with result = [] and see whether the problem goes away.

Title: l[:] performance problem

Body:
Recently I was debugging a code like following

def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?

Body:
The code that you are showing would run in the 0.1 microseconds that it would take to raise an exception:

org_list = getList()
list = orgList[:]#this line cause cpu problems.

orgList should be org_list. Show the minimal code that actually reproduces the problem.

Also, that kills the list built-in function. Don't do that.

Update Another thought: A common response to "My Django app runs slowly!" is "turn off the debug flag" ... evidently it doesn't free up memory in debug mode.

Update2 about """I found out that when you slice a list. it actually works as a view to that list and just call original list methods to get actual item.""" Where did you get that idea? That can't be the case with a plain old list! Have you redefined list somewhere?

In your getList function:

(1) put in print type(list)

(2) replace result = list() with result = [] and see whether the problem goes away.


问:
Adding Participant to locally hosted application (NetworkAdmin)
I'm facing few issues with 0.16.0 version of composer while deploying the application on local network. Please help me to resolve it.

Steps Followed:

Start Fabric: ./startFabric.sh

Create Composer Profile: ./createComposerProfile.sh

Create Peer Admin Card: ./createPeerAdminCard.sh

Network Deployment: composer network deploy -a perishable-network.bna -A admin -c PeerAdmin@hlfv1 -S adminST

Here I'm not able to add participant

Add Participant: composer add participant add -c PeerAdmin@hlfv1 -d '{"$class":"org.hyperledger.composer.system.NetworkAdmin", "participantId":"Abhilash"}'

Error: Error trying to ping. Error: No business network has been specified for this connection

答:
the solution is a lot simpler than what you've tried. Have a read of the docs here -> https://hyperledger.github.io/composer/reference/composer.network.deploy.html

```<code>composer network deploy -a perishables-network.bna -A admin -S -c PeerAdmin@hlfv1 -f networkAdmin.card
</code>```

Now that you've created the network admin card (.card file) - you can import it to get this into the user's wallet.

```<code>composer card import --file networkAdmin.card
</code>```

Lastly, ping the network - the first time its used, the certificates are retrieved:

```<code>composer network ping -c admin@perishables-network
</code>```

this 'first use' will populate the user's (ie admin user identity) wallet in the .composer card store.

You don't need your step 5.

Body:
the solution is a lot simpler than what you've tried. Have a read of the docs here -> https://hyperledger.github.io/composer/reference/composer.network.deploy.html

composer network deploy -a perishables-network.bna -A admin -S -c PeerAdmin@hlfv1 -f networkAdmin.card

Now that you've created the network admin card (.card file) - you can import it to get this into the user's wallet.

composer card import --file networkAdmin.card

Lastly, ping the network - the first time its used, the certificates are retrieved:

composer network ping -c admin@perishables-network

this 'first use' will populate the user's (ie admin user identity) wallet in the .composer card store.

You don't need your step 5.


问:
Best way to use git when a merger is anticipated
So I have a personal repo, REPO, which I have cloned onto multiple different systems (multiple "local" instances). Let's call these two local repos A and B. On system A, I know that I have uncommitted changes to the repo needing to be committed and pushed. However the system that A is located on is down today for maintenance. I need to do some development, so will use a different system where the local repo B is located.

Knowing that I am about to start development on B, and that unpushed changes are sitting on A, what is the best way to continue? Is this the appropriate scenario in which I should create a branch on B, and merge it to master once I have access to A again?

答: Put your commits wherever anyone who needs them can get them, and will understand their status, and can use them as intended.  Yes, a local branch in your own B repo that won't get pushed to the main repo's master by mistake and can be merged with/rebased on the temporarily-inaccessible commits in A seems fine, there's nothing you can do to mark the A repo while it's offline.</p>


问:
Django Return Two Separate __str__ for a Model Form
I have a Task model that includes tasks and a foreign key to entities:

```<code>class Task(models.Model):
    task = models.CharField(max_length=500)
    entity = models.ForeignKey(Entity)
</code>```

I have a model that is related to one foreign key in Task:

```<code>class Entity(models.Model):
    entity = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    def __str__(self):
        return self.entity
</code>```

Task is placed into a Model Form:

```<code>class TaskForm(ModelForm):
    class Meta:
        model = Task
        fields = [
            'task',
            'entity'
        ]
</code>```

The Model Form is displayed in the template like this:

```<code>{{ form.task }}
{{ form.instance.entity }}
</code>```

How would I include the equivalent of {{ form.instance.type }}? This would involve somehow including two __str__ representations in the same model form. I have seen label_from_instance used in overriding the model form, but this looks like it's only possible with ModelChoiceFields. In addition, it would render the field as a widget rather than text (like form.instance).

答:
Models in Django are just classes. You could also create property for type in Task class.

```<code>class Task(models.Mode):
    ... your code ...

    @property
    def entity_type(self):
        return '{}'.format(self.entity.type)
</code>```

Then you'd call {{ form.instance.entity_type }} in template.

It's a bit of an overkill in this case, but it might be an option in more complex situations.

Body:
I have a Task model that includes tasks and a foreign key to entities:

class Task(models.Model):
    task = models.CharField(max_length=500)
    entity = models.ForeignKey(Entity)

I have a model that is related to one foreign key in Task:

class Entity(models.Model):
    entity = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    def __str__(self):
        return self.entity

Task is placed into a Model Form:

class TaskForm(ModelForm):
    class Meta:
        model = Task
        fields = [
            'task',
            'entity'
        ]

The Model Form is displayed in the template like this:

{{ form.task }}
{{ form.instance.entity }}

How would I include the equivalent of {{ form.instance.type }}? This would involve somehow including two __str__ representations in the same model form. I have seen label_from_instance used in overriding the model form, but this looks like it's only possible with ModelChoiceFields. In addition, it would render the field as a widget rather than text (like form.instance).

Body:
Models in Django are just classes. You could also create property for type in Task class.

class Task(models.Mode):
    ... your code ...

    @property
    def entity_type(self):
        return '{}'.format(self.entity.type)

Then you'd call {{ form.instance.entity_type }} in template.

It's a bit of an overkill in this case, but it might be an option in more complex situations.


问:
Converting custom class object into NSData
I have a custom class that I want to save into NSUserDefaults. I am told that I need to convert the class object into data in order to save it to NSUserDefaults. I found a lot of discrete string or ints to NSData examples but nothing on custom class to NSData. I know very little about the intricacies of NSData encoding etc. Any help is appreciated

EDIT: While I understand there are similar answers here, none of them are in Swift. Translating between the languages is doable, but it is extremely tedious and sometimes very counter-intuitive.

答:
This following sample code is based on Richie Rich's answer (see above) and passes tests in this environment:

Xcode version 9.1 (9B55)

Swift version 4.0.2 (swiftlang-900.0.69.2 clang-900.0.38, Target: x86_64-apple-macosx10.9)

MacBook Air (11-inch, Mid 2012) with macOS High Sierra (version 10.13.1)

```<code>// Foundation is required to NSObject and NSCoding
import Foundation

// A custom class called Person with two properties (a string name and an
// integer age), that is a subclass of NSObject and adopts NSCoding protocol.
class Person: NSObject, NSCoding {
  var name: String!
  var age: Int!

  // The convenience initializer for class Person
  // Reference
  // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID217
  convenience init(name: String, age: Int) {
    // self.init() is the designated initializer for class Person.
    // Reference
    // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID219
    self.init()
    self.name = name
    self.age = age
  }

  // The initializer init(coder:) is required by NSCoding protocol
  // Reference
  // https://developer.apple.com/documentation/foundation/nscoding
  // https://developer.apple.com/documentation/foundation/nscoding/1416145-init
  required convenience init(coder aDecoder: NSCoder) {
    self.init()
    // as! is a type casting operator
    // Reference
    // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID388
    self.name = aDecoder.decodeObject(forKey: "name") as! String
    self.age = aDecoder.decodeInteger(forKey: "age")
  }

  // The instance method encode(with:) is required by NSCoding protocol
  // Reference
  // https://developer.apple.com/documentation/foundation/nscoding
  // https://developer.apple.com/documentation/foundation/nscoding/1413933-encode
  func encode(with anEncoder: NSCoder) {
    if let name = name {
      anEncoder.encode(name, forKey: "name")
    }
    if let age = age {
      anEncoder.encode(age, forKey: "age")
    }
  }
}

// Create an array (or, generally speaking, a collection) as a container to
// hold instances of our custom class type Person.
// Reference
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
var anArrayOfPersons = [Person]()
print(anArrayOfPersons.count) // 0

// Add two instances into anArrayOfPersons.
// Reference
// https://developer.apple.com/documentation/swift/array
// https://developer.apple.com/documentation/swift/array/1538872-append
anArrayOfPersons.append(Person(name: "Cong", age: 33))
anArrayOfPersons.append(Person(name: "Sunny", age: 2))

// Archive anArrayOfPersons into NSData using NSKeyedArchiver.
// Reference
// https://developer.apple.com/documentation/foundation/nskeyedarchiver
// https://developer.apple.com/documentation/foundation/nskeyedarchiver/1413189-archiveddata
let dataToSave = NSKeyedArchiver.archivedData(withRootObject: anArrayOfPersons)

// Persist data. Storing anArrayOfPersons into UserDefaults as data.
// Reference
// https://developer.apple.com/documentation/foundation/userdefaults
// https://developer.apple.com/documentation/foundation/userdefaults/1414067-set
UserDefaults().set(dataToSave, forKey: "tagOfData")

// Take our stored data (in previous step) from UserDefaults using the key
// "personData". Optional binding is used to make sure the retrieved data is
// not nil.
// Reference
// https://developer.apple.com/documentation/foundation/userdefaults
// https://developer.apple.com/documentation/foundation/userdefaults/1409590-data
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID333
if let dataRetrieved = UserDefaults().data(forKey: "tagOfData"),
  // Decode our instance objects from the retrieved data
  // Reference
  // https://developer.apple.com/documentation/foundation/nskeyedunarchiver
  // https://developer.apple.com/documentation/foundation/nskeyedunarchiver/1413894-unarchiveobject
  let anArrayOfPersonsRetrieved = NSKeyedUnarchiver.unarchiveObject(with: dataRetrieved) as? [Person] {
    // See how many bytes the data we retrieved has.
    print(dataRetrieved) // 393 bytes

    // See if the name and age properties are the same as what we stored.
    print(anArrayOfPersonsRetrieved[0].name) // "Cong"
    print(anArrayOfPersonsRetrieved[0].age)  // 45
    print(anArrayOfPersonsRetrieved[1].name) // "Sunny"
    print(anArrayOfPersonsRetrieved[1].age)  // 2
  }
</code>```

Body:
This following sample code is based on Richie Rich's answer (see above) and passes tests in this environment:

Xcode version 9.1 (9B55)

Swift version 4.0.2 (swiftlang-900.0.69.2 clang-900.0.38, Target: x86_64-apple-macosx10.9)

MacBook Air (11-inch, Mid 2012) with macOS High Sierra (version 10.13.1)

// Foundation is required to NSObject and NSCoding
import Foundation

// A custom class called Person with two properties (a string name and an
// integer age), that is a subclass of NSObject and adopts NSCoding protocol.
class Person: NSObject, NSCoding {
  var name: String!
  var age: Int!

  // The convenience initializer for class Person
  // Reference
  // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID217
  convenience init(name: String, age: Int) {
    // self.init() is the designated initializer for class Person.
    // Reference
    // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID219
    self.init()
    self.name = name
    self.age = age
  }

  // The initializer init(coder:) is required by NSCoding protocol
  // Reference
  // https://developer.apple.com/documentation/foundation/nscoding
  // https://developer.apple.com/documentation/foundation/nscoding/1416145-init
  required convenience init(coder aDecoder: NSCoder) {
    self.init()
    // as! is a type casting operator
    // Reference
    // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID388
    self.name = aDecoder.decodeObject(forKey: "name") as! String
    self.age = aDecoder.decodeInteger(forKey: "age")
  }

  // The instance method encode(with:) is required by NSCoding protocol
  // Reference
  // https://developer.apple.com/documentation/foundation/nscoding
  // https://developer.apple.com/documentation/foundation/nscoding/1413933-encode
  func encode(with anEncoder: NSCoder) {
    if let name = name {
      anEncoder.encode(name, forKey: "name")
    }
    if let age = age {
      anEncoder.encode(age, forKey: "age")
    }
  }
}

// Create an array (or, generally speaking, a collection) as a container to
// hold instances of our custom class type Person.
// Reference
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
var anArrayOfPersons = [Person]()
print(anArrayOfPersons.count) // 0

// Add two instances into anArrayOfPersons.
// Reference
// https://developer.apple.com/documentation/swift/array
// https://developer.apple.com/documentation/swift/array/1538872-append
anArrayOfPersons.append(Person(name: "Cong", age: 33))
anArrayOfPersons.append(Person(name: "Sunny", age: 2))

// Archive anArrayOfPersons into NSData using NSKeyedArchiver.
// Reference
// https://developer.apple.com/documentation/foundation/nskeyedarchiver
// https://developer.apple.com/documentation/foundation/nskeyedarchiver/1413189-archiveddata
let dataToSave = NSKeyedArchiver.archivedData(withRootObject: anArrayOfPersons)

// Persist data. Storing anArrayOfPersons into UserDefaults as data.
// Reference
// https://developer.apple.com/documentation/foundation/userdefaults
// https://developer.apple.com/documentation/foundation/userdefaults/1414067-set
UserDefaults().set(dataToSave, forKey: "tagOfData")

// Take our stored data (in previous step) from UserDefaults using the key
// "personData". Optional binding is used to make sure the retrieved data is
// not nil.
// Reference
// https://developer.apple.com/documentation/foundation/userdefaults
// https://developer.apple.com/documentation/foundation/userdefaults/1409590-data
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID333
if let dataRetrieved = UserDefaults().data(forKey: "tagOfData"),
  // Decode our instance objects from the retrieved data
  // Reference
  // https://developer.apple.com/documentation/foundation/nskeyedunarchiver
  // https://developer.apple.com/documentation/foundation/nskeyedunarchiver/1413894-unarchiveobject
  let anArrayOfPersonsRetrieved = NSKeyedUnarchiver.unarchiveObject(with: dataRetrieved) as? [Person] {
    // See how many bytes the data we retrieved has.
    print(dataRetrieved) // 393 bytes

    // See if the name and age properties are the same as what we stored.
    print(anArrayOfPersonsRetrieved[0].name) // "Cong"
    print(anArrayOfPersonsRetrieved[0].age)  // 45
    print(anArrayOfPersonsRetrieved[1].name) // "Sunny"
    print(anArrayOfPersonsRetrieved[1].age)  // 2
  }


问:
The package name of your Instant App APKs should be the same as your app's package name
I'm trying to upload my instant app t play store. I see the below error which uploading instant app apk zip:

The package name of your Instant App APKs should be the same as your app's package name

My build.gradles for respective features as below:

Installed apk (build.gradle) :

```<code>apply plugin: 'com.android.application'

 android {
compileSdkVersion 26
buildToolsVersion "27.0.1"

defaultConfig {
    applicationId "arith.math.arithapk"
    minSdkVersion 23
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

 dependencies {
implementation project(':arithbase')
implementation project(":arithmaticsumfeature")
 }
</code>```

base (build.gradle):

```<code>  //apply plugin: 'com.android.application'
 apply plugin: 'com.android.feature'

 android {
compileSdkVersion 26
buildToolsVersion "27.0.1"
baseFeature = true
defaultConfig {
    minSdkVersion 23
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
    "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
      }

  dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-
 core:3.0.1', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:appcompat-v7:26.1.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:26.1.0'
feature project(":arithmaticsumfeature")
api 'com.android.support:appcompat-v7:26.1.0'
   application project(':arithapk')
}
</code>```

Feature(build.gradle):

```<code>     apply plugin: 'com.android.feature'

      android {
compileSdkVersion 26
buildToolsVersion "27.0.1"

defaultConfig {
    minSdkVersion 23
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
  }

   dependencies {
api project(':arithbase')
    }
</code>```

Instant app (build.gradle):

```<code>          apply plugin: 'com.android.instantapp'

  dependencies {
implementation project(':arithbase')
implementation project(":arithmaticsumfeature")
   }
</code>```

Can any one help me in resolving this issue. ?

Thanks in Advance

答: updated base (build.gradle) with application project(':arithapk') and issue is  fixed</p>

Body:
I'm trying to upload my instant app t play store. I see the below error which uploading instant app apk zip:

The package name of your Instant App APKs should be the same as your app's package name

My build.gradles for respective features as below:

Installed apk (build.gradle) :

apply plugin: 'com.android.application'

 android {
compileSdkVersion 26
buildToolsVersion "27.0.1"

defaultConfig {
    applicationId "arith.math.arithapk"
    minSdkVersion 23
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

 dependencies {
implementation project(':arithbase')
implementation project(":arithmaticsumfeature")
 }

base (build.gradle):

  //apply plugin: 'com.android.application'
 apply plugin: 'com.android.feature'

 android {
compileSdkVersion 26
buildToolsVersion "27.0.1"
baseFeature = true
defaultConfig {
    minSdkVersion 23
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
    "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
      }

  dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-
 core:3.0.1', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:appcompat-v7:26.1.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:26.1.0'
feature project(":arithmaticsumfeature")
api 'com.android.support:appcompat-v7:26.1.0'
   application project(':arithapk')
}

Feature(build.gradle):

     apply plugin: 'com.android.feature'

      android {
compileSdkVersion 26
buildToolsVersion "27.0.1"

defaultConfig {
    minSdkVersion 23
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
  }

   dependencies {
api project(':arithbase')
    }

Instant app (build.gradle):

          apply plugin: 'com.android.instantapp'

  dependencies {
implementation project(':arithbase')
implementation project(":arithmaticsumfeature")
   }

Can any one help me in resolving this issue. ?

Thanks in Advance


问:
"Creating precompiled collator because collator is out of date"
I am trying to "self-destruct" a view controller by doing [[self navigationController] popViewControllerAnimated:YES].

Before I do this, I also present an UIAlertView.

The first time I do this, I get a console-error that says:

WARNING! Creating precompiled collator because collator is out of date. This is expensive!

What does that mean? How can I fix it?

Thank you.

答: This was simply due to a framework-error in the iOS 4.2.1 beta. I'm not getting this error anymore.</p>


问:
Ruby on Docker: determining which image I need
I've got a Sinatra app and I want to start doing development and production in Docker.  Seeing blogs like this: https://blog.codeship.com/build-minimal-docker-container-ruby-apps/ which advocate using slimmed-down Alpine image.  I understand the value of having a smaller image, however in my research on this subject I can't find a clear explanation on exactly how to know whether I will need, now or in the future, the full docker ruby image? Do I start with Alpine for dev and prod, and then assume that if I later need the bigger image, I'll switch to that?  What would be an example of the kind of new requirement that could come up that would require the larger docker ruby image?  thanks</p>

答: Decided to use alpine and see where it leads based upon the response.  </p>


问:
gRPC context on the client side
I am building a client/server system in go, using gRPC and protobuf (and with a gRPC gateway to REST).

I use metadata in the context on the server side to carry authentication data from the client, and that works perfectly well.

Now, I'd like the server to set some metadata keys/values so that the client can get them, alongside with the response. How can I do that? Using SetHeader and SendHeader? Ideally, I'd like every single response from the server to integrate that metadata (can be seen as some kind of UnaryInterceptor, but on the response rather than the request?)

Here is the code for the server and for the client.

答:
I finally found my way: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md

So basically, grpc.SetHeader() + grpc.SendHeader() and grpc.SetTrailer() are totally what I was looking for. On the client side, grpc.Header() and grpc.Trailer() functions need to be passed to the RPC call, and their argument is a metadata.MD object to be filled.

On the client side, define your receiving metadata:

```<code>var header, trailer metadata.MD
</code>```

Then, pass it to the SomeRPCCall() unary RPC:

```<code>response, err := client.SomeRPCCall(
    context.Background(),
    proto.MyMessage{},
    grpc.Header(&header),
    grpc.Trailer(&trailer),
)
</code>```

And now, you can check what's in your metadata:

```<code>for key, value := range header {
    fmt.Printf("%s => %s", key, value)
}

for key, value := range trailer {
    fmt.Printf("%s => %s", key, value)
}
</code>```

On the server side, you can:

force the data to be sent right after the RPC is received (but before it's processed):

grpc.SendHeader(ctx, metadata.New(map[string]string{"my-key": "my-value"}))

or set & send the metadata at the end of the RPC process (along with the Status):

grpc.SetTrailer(ctx, metadata.New(map[string]string{"my-key": "my-value"}))

Title: gRPC context on the client side

Body:
I finally found my way: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md

So basically, grpc.SetHeader() + grpc.SendHeader() and grpc.SetTrailer() are totally what I was looking for. On the client side, grpc.Header() and grpc.Trailer() functions need to be passed to the RPC call, and their argument is a metadata.MD object to be filled.

On the client side, define your receiving metadata:

var header, trailer metadata.MD

Then, pass it to the SomeRPCCall() unary RPC:

response, err := client.SomeRPCCall(
    context.Background(),
    proto.MyMessage{},
    grpc.Header(&header),
    grpc.Trailer(&trailer),
)

And now, you can check what's in your metadata:

for key, value := range header {
    fmt.Printf("%s => %s", key, value)
}

for key, value := range trailer {
    fmt.Printf("%s => %s", key, value)
}

On the server side, you can:

force the data to be sent right after the RPC is received (but before it's processed):

grpc.SendHeader(ctx, metadata.New(map[string]string{"my-key": "my-value"}))

or set & send the metadata at the end of the RPC process (along with the Status):

grpc.SetTrailer(ctx, metadata.New(map[string]string{"my-key": "my-value"}))


问:
How autocomplete fill another form input
I need to know how to fill another input in other forms in the same page  when the autocomplete fill the values in the first form.

Like per example, if I have three form in the same page and I need to fill the id adquired in the autocomplete value in the first form to populate in the other two, how can I do it?

Here the example code:

```<code>//First form, in the license input the autocomplete fill the license, owner, brand and the id
<form method="post" name="first" id="first" class="form-horizontal">
    <div class="row form-group">
        <label class="col-sm-3 text-right">Car license number:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" name="license"  id="license"> //  autocomplete input
        </div>
    </div>
    <div class="row form-group">
        <label class="col-sm-3 text-right">Owner:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" name="owner"  id="owner">
        </div>
    </div>
    <div class="row form-group">
        <label class="col-sm-3 text-right">Brand:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" name="brand"  id="brand">
        </div>
    </div>
    <input type="hidden" id="idCar" name="idCar" />  // hidden input needed in the other forms
    <input type="submit" id="sCar" class="btn btn-info" value="Save Car" />
</form>

//Second form
<form method="post" name="second" id="second" class="form-horizontal">
    <div class="row form-group">
        <label class="col-sm-3 text-right">Requested work:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" name="reWork"  id="reWork">
        </div>
    </div>
    <div class="row form-group">
        <label class="col-sm-3 text-right">How many miles in this diagnosis have the car:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" name="miles"  id="miles">
        </div>
    </div>
    <div class="row form-group">
        <label class="col-sm-3 text-right">Type of oil used:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" name="oil"  id="oil">
        </div>
    </div>
    <input type="hidden" id="idCar" name="idCar" />  // Hidden input needed to fill previously in the first form
    <input type="submit" id="sDiag" class="btn btn-info" value="Save diagnosis" />
</form>
</code>```

And so on... the page have five form for make the diagnosis and revision of each car.. when the user hit the submit button with ajax the form is submited. My problem is how the add the same id in the others form when the autocomplete fill the values in the first form.

答:
Something like this?

```<code>$("#first [name='license']").on("change keyup",function(){
            $("#first [name='idCar']").val("123").trigger("change"); // i just make this like some autocomplete example
});

$("#first [name='idCar']").on("change",function(){
        var val = $(this).val();
            $("[name='idCar']").not(this).val(val);
});
</code>```

jsfiddle : https://jsfiddle.net/synz/cc958dp4/

Body:
I need to know how to fill another input in other forms in the same page  when the autocomplete fill the values in the first form.

Like per example, if I have three form in the same page and I need to fill the id adquired in the autocomplete value in the first form to populate in the other two, how can I do it?

Here the example code:

//First form, in the license input the autocomplete fill the license, owner, brand and the id
<form method="post" name="first" id="first" class="form-horizontal">

        Car license number:

            <input type="text" class="form-control" name="license"  id="license"> //  autocomplete input

        Owner:

            <input type="text" class="form-control" name="owner"  id="owner">

        Brand:

            <input type="text" class="form-control" name="brand"  id="brand">

    <input type="hidden" id="idCar" name="idCar" />  // hidden input needed in the other forms
    <input type="submit" id="sCar" class="btn btn-info" value="Save Car" />
</form>

//Second form
<form method="post" name="second" id="second" class="form-horizontal">

        Requested work:

            <input type="text" class="form-control" name="reWork"  id="reWork">

        How many miles in this diagnosis have the car:

            <input type="text" class="form-control" name="miles"  id="miles">

        Type of oil used:

            <input type="text" class="form-control" name="oil"  id="oil">

    <input type="hidden" id="idCar" name="idCar" />  // Hidden input needed to fill previously in the first form
    <input type="submit" id="sDiag" class="btn btn-info" value="Save diagnosis" />
</form>

And so on... the page have five form for make the diagnosis and revision of each car.. when the user hit the submit button with ajax the form is submited. My problem is how the add the same id in the others form when the autocomplete fill the values in the first form.

Body:
Something like this?

$("#first [name='license']").on("change keyup",function(){
            $("#first [name='idCar']").val("123").trigger("change"); // i just make this like some autocomplete example
});

$("#first [name='idCar']").on("change",function(){
        var val = $(this).val();
            $("[name='idCar']").not(this).val(val);
});

jsfiddle : https://jsfiddle.net/synz/cc958dp4/


问:
Resolve relative relocations in partial link
I've noticed that using -r to do a partial link doesn't actually resolve any relocations, it seems, even if they could be resolved via relative addressing. For example, consider f.o and g.o, with f.o containing f() which calls g() within g.o. Before linking, the disassembly and relocations are as expected. After partial linking to a new file h.o (via ld -r -o h.o f.o g.o), however, there is still a relocation for the call to g(), even though in theory it could have been resolved with a relative address.

Here is the disassembly of h.o (objdump -d h.o), containing f() and g(). You can see that the call to g() is still unresolved:

```<code>h.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <f>:
   0:       55                      push   %rbp
   1:       48 89 e5                mov    %rsp,%rbp
   4:       e8 00 00 00 00          callq  9 <f+0x9>
   9:       90                      nop
   a:       5d                      pop    %rbp
   b:       c3                      retq

000000000000000c <g>:
   c:       55                      push   %rbp
   d:       48 89 e5                mov    %rsp,%rbp
  10:       90                      nop
  11:       5d                      pop    %rbp
  12:       c3                      retq
</code>```

Here is the relocation table of h.o (objdump -r h.o):

```<code>h.o:     file format elf64-x86-64

RELOCATION RECORDS FOR [.text]:
OFFSET           TYPE              VALUE
0000000000000005 R_X86_64_PC32     g-0x0000000000000004

RELOCATION RECORDS FOR [.eh_frame]:
OFFSET           TYPE              VALUE
0000000000000020 R_X86_64_PC32     .text
0000000000000058 R_X86_64_PC32     .text+0x000000000000000c
</code>```

So, just wondering whether or not there was any way to force the relocation to be performed via a relative address during a partial link. I tried compiling the code with -fpic, but that still did not cause the relocation to be performed during the partial link.

Note that I have no goal, application, or reason for this. Just exploring the functionality and capabilities of ld.

答:
Per this reference it looks like the reason that the relative symbols are not resolved is to give the linked more flexibility. If we wanted to instead resolve the symbol g to a different address, we would need to change those jumps in the code.

However, if you change your symbol g to be static, then the linker will resolve the jumps. In that case, the symbol is no longer exported and thus not manipulable by future linker calls.

Body:
I've noticed that using -r to do a partial link doesn't actually resolve any relocations, it seems, even if they could be resolved via relative addressing. For example, consider f.o and g.o, with f.o containing f() which calls g() within g.o. Before linking, the disassembly and relocations are as expected. After partial linking to a new file h.o (via ld -r -o h.o f.o g.o), however, there is still a relocation for the call to g(), even though in theory it could have been resolved with a relative address.

Here is the disassembly of h.o (objdump -d h.o), containing f() and g(). You can see that the call to g() is still unresolved:

h.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <f>:
   0:       55                      push   %rbp
   1:       48 89 e5                mov    %rsp,%rbp
   4:       e8 00 00 00 00          callq  9 <f+0x9>
   9:       90                      nop
   a:       5d                      pop    %rbp
   b:       c3                      retq

000000000000000c <g>:
   c:       55                      push   %rbp
   d:       48 89 e5                mov    %rsp,%rbp
  10:       90                      nop
  11:       5d                      pop    %rbp
  12:       c3                      retq

Here is the relocation table of h.o (objdump -r h.o):

h.o:     file format elf64-x86-64

RELOCATION RECORDS FOR [.text]:
OFFSET           TYPE              VALUE
0000000000000005 R_X86_64_PC32     g-0x0000000000000004

RELOCATION RECORDS FOR [.eh_frame]:
OFFSET           TYPE              VALUE
0000000000000020 R_X86_64_PC32     .text
0000000000000058 R_X86_64_PC32     .text+0x000000000000000c

So, just wondering whether or not there was any way to force the relocation to be performed via a relative address during a partial link. I tried compiling the code with -fpic, but that still did not cause the relocation to be performed during the partial link.

Note that I have no goal, application, or reason for this. Just exploring the functionality and capabilities of ld.


问:
Fill 2D vector in C++
I'm trying to fill 2D vector in C++ with characters, but when I run this code it ends with one line characters (*..).

How can I fill 2D vector like this:

*.*
.**

```<code>#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<char> > vec2D;
    std::vector<char> rowV;

    unsigned int row=2;
    unsigned int col=3;

    char c;
    unsigned int temp=0;

    while(temp!=col)
    {
        while(rowV.size()!=row)
        {
            std::cin>>c;
            rowV.push_back(c);
        }
        vec2D.push_back(rowV);
        ++temp;
    }

    return 0;
}
</code>```

答:
You should clear rowV after each insertion, otherwise it will be full and no other characters will be added. Also, row should be swapped by col and vice-versa, otherwise you will get a 3x2 (and not 2x3) 2D vector.

```<code>while(temp!=row)
{
    while(rowV.size()!=col)
    {
        std::cin>>c;
        rowV.push_back(c);
    }
    vec2D.push_back(rowV);
    rowV.clear(); // clear after inserting
    ++temp;
}
</code>```

Title: Fill 2D vector in C++

Body:
I'm trying to fill 2D vector in C++ with characters, but when I run this code it ends with one line characters (*..).

How can I fill 2D vector like this:

*.*
.**

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<char> > vec2D;
    std::vector<char> rowV;

    unsigned int row=2;
    unsigned int col=3;

    char c;
    unsigned int temp=0;

    while(temp!=col)
    {
        while(rowV.size()!=row)
        {
            std::cin>>c;
            rowV.push_back(c);
        }
        vec2D.push_back(rowV);
        ++temp;
    }

    return 0;
}

Body:
You should clear rowV after each insertion, otherwise it will be full and no other characters will be added. Also, row should be swapped by col and vice-versa, otherwise you will get a 3x2 (and not 2x3) 2D vector.

while(temp!=row)
{
    while(rowV.size()!=col)
    {
        std::cin>>c;
        rowV.push_back(c);
    }
    vec2D.push_back(rowV);
    rowV.clear(); // clear after inserting
    ++temp;
}


问:
Java Is there a feature for replacing placeholders inside a String with a String variable
I have a requirement to move all the hard-coded error logs to DB. Some of the error logs comes in the format

```<code>"xxxxx" + variable + "xxxxxx";
</code>```

It is  not possible to change the structure of the table. Neither can I do some String insert based on the position since the values in the DB can always change.

Is there a feature in any Java libraries or third party ones where you can have placeholders in the String value and they get replaced by variables.
To quote an example, we could think of the good old

```<code>printf("bla %s %d bla,", var, var2);
</code>```

or the SQL PreparedStatement class

```<code>stmt("select * from blah where a = ?");
</code>```

And the '?' gets replaced by a variable content.

Any suggestions would be of great help.

答:
You can use MessageFormat like this :</p>

```<code>String log = "xxxxx [{0}] xxxxxx";
String variable = "some_string";
String result = MessageFormat.format(log, variable);
</code>```

Body:
I have a requirement to move all the hard-coded error logs to DB. Some of the error logs comes in the format

"xxxxx" + variable + "xxxxxx";

It is  not possible to change the structure of the table. Neither can I do some String insert based on the position since the values in the DB can always change.

Is there a feature in any Java libraries or third party ones where you can have placeholders in the String value and they get replaced by variables.
To quote an example, we could think of the good old

printf("bla %s %d bla,", var, var2);

or the SQL PreparedStatement class

stmt("select * from blah where a = ?");

And the '?' gets replaced by a variable content.

Any suggestions would be of great help.

Body:
You can use MessageFormat like this :

String log = "xxxxx [{0}] xxxxxx";
String variable = "some_string";
String result = MessageFormat.format(log, variable);


问:
How to use two different params hashes in one page (Rails)
Hi
I want to use two params hashes in one page

The job of this page is straightforward, it's an edit page, and I want it to send out notifications to a server once the editing job is done.

```<code>def update
      @description = Tempdescription.find(params[:id])
     @description.update_attributes(params[:tempdescription])
      sendnotification
end

def sendnotification
       params[:to_ids]="xxxx"
       sig = hash_params(params);
       params[:sig] = sig
     response = RestClient.post "http://api.xxxx.com/restserver.do",  params, :content_type => :json, :accept => :json
       render :text=>response
end

def hash_params(params)
      params = Hash[*params.sort.flatten]
    payload = ''
    params.sort.each do |pair|
         key, value = pair
     payload = payload + "#{key}=#{value}"
    end
    return Digest::MD5.hexdigest(payload + API_SECRET)
 end
</code>```

Not surprisingly the params in sendnotification also includes params used for updating

and the server returns 104 error

Therefore,
I tried

```<code>new_params=Hash[]
</code>```

and use new_params to replace the old params in sendnotification

But then rails complains

```<code> undefined method `<=>' for :session_key:Symbol
 app/controllers/tempdescriptions_controller.rb:72:in `<=>'
  app/controllers/tempdescriptions_controller.rb:72:in `sort'
  app/controllers/tempdescriptions_controller.rb:72:in `hash_params'
  app/controllers/tempdescriptions_controller.rb:45:in `sendnotification'
</code>```

So I am thinking if there is any way I can create another params?

Thanks in advance

答:
Ok...after playing with rails console for a while I finally find a solution to this problem.

In sendnotification method I created a new hash

```<code>    p=Hash[]
</code>```

but simply putting this will not work, as I mentioned before.
Then I changed all
      p[:key]
    to
      p["key"]
and it works.

Obviously Hash#sort doesn't work with hash[:key] if the hash is newly created but it works with params and that's what puzzled me and made me believe there is a difference between params and normal hash.

I am using Ruby 1.8.7 so I think it might just be a bug of this version.

Body:
Hi
I want to use two params hashes in one page

The job of this page is straightforward, it's an edit page, and I want it to send out notifications to a server once the editing job is done.

def update
      @description = Tempdescription.find(params[:id])
     @description.update_attributes(params[:tempdescription])
      sendnotification
end

def sendnotification
       params[:to_ids]="xxxx"
       sig = hash_params(params);
       params[:sig] = sig
     response = RestClient.post "http://api.xxxx.com/restserver.do",  params, :content_type => :json, :accept => :json
       render :text=>response
end

def hash_params(params)
      params = Hash[*params.sort.flatten]
    payload = ''
    params.sort.each do |pair|
         key, value = pair
     payload = payload + "#{key}=#{value}"
    end
    return Digest::MD5.hexdigest(payload + API_SECRET)
 end

Not surprisingly the params in sendnotification also includes params used for updating

and the server returns 104 error

Therefore,
I tried

new_params=Hash[]

and use new_params to replace the old params in sendnotification

But then rails complains

 undefined method `<=>' for :session_key:Symbol
 app/controllers/tempdescriptions_controller.rb:72:in `<=>'
  app/controllers/tempdescriptions_controller.rb:72:in `sort'
  app/controllers/tempdescriptions_controller.rb:72:in `hash_params'
  app/controllers/tempdescriptions_controller.rb:45:in `sendnotification'

So I am thinking if there is any way I can create another params?

Thanks in advance

Body:
Ok...after playing with rails console for a while I finally find a solution to this problem.

In sendnotification method I created a new hash

    p=Hash[]

but simply putting this will not work, as I mentioned before.
Then I changed all
      p[:key]
    to
      p["key"]
and it works.

Obviously Hash#sort doesn't work with hash[:key] if the hash is newly created but it works with params and that's what puzzled me and made me believe there is a difference between params and normal hash.

I am using Ruby 1.8.7 so I think it might just be a bug of this version.


问:
Complex SQL query with where and where not in
I have 3 tables (candidates, candidate_notes and candidate_events)

```<code>CANDIDATES  | CANDIDATE_NOTES       | CANDIDATE_EVENTS
id          | id                    | id
name        | candidate_event_id    | type
surname     | candidate_id
city        | note
...
</code>```

One candidate can have many notes.

One note has one kind of event.

I would like to obtain all the candidates that have notes of kind of event 1 but only that.

For example, if the candidate 1 have 5 notes, one of type 1, other 3 of type 3 and another one of type 6, I don't want to see it in the results.

Can someone help me with this query?
Thanks

答:
One method uses group by and having:

```<code>select cn.candidate_id
from candidate_notes cn join
     candidate_events e
     on cn.candidate_event_id = e.candidate_event_id
group by cn.candidate_id
having min(type) = 1 and min(type) = max(type);
</code>```

Body:
I have 3 tables (candidates, candidate_notes and candidate_events)

CANDIDATES  | CANDIDATE_NOTES       | CANDIDATE_EVENTS
id          | id                    | id
name        | candidate_event_id    | type
surname     | candidate_id
city        | note
...

One candidate can have many notes.

One note has one kind of event.

I would like to obtain all the candidates that have notes of kind of event 1 but only that.

For example, if the candidate 1 have 5 notes, one of type 1, other 3 of type 3 and another one of type 6, I don't want to see it in the results.

Can someone help me with this query?
Thanks

Body:
One method uses group by and having:

select cn.candidate_id
from candidate_notes cn join
     candidate_events e
     on cn.candidate_event_id = e.candidate_event_id
group by cn.candidate_id
having min(type) = 1 and min(type) = max(type);


问:
Execute Curl from Java
I am trying to execute the following curl command from Java, but the answer I get is incorrect, since it always returns the status 401.

```<code>curl -k -v -u "admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI" -d "{"username":"test","token_code":"246212"}" -H "Content-Type: application/json" https://192.168.101.59/api/v1/auth/
</code>```

I am sending correctly the user "admin2" with his password for the authentication. I think the problem is the use of character (") in my code.

```<code>String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
                "-d", "{\"username\":\"test\",\"token_code\":\"246212\"}","-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);

String curlResult = "";
String line = "";

try {
    Process process = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while (true) {
        line = r.readLine();
        if (line == null) {
            break;
        }
        curlResult = curlResult + line;
    }
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

答:
In 'command', try removing the single quotes from

```<code>"'admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI'"
</code>```

so that it becomes

```<code>"admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI"
</code>```

and see if that helps. It might be considering them as part of the actual username and password.

I think the issue is the Json in this case and I think you are right then that the double quotes are the issue. Try putting the Json in a file and use curl to send the file contents as the body of your message.

```<code>String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
            "-d", "@/path/to/filename.json", "-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};
</code>```

Title: Execute Curl from Java

Body:
I am trying to execute the following curl command from Java, but the answer I get is incorrect, since it always returns the status 401.

curl -k -v -u "admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI" -d "{"username":"test","token_code":"246212"}" -H "Content-Type: application/json" https://192.168.101.59/api/v1/auth/

I am sending correctly the user "admin2" with his password for the authentication. I think the problem is the use of character (") in my code.

String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
                "-d", "{\"username\":\"test\",\"token_code\":\"246212\"}","-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);

String curlResult = "";
String line = "";

try {
    Process process = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while (true) {
        line = r.readLine();
        if (line == null) {
            break;
        }
        curlResult = curlResult + line;
    }
} catch (Exception e) {
    e.printStackTrace();
}

Body:
In 'command', try removing the single quotes from

"'admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI'"

so that it becomes

"admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI"

and see if that helps. It might be considering them as part of the actual username and password.

I think the issue is the Json in this case and I think you are right then that the double quotes are the issue. Try putting the Json in a file and use curl to send the file contents as the body of your message.

String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
            "-d", "@/path/to/filename.json", "-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};


问:
SCons problem - dont understand Variables class
I'm working on an SConstruct build file for a project and I'm trying to update from Options to Variables, since Options is being deprecated. I don't understand how to use Variables though. I have 0 python experience which is probably contributing to this.

For example, I have this:

```<code>opts = Variables()
opts.Add('fcgi',0)
print opts['fcgi']
</code>```

But I get an error:

```<code>AttributeError: Variables instance has no attribute '__getitem__':
</code>```

Not sure how this is supposed to work

答:
That specific error tells you that class Variables hasn't implemented python's __getitem__ interface which would allow you to use [ ...] on  opts.  If all you want to do is print out your keys, the Variables documentation seems to indicate that you can iterate over your keys:

```<code>for key in opts.keys():
    print key
</code>```

Or you can print out the help text:

```<code>print opts.GenerateHelpText()
</code>```

OwnerDisplayName: Geuis

Body:
I'm working on an SConstruct build file for a project and I'm trying to update from Options to Variables, since Options is being deprecated. I don't understand how to use Variables though. I have 0 python experience which is probably contributing to this.

For example, I have this:

opts = Variables()
opts.Add('fcgi',0)
print opts['fcgi']

But I get an error:

AttributeError: Variables instance has no attribute '__getitem__':

Not sure how this is supposed to work

LastEditorDisplayName: Eli Courtwright

Body:
That specific error tells you that class Variables hasn't implemented python's __getitem__ interface which would allow you to use [ ...] on  opts.  If all you want to do is print out your keys, the Variables documentation seems to indicate that you can iterate over your keys:

for key in opts.keys():
    print key

Or you can print out the help text:

print opts.GenerateHelpText()

OwnerDisplayName: funkyworklehead


问:
How to host site with ASPNETDB.MDF database from Development Server to Production Server?
I have created my site using ASP.NET Personal Starter Kits 3.5. I use Visual Studio 2008 only . .with its built-in SQL Server (2005 Express) ... my database in App_Data is ASPNETDB.MDF ...

I have created some of my tables also ....in ASPNETDB ..

In my local PC the site was running fine ...

But when I publish my site on production server it doesn't work and shows the following error

```<code><!-- Web.Config Configuration File -->
<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>
</code>```

Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's  configuration tag to point to a custom error page URL.

```<code><!-- Web.Config Configuration File -->
<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration>
</code>```

My hosting provider connection string ..

```<code><add name="ConnectionString" connectionString="Data Source=69.16.253.19;Initial Catalog=usa_data;Persist Security Info=True;User Id=user;Password=pass" providerName="System.Data.SqlClient"/>
</code>```

My hosting provider gave me the connection string to connect to the SQL Server 2005 but it doesn't work...

I don't understand why my site was running fine using the production SQL Server 2005 in my local PC when I include ASPNETDB.MDF file in App_Data in my local pc only ..if I remove file ASPNETDB.MDF from App_Data of my local pc ... the site stops working ...

Can anybody tell em how to fix this ... !! I am very tensed since last 3-4 days

答:
Firstly, the file in the APP_DATA folder is not accessible as a DB in production.
You will have to migrate the whole Database from the  ASPNETDB.MDF to the Production Database server (given by provider.)
And then the site will work.
Also, change the config to :   to see the exact error!!

If the porting doesn't work, see the exact error and post it here.

Body:
I have created my site using ASP.NET Personal Starter Kits 3.5. I use Visual Studio 2008 only . .with its built-in SQL Server (2005 Express) ... my database in App_Data is ASPNETDB.MDF ...

I have created some of my tables also ....in ASPNETDB ..

In my local PC the site was running fine ...

But when I publish my site on production server it doesn't work and shows the following error

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's  configuration tag to point to a custom error page URL.

<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration>

My hosting provider connection string ..

<add name="ConnectionString" connectionString="Data Source=69.16.253.19;Initial Catalog=usa_data;Persist Security Info=True;User Id=user;Password=pass" providerName="System.Data.SqlClient"/>

My hosting provider gave me the connection string to connect to the SQL Server 2005 but it doesn't work...

I don't understand why my site was running fine using the production SQL Server 2005 in my local PC when I include ASPNETDB.MDF file in App_Data in my local pc only ..if I remove file ASPNETDB.MDF from App_Data of my local pc ... the site stops working ...

Can anybody tell em how to fix this ... !! I am very tensed since last 3-4 days


问:
VBA code executes with message box, but not without
I have a Sub in VBA that I need to be able to run multiple times. When I execute this piece of code to find the last row of the sheet:

```<code>Dim lastRow As Long
With ActiveSheet
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With
</code>```

I get

object variable or with block variable not set

when I execute it a second time, but if I add a message box before the variable set:

```<code>Dim lastRow As Long
With ActiveSheet
MsgBox xlWs.Cells(.Rows.count, "A").End(xlUp).Row
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With
</code>```

It works no matter how many times I run it. Has anyone run into this issue before? What is wrong with the first set of code, that is corrected with the second set?

答:
You are using xlWs as a worksheet object inside the block of code that you are defining lastrow and I cannot see where you have defined it prior to calling it and that is why you get an error. If by any chance you have set that object in prior code executions it and somehow that worksheet is active you will not get any error message. We just don't have more information on what the other parameters are when you are running the code or how you are running it, but the best question for you here is how to follow a clean and standard definition of objects and using them inside a good code line. I would write a function for last row and make the worksheet and column number optional:

```<code>Function LastRowInColumn(Optional sh As Worksheet, Optional colNumber As Long = 1) As Long
    'Finds the last row in a particular column which has a value in it
    If sh Is Nothing Then
        Set sh = ActiveSheet
    End If
    LastRowInColumn = sh.Cells(sh.Rows.Count, colNumber).End(xlUp).row
End Function
</code>```

This function will manage setting the proper sheet for you, if you enter the sheet object it will use it, if not then it will use the active sheet. The same goes for the column you want to define the last row, if you enter any column number (e.g. colNumber=3 will be column C) it will find the last row in that column, if you leave it blank, it will consider column A.

Body:
I have a Sub in VBA that I need to be able to run multiple times. When I execute this piece of code to find the last row of the sheet:

Dim lastRow As Long
With ActiveSheet
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With

I get

object variable or with block variable not set

when I execute it a second time, but if I add a message box before the variable set:

Dim lastRow As Long
With ActiveSheet
MsgBox xlWs.Cells(.Rows.count, "A").End(xlUp).Row
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With

It works no matter how many times I run it. Has anyone run into this issue before? What is wrong with the first set of code, that is corrected with the second set?

Body:
You are using xlWs as a worksheet object inside the block of code that you are defining lastrow and I cannot see where you have defined it prior to calling it and that is why you get an error. If by any chance you have set that object in prior code executions it and somehow that worksheet is active you will not get any error message. We just don't have more information on what the other parameters are when you are running the code or how you are running it, but the best question for you here is how to follow a clean and standard definition of objects and using them inside a good code line. I would write a function for last row and make the worksheet and column number optional:

Function LastRowInColumn(Optional sh As Worksheet, Optional colNumber As Long = 1) As Long
    'Finds the last row in a particular column which has a value in it
    If sh Is Nothing Then
        Set sh = ActiveSheet
    End If
    LastRowInColumn = sh.Cells(sh.Rows.Count, colNumber).End(xlUp).row
End Function

This function will manage setting the proper sheet for you, if you enter the sheet object it will use it, if not then it will use the active sheet. The same goes for the column you want to define the last row, if you enter any column number (e.g. colNumber=3 will be column C) it will find the last row in that column, if you leave it blank, it will consider column A.


问:
With Nix, how can I specify Haskell dependencies with profiling enabled?
I was trying like this initially:

```<code>nix-shell -p "haskell.packages.ghc821.ghcWithPackages (p: with p; [text hspec lens])" -j4 --run 'ghc Main.hs -prof
</code>```

Then GHC told me

```<code>Main.hs:4:1: error:
    Could not find module ‘Control.Lens’
    Perhaps you haven't installed the profiling libraries for package ‘lens-4.15.4’?
    Use -v to see a list of the files searched for.
</code>```

Searching around the web I found this: https://github.com/NixOS/nixpkgs/issues/22340

So it seems I won't be able to download from the cache. But that's okay, if at least I can build the profiled variants locally.

Can I do that somehow simply by modifying the nix expression given to -p slightly?

Then at this point in writing this question, I remembered this resource: https://github.com/NixOS/nixpkgs/blob/bd6ba7/pkgs/development/haskell-modules/lib.nix

Where I found enableLibraryProfiling. So I tried:

```<code>nix-shell -p "haskell.packages.ghc821.ghcWithPackages (p: with p; [text hspec (haskell.lib.enableLibraryProfiling lens)])" -j4 --run 'ghc Main.hs -prof'
</code>```

Which got me to a new error:

```<code>src/Control/Lens/Internal/Getter.hs:26:1: error:
    Could not find module ‘Data.Functor.Contravariant’
    Perhaps you haven't installed the profiling libraries for package ‘contravariant-1.4’?
    Use -v to see a list of the files searched for.
   |
26 | import Data.Functor.Contravariant
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

So if I could map over all packages to enableLibraryProfiling on them, then I guess this could work. But my nix knowledge doesn't quite extend that far at the moment. How could I do that? And is this even the correct path to pursue?

答:
With further snooping around in nix-repl and some helpful pointers from ElvishJerricco on #reflex-frp at FreeNode, I was able to construct this, which seems to work:

$ nix-shell -p "(haskell.packages.ghc821.extend (self: super: {mkDerivation = expr: super.mkDerivation (expr // { enableLibraryProfiling = true; });})).ghcWithPackages (p: with p; [text hspec lens])" -j4 --run 'ghc Main.hs -prof'

Body:
I was trying like this initially:

nix-shell -p "haskell.packages.ghc821.ghcWithPackages (p: with p; [text hspec lens])" -j4 --run 'ghc Main.hs -prof

Then GHC told me

Main.hs:4:1: error:
    Could not find module ‘Control.Lens’
    Perhaps you haven't installed the profiling libraries for package ‘lens-4.15.4’?
    Use -v to see a list of the files searched for.

Searching around the web I found this: https://github.com/NixOS/nixpkgs/issues/22340

So it seems I won't be able to download from the cache. But that's okay, if at least I can build the profiled variants locally.

Can I do that somehow simply by modifying the nix expression given to -p slightly?

Then at this point in writing this question, I remembered this resource: https://github.com/NixOS/nixpkgs/blob/bd6ba7/pkgs/development/haskell-modules/lib.nix

Where I found enableLibraryProfiling. So I tried:

nix-shell -p "haskell.packages.ghc821.ghcWithPackages (p: with p; [text hspec (haskell.lib.enableLibraryProfiling lens)])" -j4 --run 'ghc Main.hs -prof'

Which got me to a new error:

src/Control/Lens/Internal/Getter.hs:26:1: error:
    Could not find module ‘Data.Functor.Contravariant’
    Perhaps you haven't installed the profiling libraries for package ‘contravariant-1.4’?
    Use -v to see a list of the files searched for.
   |
26 | import Data.Functor.Contravariant
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

So if I could map over all packages to enableLibraryProfiling on them, then I guess this could work. But my nix knowledge doesn't quite extend that far at the moment. How could I do that? And is this even the correct path to pursue?


问:
Why do I get InputMismatchException in my Java programme?
I have made a dog kennel/pound in Java that is working (in eclipse). But when I test it I get this InputMismatchException.
Is it something wrong with the way I did the switch-statement and the cases? Or something with my Scanner? The program is compiling so I don't understand.
One of the requirements in the assignment is for the program to accept these commands:

register new dog

increase age

list dogs

remove dog

exit

Another requirement is that the test program must identify the word "Error".
Please help me!!!

Here is the Dog class:

```<code>import java.util.*;

public class Dog {

    private String dogName;
    private String dogRace;
    private int dogAge;
    private double dogWeight;

    public Dog(String name, String race, int age, double weight){
    this.dogName = name;
    this.dogRace = race;
    this.dogAge = age;
    this.dogWeight = weight;
    }

    public String getDogName (){
        return this.dogName;
    }
    public String getDogRace (){
        return this.dogRace;
    }
    public void birthday(){
        dogAge = dogAge+1;
    }
    public int getDogAge(){
        return this.dogAge;
    }
    public double getDogWeight(){
        return this.dogWeight;
    }
    public double getDogTailLength(){
        if (!getDogRace().equalsIgnoreCase("Tax"))
        if(!getDogRace().equalsIgnoreCase("Dachshund")){
            return ((dogAge * dogWeight)/ 10);

        }
        return 3.7;
    }

    public String toString(){
        return "Name: " + getDogName() + ", Race: " + getDogRace() + ", Age: " + getDogAge() + ", Weight: " +
                getDogWeight() + ", Tail: " + getDogTailLength();

    }
}
</code>```

And here is the Main class:

```<code>import java.util.*;

public class Main {

    public static Scanner scan = new Scanner(System.in);

    private ArrayList <Dog> dogList = new ArrayList<Dog>();

    public ArrayList<Dog> getDogList(){
        return this.dogList;
    }

    public String dogMenu(){
        return "Choose a commande below: \n1) Register new dog \n2) Increase age \n3) List dogs \n4)"
                    + " Remove dog \n5) Exit ";
    }
    public String error(){
        return "ERROR: please choose a number between 1-5";
    }
    public void addDog(){
        System.out.println("1- Enter the dogs name: ");
        String name = scan.next();
        System.out.println("2- Enter the dogs race: ");
        String race = scan.next();
        System.out.println("3- Enter the dogs age: ");
        int age = scan.nextInt();
        System.out.println("4- Enter the dogs weight: ");
        double weight = scan.nextDouble();
        Dog newDog = new Dog(name, race, age, weight);
        getDogList().add(newDog);
        System.out.println(newDog);

    }

    public void ageDog(){
        System.out.println("Which dog would you like to age? (State the name): ");
        String write = scan.next();
        for(Dog d: getDogList()){
            if(d.getDogName().equalsIgnoreCase(write)){
                d.birthday();
            }else{
                System.out.println("ERROR: The dog doesn't exist in the kennel");

            }
        }
    }

    public void dogTail(){
        System.out.println("State the tail length: ");
        double dogTailLengthIn = scan.nextDouble();
        for(Dog d1: getDogList()){
            if(d1.getDogTailLength()>= dogTailLengthIn){
                System.out.println(d1);
            }
        }
        if(getDogList().isEmpty()){
            System.out.println("ERROR: There are no dogs!!!");

    }

    }
    public void deleteDog(){
        System.out.println("Which dog do you want to delete? (State the name): ");
        String nameIn = scan.next();
        boolean delete = false;
        for(int a = 0; a <getDogList().size();a++){
            if(getDogList().get(a).getDogName().equalsIgnoreCase(nameIn)){
                getDogList().remove(a);
                delete = true;
            }
        }
        if(delete){
            System.out.println("The dog " + nameIn + " is deleted from the register.");
        }else{
            System.out.println("The dog " + nameIn + " doesn't exist in the register.");
        }
    }
    public void exit(){
        System.out.println("Thank you. Hope to see you soon!");
        scan.close();
        System.exit(0);
    }
    public static void main(String[] args){

        /*      Dog betty = new Dog("pudel", "Betty", 4, 22, 1.5);

        Dog jonte = new Dog("rotweiler", "Jontis", 8, 60, 2);

        Dog jonas = new Dog("chihuahua", "Jonis", 2, 5, 0.3);*/

        Main kennel = new Main();

        while (true){
            System.out.print(kennel.dogMenu());
            int write = scan.nextInt();

            switch(write){

            case 1:
                kennel.addDog();
                break;

            case 2:
                kennel.ageDog();
                break;

            case 3:
                kennel.dogTail();
                break;

            case 4:
                kennel.deleteDog();
                break;

            case 5:
                kennel.exit();
            default:
                System.out.println(kennel.error());
            }
        }
    }
}
</code>```

Here is the problem:

```<code>Choose a commande below:
1) Register new dog
2) Increase age
3) List dogs
4) Remove dog
5) Exit

[IN:wrong command]
    java.util.concurrent.TimeoutException [LOOKING FOR: Any of [[fel case insensitive], [error case insensitive]]]
    [ERR: Exception in thread "main" java.util.InputMismatchException
      at java.util.Scanner.throwFor(Scanner.java:864)
      at java.util.Scanner.next(Scanner.java:1485)
      at java.util.Scanner.nextInt(Scanner.java:2117)
      at java.util.Scanner.nextInt(Scanner.java:2076)
      at Main.main(Main.java:96)]
</code>```

I get exactly this in every case!!

答:
My best guess is that when VPL is testing your program, it's giving invalid inputs to test that you're handling invalid inputs correctly.  And you aren't.

If you have learned about try and catch blocks, this would be a good time to implement that knowledge and catch the error so you can properly handle it.

Body:
I have made a dog kennel/pound in Java that is working (in eclipse). But when I test it I get this InputMismatchException.
Is it something wrong with the way I did the switch-statement and the cases? Or something with my Scanner? The program is compiling so I don't understand.
One of the requirements in the assignment is for the program to accept these commands:

register new dog

increase age

list dogs

remove dog

exit

Another requirement is that the test program must identify the word "Error".
Please help me!!!

Here is the Dog class:

import java.util.*;

public class Dog {

    private String dogName;
    private String dogRace;
    private int dogAge;
    private double dogWeight;

    public Dog(String name, String race, int age, double weight){
    this.dogName = name;
    this.dogRace = race;
    this.dogAge = age;
    this.dogWeight = weight;
    }

    public String getDogName (){
        return this.dogName;
    }
    public String getDogRace (){
        return this.dogRace;
    }
    public void birthday(){
        dogAge = dogAge+1;
    }
    public int getDogAge(){
        return this.dogAge;
    }
    public double getDogWeight(){
        return this.dogWeight;
    }
    public double getDogTailLength(){
        if (!getDogRace().equalsIgnoreCase("Tax"))
        if(!getDogRace().equalsIgnoreCase("Dachshund")){
            return ((dogAge * dogWeight)/ 10);

        }
        return 3.7;
    }

    public String toString(){
        return "Name: " + getDogName() + ", Race: " + getDogRace() + ", Age: " + getDogAge() + ", Weight: " +
                getDogWeight() + ", Tail: " + getDogTailLength();

    }
}

And here is the Main class:

import java.util.*;

public class Main {

    public static Scanner scan = new Scanner(System.in);

    private ArrayList <Dog> dogList = new ArrayList<Dog>();

    public ArrayList<Dog> getDogList(){
        return this.dogList;
    }

    public String dogMenu(){
        return "Choose a commande below: \n1) Register new dog \n2) Increase age \n3) List dogs \n4)"
                    + " Remove dog \n5) Exit ";
    }
    public String error(){
        return "ERROR: please choose a number between 1-5";
    }
    public void addDog(){
        System.out.println("1- Enter the dogs name: ");
        String name = scan.next();
        System.out.println("2- Enter the dogs race: ");
        String race = scan.next();
        System.out.println("3- Enter the dogs age: ");
        int age = scan.nextInt();
        System.out.println("4- Enter the dogs weight: ");
        double weight = scan.nextDouble();
        Dog newDog = new Dog(name, race, age, weight);
        getDogList().add(newDog);
        System.out.println(newDog);

    }

    public void ageDog(){
        System.out.println("Which dog would you like to age? (State the name): ");
        String write = scan.next();
        for(Dog d: getDogList()){
            if(d.getDogName().equalsIgnoreCase(write)){
                d.birthday();
            }else{
                System.out.println("ERROR: The dog doesn't exist in the kennel");

            }
        }
    }

    public void dogTail(){
        System.out.println("State the tail length: ");
        double dogTailLengthIn = scan.nextDouble();
        for(Dog d1: getDogList()){
            if(d1.getDogTailLength()>= dogTailLengthIn){
                System.out.println(d1);
            }
        }
        if(getDogList().isEmpty()){
            System.out.println("ERROR: There are no dogs!!!");

    }

    }
    public void deleteDog(){
        System.out.println("Which dog do you want to delete? (State the name): ");
        String nameIn = scan.next();
        boolean delete = false;
        for(int a = 0; a <getDogList().size();a++){
            if(getDogList().get(a).getDogName().equalsIgnoreCase(nameIn)){
                getDogList().remove(a);
                delete = true;
            }
        }
        if(delete){
            System.out.println("The dog " + nameIn + " is deleted from the register.");
        }else{
            System.out.println("The dog " + nameIn + " doesn't exist in the register.");
        }
    }
    public void exit(){
        System.out.println("Thank you. Hope to see you soon!");
        scan.close();
        System.exit(0);
    }
    public static void main(String[] args){

        /*      Dog betty = new Dog("pudel", "Betty", 4, 22, 1.5);

        Dog jonte = new Dog("rotweiler", "Jontis", 8, 60, 2);

        Dog jonas = new Dog("chihuahua", "Jonis", 2, 5, 0.3);*/

        Main kennel = new Main();

        while (true){
            System.out.print(kennel.dogMenu());
            int write = scan.nextInt();

            switch(write){

            case 1:
                kennel.addDog();
                break;

            case 2:
                kennel.ageDog();
                break;

            case 3:
                kennel.dogTail();
                break;

            case 4:
                kennel.deleteDog();
                break;

            case 5:
                kennel.exit();
            default:
                System.out.println(kennel.error());
            }
        }
    }
}

Here is the problem:

Choose a commande below:
1) Register new dog
2) Increase age
3) List dogs
4) Remove dog
5) Exit

[IN:wrong command]
    java.util.concurrent.TimeoutException [LOOKING FOR: Any of [[fel case insensitive], [error case insensitive]]]
    [ERR: Exception in thread "main" java.util.InputMismatchException
      at java.util.Scanner.throwFor(Scanner.java:864)
      at java.util.Scanner.next(Scanner.java:1485)
      at java.util.Scanner.nextInt(Scanner.java:2117)
      at java.util.Scanner.nextInt(Scanner.java:2076)
      at Main.main(Main.java:96)]

I get exactly this in every case!!