问:
Django user registration where username becomes "firstname.lastname"
I want to make a registration page for my django application in order to 'request' access. In other words they submit the form and it creates the user and user.is_active = False. Then as admin I can approve their access.

However I do not want them to be able to put in their username. Instead i want their username to be firstname.lastname. In the unlikely case of the same name people trying to sign up (app is for small number of people) - then a number will need adding on the end.

I do this at the moment using a signup view:

```<code>def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)

        if form.is_valid():
            form.save()

            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            raw_password = form.cleaned_data.get('password1')
            username = form.cleaned_data.get('username')

            user = authenticate(username=username, password=raw_password)

            user.is_active = False
            user.save()
            return render(request, 'registration/signedup.html', {'user': user})
        else:
            return render(request, 'registration/signup.html', {'form': form, 'invalid': 'Please try again.'})
    else:
        form = SignUpForm()
        return render(request, 'registration/signup.html', {'form': form})
</code>```

and a signup form:

```<code>class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
</code>```

and this as the html for my signup page:

```<code><form method="post"  autocomplete="off">
  {% csrf_token %}

   <table class='login' width='400'>
   {% for field in form %}

   <tr>
     <td width='200' class='loginrow'>{{ field.label_tag }}</td>
     <td width='180' class='loginrow'>{{ field }}</td>
       {% for error in field.errors %}
      <p style="color: red">{{ error }}</p>
       {% endfor %}
   </tr>
   {% endfor %}
</table>

 <button type="submit">Sign up</button>

</form>
</code>```

I have tried to remove username from my form field, and then create username variable as firs_name+'.'+last_name in my view by the user = authenticate() returns none.

Is there a way I can automatically produce a username without the user submitting one? - I was also thinking of using javascript function in the html page, and a hidden 'username' input tag which concats the names, but I can't get this to work either.

Thanks

答:
Override save method in SignUpForm

```<code>def save(self, commit=True):
    instance = super(SignUpForm, self).save(commit=False)
    instance.username = "%s.%s" %(self.cleaned_data['first_name'], self.cleaned_data['last_name'])
    if commit:
        instance.save()
    return instance
</code>```

Body:
I want to make a registration page for my django application in order to 'request' access. In other words they submit the form and it creates the user and user.is_active = False. Then as admin I can approve their access.

However I do not want them to be able to put in their username. Instead i want their username to be firstname.lastname. In the unlikely case of the same name people trying to sign up (app is for small number of people) - then a number will need adding on the end.

I do this at the moment using a signup view:

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)

        if form.is_valid():
            form.save()

            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            raw_password = form.cleaned_data.get('password1')
            username = form.cleaned_data.get('username')

            user = authenticate(username=username, password=raw_password)

            user.is_active = False
            user.save()
            return render(request, 'registration/signedup.html', {'user': user})
        else:
            return render(request, 'registration/signup.html', {'form': form, 'invalid': 'Please try again.'})
    else:
        form = SignUpForm()
        return render(request, 'registration/signup.html', {'form': form})

and a signup form:

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )

and this as the html for my signup page:

<form method="post"  autocomplete="off">
  {% csrf_token %}

   {% for field in form %}

     {{ field.label_tag }}
     {{ field }}
       {% for error in field.errors %}

{{ error }}

       {% endfor %}

   {% endfor %}

 <button type="submit">Sign up</button>

</form>

I have tried to remove username from my form field, and then create username variable as firs_name+'.'+last_name in my view by the user = authenticate() returns none.

Is there a way I can automatically produce a username without the user submitting one? - I was also thinking of using javascript function in the html page, and a hidden 'username' input tag which concats the names, but I can't get this to work either.

Thanks

Body:
Override save method in SignUpForm

def save(self, commit=True):
    instance = super(SignUpForm, self).save(commit=False)
    instance.username = "%s.%s" %(self.cleaned_data['first_name'], self.cleaned_data['last_name'])
    if commit:
        instance.save()
    return instance


来源: stackexchange

问:
how to get the date from string in C#
I have a string like

```<code> string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");
</code>```

want the output only 2017-03-10

答:
Do something like this</p>

```<code> string startdatestring = "2017-03-10T07:19:28.907";
 string s = startdatestring.Substring(0, 9);
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to get the date from string in C#

Body:
I have a string like

 string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");

want the output only 2017-03-10

Body:
Do something like this

 string startdatestring = "2017-03-10T07:19:28.907";
 string s = startdatestring.Substring(0, 9);


问:
Intercept "git commit -a(m)"
I like the fine-grained commits that the git index allow, i.e. the staging of individual files or even hunks through git add before the final commit. Unfortunately, sometimes after spending some time staging a particular commit, muscle-memory kicks in so that I git commit -a -m "msg". Then I either have to live with it, or jump through some reset or --amend hoops.

Is there a way for me to (ideally, globally) configure Git so that if I issue a git commit -a, it gets intercepted? Maybe a script asking me to confirm if I really want to commit all? I've thought about delegating the commit operation to a wrapper script (e.g., "gitcommit"), but do not think that will work very well as it does not stop me from doing a git commit -a -m "msg", which is the problem in the first place.

答:
Try pre-commit hooks:

something like this (not tested)

.git/hooks/pre-commit

```<code>#!/bin/sh
git diff-files --quiet    # check if the working directory have non-staged files
DIRTY_WORKING=$?

if [ ! $DIRTY_WORKING ] ; then        #  check if we are committing all files
   # list all files to be committed
   git diff-index --name-status --cached HEAD

   echo "Are you sure? (type YES to continue)"
   read VALUE
   [ "x$VALUE" != "xYES" ]
   exit $?
fi
exit 0
</code>```

You can find out the number of files to be committed using  git diff-index --cached HEAD | wc -l.  But I think I would leave this to yourself.

ContentLicense: CC BY-SA 2.5

Title: Intercept "git commit -a(m)"

Body:
Try pre-commit hooks:

something like this (not tested)

.git/hooks/pre-commit

#!/bin/sh
git diff-files --quiet    # check if the working directory have non-staged files
DIRTY_WORKING=$?

if [ ! $DIRTY_WORKING ] ; then        #  check if we are committing all files
   # list all files to be committed
   git diff-index --name-status --cached HEAD

   echo "Are you sure? (type YES to continue)"
   read VALUE
   [ "x$VALUE" != "xYES" ]
   exit $?
fi
exit 0

You can find out the number of files to be committed using  git diff-index --cached HEAD | wc -l.  But I think I would leave this to yourself.


问:
Loop through Cols & Rows with IF statement vba
All,

I have written the below code to check if cells in the variable range have conditional formatting. However the code falls over at  "If Cells.ColorIndex = 3 Then" can anyone suggest why the error is occurring and if there is a better solution than the below code to achieve a loop through cols & rows (variable length)

```<code>Sub Check_Conditional()

Dim rng As Range
Dim row As Range
Dim cell As Range

Dim RW As Long
RW = ActiveSheet.Range("Total").Offset(rowOffset:=-1).row
Set rng = Range("O7:AB" & RW)

For Each row In rng.Rows
    For Each cell In row.Cells
        If Cells.ColorIndex = 3 Then
            MsgBox "Not all the cells have been filled out"
            Exit For
        End If
    Next cell
Next row

End Sub
</code>```

答:
cell.ColorIndex is not a valid Range property.

If you mean to check the font's color then use If cell.Font.ColorIndex = 3 Then

If you mean to check the Fill color, then use If cell.Interior.ColorIndex = 3 Then

When you type in the editor, Cell. the VBA autocompletes it with the following options:

There's no cell.ColorIndex in the list:

Body:
All,

I have written the below code to check if cells in the variable range have conditional formatting. However the code falls over at  "If Cells.ColorIndex = 3 Then" can anyone suggest why the error is occurring and if there is a better solution than the below code to achieve a loop through cols & rows (variable length)

Sub Check_Conditional()

Dim rng As Range
Dim row As Range
Dim cell As Range

Dim RW As Long
RW = ActiveSheet.Range("Total").Offset(rowOffset:=-1).row
Set rng = Range("O7:AB" & RW)

For Each row In rng.Rows
    For Each cell In row.Cells
        If Cells.ColorIndex = 3 Then
            MsgBox "Not all the cells have been filled out"
            Exit For
        End If
    Next cell
Next row

End Sub


问:
Python MySQL: error inserting data
Here is my code

```<code>qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES ('%s','%s')"
cursor.execute(qry, ('123', '456',))
db_con.commit()
</code>```

I am getting error:

```<code>(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '123'',''456'')' at line 1")
</code>```

答:
You are using SQL parameters (yay!), and those already take care of proper quoting. You essentially double-quoted your values. Remove the quotes from the query:

```<code>qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES (%s,%s)"
</code>```

Title: Python MySQL: error inserting data

Body:
Here is my code

qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES ('%s','%s')"
cursor.execute(qry, ('123', '456',))
db_con.commit()

I am getting error:

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '123'',''456'')' at line 1")

Body:
You are using SQL parameters (yay!), and those already take care of proper quoting. You essentially double-quoted your values. Remove the quotes from the query:

qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES (%s,%s)"


问:
Search sibling of by another child's value in XML
I have a question regarding the processing of an XML file using DomDocument in PHP.

```<code><managedObject class="class1" version="version1" distName="distName1" id="id1">
    <p name="a">Data I have</p>
    <p name="b">Some data</p>
    <p name="c">Some data</p>
    <p name="d">Data I need</p>
    <p name="e">Some data</p>
</managedObject>

<managedObject class="class2" version="version2" distName="distName2" id="id2">
    <p name="a">Some data</p>
    <p name="b">Some data</p>
    <p name="c">Some data</p>
    <p name="d">Some data</p>
    <p name="e">Some data</p>
</managedObject>
</code>```

By only knowing the "a" element, could I get the "d" element, but only if the parent have a certain class and version?

So far I've had a few tries, most recent being:

```<code>$nodes = $finder->query("//*[contains(@class, 'class1')][contains(@version, 'version1')]/*[contains(@name, 'a')]");
foreach ($nodes as $node) {
            $Array[$i] = $node;
        }
</code>```

I used this to see at least some properties of the node but it doesn't return anything.

Any help would be appreciated.

答:
If you can work from Data I have and work back, an Xpath of //p[@name="d" and ../p[@name="a"]/text() = "Data I have" and parent::*[@version="version1"]] should be able to get you what you need

otherwise a sibling and parent check can be done with //p[@name="d" and ../p[@name="a"] and parent::*[@version="version1"]]

Body:
I have a question regarding the processing of an XML file using DomDocument in PHP.

<managedObject class="class1" version="version1" distName="distName1" id="id1">

Data I have

Some data

Some data

Data I need

Some data

</managedObject>

<managedObject class="class2" version="version2" distName="distName2" id="id2">

Some data

Some data

Some data

Some data

Some data

</managedObject>

By only knowing the "a" element, could I get the "d" element, but only if the parent have a certain class and version?

So far I've had a few tries, most recent being:

$nodes = $finder->query("//*[contains(@class, 'class1')][contains(@version, 'version1')]/*[contains(@name, 'a')]");
foreach ($nodes as $node) {
            $Array[$i] = $node;
        }

I used this to see at least some properties of the node but it doesn't return anything.

Any help would be appreciated.


问:
S3 operator overloading for multiple classes
I defined two classes that can successfully add two of their own objects or a number and one of their own objects.

```<code>a <- structure(list(val = 1), class = 'customClass1')
b <- structure(list(val = 1), class = 'customClass2')
`+.customClass1` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass1')
  return(structure(list(val = val_res), class = 'customClass1'))
}
`+.customClass2` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass2')
  return(structure(list(val = val_res), class = 'customClass1'))
}
print.customClass1 <- function(x, ...){
  print(x$val)
}
print.customClass2 <- function(x, ...){
  print(x$val)
}
a + a
# [1] 2
a + 1
# [1] 2
b + b
# [1] 2
1 + b
# [1] 2
</code>```

But obviously, it goes wrong when I try to add the two custom classes.

```<code>a + b
# Error in a + b : non-numeric argument to binary operator
# In addition: Warning message:
# Incompatible methods ("+.customClass1", "+.customClass2") for "+"
</code>```

I could define just one function for customClass1, but then that function would not work when I try to add two customClass2 objects. Is there any way to prioritize one function over the other?

R seems to do this naturally by prioritizing my functions over the base functions (e.g. of the type numeric or integer). When one of both arguments has the customClass type, R automatically redirects it to my function instead of the default function.

答:
Joshua explained why your approach can never work smoothly when using S3 without constructing virtual superclasses and the likes. With S3 you'll have to manually manage the class assignments in every possible function you use. Forget to assign the super class once, and you're off for a bug hunt that can last a while.

I would strongly suggest to abandon S3 and move to S4. Then you can define the methods in both directions for the group "Ops". This has the advantage that all arithmetic, logic and comparison operators are now defined for both classes. If you want to limit this to a subgroup or a single operator, replace "Ops" by the subgroup or operator. More info on the help page ?S4GroupGeneric.

An example based on your S3 classes using a virtual class to make things easier:

```<code># Define the superclass
setClass("super", representation(x = "numeric"))
# Define two custom classes
setClass("foo", representation(slot1 = "character"),
         contains = "super")
setClass("bar", representation(slot1 = "logical"),
         contains = "super")

# Set the methods
setMethod("Ops",
          signature = c('super','ANY'),
          function(e1,e2){
            callGeneric(e1@x, e2)
          })
setMethod("Ops",
          signature = c('ANY','super'),
          function(e1,e2){
            callGeneric(e1, e2@x)
          })
# Redundant actually, but limits the amount of times callGeneric
# has to be executed.
setMethod("Ops",
          signature = c('super','super'),
          function(e1,e2){
            callGeneric(e1@x, e2@x)
          })

foo1 <- new("foo", x = 3, slot1 = "3")
bar1 <- new("bar", x = 5, slot1 = TRUE)

foo1 + bar1
#> [1] 8
bar1 + foo1
#> [1] 8
bar1 < foo1
#> [1] FALSE
foo1 / bar1
#> [1] 0.6
</code>```

An example with 2 classes where the slot names are different:

```<code>setClass("foo", representation(x = "numeric"))
setClass("bar", representation(val = "numeric"))

setMethod("Ops",
          signature = c('foo','ANY'),
          function(e1,e2){
            callGeneric(e1@x, e2)
          })
setMethod("Ops",
          signature = c('bar','ANY'),
          function(e1,e2){
            callGeneric(e1@val, e2)
          })
setMethod("Ops",
          signature = c('ANY','bar'),
          function(e1,e2){
            callGeneric(e1, e2@val)
          })
setMethod("Ops",
          signature = c('ANY','foo'),
          function(e1,e2){
            callGeneric(e1, e2@x)
          })
</code>```

Again you can use the code above to check the results. Note that here you will get a note about the chosen methods when trying this interactively. To avoid that, you can add a method for signature c('foo','bar') and c('bar','foo')

Body:
I defined two classes that can successfully add two of their own objects or a number and one of their own objects.

a <- structure(list(val = 1), class = 'customClass1')
b <- structure(list(val = 1), class = 'customClass2')
`+.customClass1` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass1')
  return(structure(list(val = val_res), class = 'customClass1'))
}
`+.customClass2` <- function(e1, e2, ...){
  val1 <- ifelse(is.numeric(e1), e1, e1$val)
  val2 <- ifelse(is.numeric(e2), e2, e2$val)
  val_res <- val1  + val2
  print('customClass2')
  return(structure(list(val = val_res), class = 'customClass1'))
}
print.customClass1 <- function(x, ...){
  print(x$val)
}
print.customClass2 <- function(x, ...){
  print(x$val)
}
a + a
# [1] 2
a + 1
# [1] 2
b + b
# [1] 2
1 + b
# [1] 2

But obviously, it goes wrong when I try to add the two custom classes.

a + b
# Error in a + b : non-numeric argument to binary operator
# In addition: Warning message:
# Incompatible methods ("+.customClass1", "+.customClass2") for "+"

I could define just one function for customClass1, but then that function would not work when I try to add two customClass2 objects. Is there any way to prioritize one function over the other?

R seems to do this naturally by prioritizing my functions over the base functions (e.g. of the type numeric or integer). When one of both arguments has the customClass type, R automatically redirects it to my function instead of the default function.

Body:
Joshua explained why your approach can never work smoothly when using S3 without constructing virtual superclasses and the likes. With S3 you'll have to manually manage the class assignments in every possible function you use. Forget to assign the super class once, and you're off for a bug hunt that can last a while.

I would strongly suggest to abandon S3 and move to S4. Then you can define the methods in both directions for the group "Ops". This has the advantage that all arithmetic, logic and comparison operators are now defined for both classes. If you want to limit this to a subgroup or a single operator, replace "Ops" by the subgroup or operator. More info on the help page ?S4GroupGeneric.

An example based on your S3 classes using a virtual class to make things easier:

# Define the superclass
setClass("super", representation(x = "numeric"))
# Define two custom classes
setClass("foo", representation(slot1 = "character"),
         contains = "super")
setClass("bar", representation(slot1 = "logical"),
         contains = "super")

# Set the methods
setMethod("Ops",
          signature = c('super','ANY'),
          function(e1,e2){
            callGeneric(e1@x, e2)
          })
setMethod("Ops",
          signature = c('ANY','super'),
          function(e1,e2){
            callGeneric(e1, e2@x)
          })
# Redundant actually, but limits the amount of times callGeneric
# has to be executed.
setMethod("Ops",
          signature = c('super','super'),
          function(e1,e2){
            callGeneric(e1@x, e2@x)
          })

foo1 <- new("foo", x = 3, slot1 = "3")
bar1 <- new("bar", x = 5, slot1 = TRUE)

foo1 + bar1
#> [1] 8
bar1 + foo1
#> [1] 8
bar1 < foo1
#> [1] FALSE
foo1 / bar1
#> [1] 0.6

An example with 2 classes where the slot names are different:

setClass("foo", representation(x = "numeric"))
setClass("bar", representation(val = "numeric"))

setMethod("Ops",
          signature = c('foo','ANY'),
          function(e1,e2){
            callGeneric(e1@x, e2)
          })
setMethod("Ops",
          signature = c('bar','ANY'),
          function(e1,e2){
            callGeneric(e1@val, e2)
          })
setMethod("Ops",
          signature = c('ANY','bar'),
          function(e1,e2){
            callGeneric(e1, e2@val)
          })
setMethod("Ops",
          signature = c('ANY','foo'),
          function(e1,e2){
            callGeneric(e1, e2@x)
          })

Again you can use the code above to check the results. Note that here you will get a note about the chosen methods when trying this interactively. To avoid that, you can add a method for signature c('foo','bar') and c('bar','foo')


问:
C++ A constructor triggers a destructor
I'm trying to make a Monster generator using vectors and classes to allow the user to create and delete Monster objects as they wish. However, when I call the constructor of Monster in my code it also immediately triggers a destructor, thereby removing Monster from the the vector container.

This is the fragment of my code, which creates and destroys the Monster object:

```<code>while (p == 't')
{
    cout << "Generate (g) or remove (u) a monster?" << endl;
    cin >> p;
    while (p == 'u' && Monster::n == 0)
    {
        cout << "No monsters to remove." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    while (p != 'g' && p != 'u')
    {
        cout << "Error. Follow the instructions." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    if (p == 'g')
    {
        {
            vec.push_back(Monster());
            vec[Monster::n].print();
        }
    }
    if (p == 'u')
    {
        vec.~Monster();
    }
    cout << "Continue (t) or finish (n)?" << endl;
    cin >> p;
    while (p != 't' && p != 'n')
    {
        cout << "Error. Follow the instructions?" << endl;
        cout << "Continue (t) or finish (n)?" << endl;
        cin >> p;
    }
</code>```

This is the constructor for Monster:

```<code>Monster::Monster()
{
    ostringstream buffer;
    buffer << Monster::n;
    string name = buffer.str();
    Monster::setname(name);
    Monster::settype(MonsterType(rand() % 7 + 1));
    Monster::setattack(rand() % 25);
    Monster::sethealth(rand() % 15);
    cout << endl << "Monster generated." << endl << endl;
    Monster::n++;
}
</code>```

This is the destructor:

```<code>Monster::~Monster()
{
    cout << "Monster removed." << endl << endl;
    Monster::n--;
}
</code>```

When I input the character 'g', it creates a Monster object as expected but then immediately destroys it, even before its stats are printed with the print() method. This means my code is not acting as expected, as it will never allow the proper creation or destruction of Monster objects.

Can someone please help me understand what's going on here?

EDIT:

Alright, I was able to somewhat solve the issue by making another constructor.

This is it:

```<code>Monster::Monster(const Monster & mon)
{
    Monster::name = mon.name;
    Monster::type = mon.type;
    Monster::attack = mon.attack;
    Monster::health = mon.health;
    cout << endl << "Monster created (cpy)." << endl << endl;
    Monster::n++;
}
</code>```

I edited the point where the user decides to generate a Monster to the following:

```<code>    {
        vec.push_back(Monster());
        vector<Monster> veccpy = {};
        veccpy.push_back(Monster(vec[Monster::n-1]));
        vec.back().print();
    }
</code>```

When I lauch the program, it spits out something like this:

Monster created

Monster created (cpy)

Monster removed

Monster created (cpy)

Monster created (cpy)

Monster removed

Monster's stats

Now, the odd thing is even though it uses those constructors so oddly, the program works as I intended it to. n iterates as it should, I can remove or add Monster as I intended and the Monster stats are displayed as they should.

Could someone point to what I'm doing wrong here?

答:
```<code>vec.push_back(Monster());
</code>```

This is going to create a temporary object, an instance of the Monster class, and pass it to the vector's push_back() method.

push_back() will take its parameter and copy it into the vector. Since the vector owns its object, this will involve the construction of another instance of the Monster class.

After push_back() returns the temporary object that it passed as the parameter is going to get destroyed, thus invoking your object's destructor. And that's why you see a destructor getting invoked here.

Note that when adding objects to a vector, the vector may choose to reallocate its contents, at any time. This will involve, essentially, copy-constructing new instances of the class in the vector, then destroying the old ones, as well.

Lessons learned

Spend some time reading your C++ book and learn how smart pointers work, and put smart pointers in your vector, rather than object instances, in order to avoid unwanted side effects due to temporaries.

You could also implement move constructors as an alternative solution, but using smart pointers will probably be easier.

A second alternative is to emplace_back(), rather than push_back() new instances. However that won't solve your problem completely. See "reallocation", above.

Additionally, it wouldn't hurt to make your class Rule of 3 compliant either. The real underlying reason you asked this question is likely because it's currently not.

Title: C++ A constructor triggers a destructor

Body:
I'm trying to make a Monster generator using vectors and classes to allow the user to create and delete Monster objects as they wish. However, when I call the constructor of Monster in my code it also immediately triggers a destructor, thereby removing Monster from the the vector container.

This is the fragment of my code, which creates and destroys the Monster object:

while (p == 't')
{
    cout << "Generate (g) or remove (u) a monster?" << endl;
    cin >> p;
    while (p == 'u' && Monster::n == 0)
    {
        cout << "No monsters to remove." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    while (p != 'g' && p != 'u')
    {
        cout << "Error. Follow the instructions." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    if (p == 'g')
    {
        {
            vec.push_back(Monster());
            vec[Monster::n].print();
        }
    }
    if (p == 'u')
    {
        vec.~Monster();
    }
    cout << "Continue (t) or finish (n)?" << endl;
    cin >> p;
    while (p != 't' && p != 'n')
    {
        cout << "Error. Follow the instructions?" << endl;
        cout << "Continue (t) or finish (n)?" << endl;
        cin >> p;
    }

This is the constructor for Monster:

Monster::Monster()
{
    ostringstream buffer;
    buffer << Monster::n;
    string name = buffer.str();
    Monster::setname(name);
    Monster::settype(MonsterType(rand() % 7 + 1));
    Monster::setattack(rand() % 25);
    Monster::sethealth(rand() % 15);
    cout << endl << "Monster generated." << endl << endl;
    Monster::n++;
}

This is the destructor:

Monster::~Monster()
{
    cout << "Monster removed." << endl << endl;
    Monster::n--;
}

When I input the character 'g', it creates a Monster object as expected but then immediately destroys it, even before its stats are printed with the print() method. This means my code is not acting as expected, as it will never allow the proper creation or destruction of Monster objects.

Can someone please help me understand what's going on here?

EDIT:

Alright, I was able to somewhat solve the issue by making another constructor.

This is it:

Monster::Monster(const Monster & mon)
{
    Monster::name = mon.name;
    Monster::type = mon.type;
    Monster::attack = mon.attack;
    Monster::health = mon.health;
    cout << endl << "Monster created (cpy)." << endl << endl;
    Monster::n++;
}

I edited the point where the user decides to generate a Monster to the following:

    {
        vec.push_back(Monster());
        vector<Monster> veccpy = {};
        veccpy.push_back(Monster(vec[Monster::n-1]));
        vec.back().print();
    }

When I lauch the program, it spits out something like this:

Monster created

Monster created (cpy)

Monster removed

Monster created (cpy)

Monster created (cpy)

Monster removed

Monster's stats

Now, the odd thing is even though it uses those constructors so oddly, the program works as I intended it to. n iterates as it should, I can remove or add Monster as I intended and the Monster stats are displayed as they should.

Could someone point to what I'm doing wrong here?

Body:
vec.push_back(Monster());

This is going to create a temporary object, an instance of the Monster class, and pass it to the vector's push_back() method.

push_back() will take its parameter and copy it into the vector. Since the vector owns its object, this will involve the construction of another instance of the Monster class.

After push_back() returns the temporary object that it passed as the parameter is going to get destroyed, thus invoking your object's destructor. And that's why you see a destructor getting invoked here.

Note that when adding objects to a vector, the vector may choose to reallocate its contents, at any time. This will involve, essentially, copy-constructing new instances of the class in the vector, then destroying the old ones, as well.

Lessons learned

Spend some time reading your C++ book and learn how smart pointers work, and put smart pointers in your vector, rather than object instances, in order to avoid unwanted side effects due to temporaries.

You could also implement move constructors as an alternative solution, but using smart pointers will probably be easier.

A second alternative is to emplace_back(), rather than push_back() new instances. However that won't solve your problem completely. See "reallocation", above.

Additionally, it wouldn't hurt to make your class Rule of 3 compliant either. The real underlying reason you asked this question is likely because it's currently not.


问:
How to access/get the value of a Variable inside a nested if statement to outside the main if statement
I have this code sample which I was developing. Here I have declared two variables (initialPath, lastPath) outside the main if-else statement. Inside the main If statement there is a nested if-else statement. I have initialized the variable (initialPath) inside the nested if statement. I need that value to be used outside the nested if-else statement. I have attached my code snippet. If anyone can help to solve my problem, I'd be glad :)</p>

```<code>    FileWriter writer;
    File initialPath=null;
    File lastPath=null;

    if (clicked == 1) {

        int sf = savefile.showSaveDialog(null);

        if (sf == JFileChooser.APPROVE_OPTION) {

            initialPath=savefile.getSelectedFile(); // in here the Variable values is initialized/assigned

            try {

                if (savefile.getFileFilter().equals(filter2)) {

                    String path = savefile.getSelectedFile() + ".java";
                    File file = new File(path);
                    writer = new FileWriter(file, false);
                    System.out.println(savefile.getFileFilter());
                    writer.write(jTextPane1.getText());

                    writer.close();
                } else if (savefile.getFileFilter().equals(filter)) {

                    System.out.println("2");
                    String path = savefile.getSelectedFile() + ".txt";
                    File file = new File(path);
                    writer = new FileWriter(file, false);

                    writer.write(jTextPane1.getText());

                    writer.close();

                } else {
                    System.out.println("No format");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (sf == JFileChooser.CANCEL_OPTION) {

            clicked = 0;

        }

    } else {

        try {

            lastPath=initialPath.getParentFile(); //but in here lastPath become NULL because initialPath is NULL...

    //I need to get the value of initialPath to this ELSE statement

            if (savefile.getFileFilter().equals(filter2)) {

                String path = savefile.getSelectedFile() + ".java";
                File file = new File(path);
                writer = new FileWriter(file, false);
                System.out.println(savefile.getFileFilter());
                writer.write(jTextPane1.getText());

                writer.close();
            } else if (savefile.getFileFilter().equals(filter)) {

                String path = savefile.getSelectedFile() + ".txt";
                File file = new File(path);
                writer = new FileWriter(file, false);

                writer.write(jTextPane1.getText());

                writer.close();

            } else {
                System.out.println("No format");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

答:
Is it possible for you to move initialPath=savefile.getSelectedFile(); outside of the if statement?

```<code>initialPath=savefile.getSelectedFile();
if (sf == JFileChooser.APPROVE_OPTION) {
    ...
}
else {
    ...
}
</code>```

Body:
I have this code sample which I was developing. Here I have declared two variables (initialPath, lastPath) outside the main if-else statement. Inside the main If statement there is a nested if-else statement. I have initialized the variable (initialPath) inside the nested if statement. I need that value to be used outside the nested if-else statement. I have attached my code snippet. If anyone can help to solve my problem, I'd be glad :)

    FileWriter writer;
    File initialPath=null;
    File lastPath=null;

    if (clicked == 1) {

        int sf = savefile.showSaveDialog(null);

        if (sf == JFileChooser.APPROVE_OPTION) {

            initialPath=savefile.getSelectedFile(); // in here the Variable values is initialized/assigned

            try {

                if (savefile.getFileFilter().equals(filter2)) {

                    String path = savefile.getSelectedFile() + ".java";
                    File file = new File(path);
                    writer = new FileWriter(file, false);
                    System.out.println(savefile.getFileFilter());
                    writer.write(jTextPane1.getText());

                    writer.close();
                } else if (savefile.getFileFilter().equals(filter)) {

                    System.out.println("2");
                    String path = savefile.getSelectedFile() + ".txt";
                    File file = new File(path);
                    writer = new FileWriter(file, false);

                    writer.write(jTextPane1.getText());

                    writer.close();

                } else {
                    System.out.println("No format");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (sf == JFileChooser.CANCEL_OPTION) {

            clicked = 0;

        }

    } else {

        try {

            lastPath=initialPath.getParentFile(); //but in here lastPath become NULL because initialPath is NULL...

    //I need to get the value of initialPath to this ELSE statement

            if (savefile.getFileFilter().equals(filter2)) {

                String path = savefile.getSelectedFile() + ".java";
                File file = new File(path);
                writer = new FileWriter(file, false);
                System.out.println(savefile.getFileFilter());
                writer.write(jTextPane1.getText());

                writer.close();
            } else if (savefile.getFileFilter().equals(filter)) {

                String path = savefile.getSelectedFile() + ".txt";
                File file = new File(path);
                writer = new FileWriter(file, false);

                writer.write(jTextPane1.getText());

                writer.close();

            } else {
                System.out.println("No format");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

Body:
Is it possible for you to move initialPath=savefile.getSelectedFile(); outside of the if statement?

initialPath=savefile.getSelectedFile();
if (sf == JFileChooser.APPROVE_OPTION) {
    ...
}
else {
    ...
}


问:
Click a button using delphi and javascript
I'm having difficulty pressing a button using delphi and javascript. My question is not like other's because in other's the questions are about how to press a image and they are the same title of this post. And the other is about chromium. My question is how in my webbrowser made in delphi i can press a button the code is the follow:

```<code>{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$WARNINGS ON}

unit FmDemo;

interface

uses
  SHDocVw, Controls, StdCtrls, Classes, OleCtrls, Forms;

type
  TForm1 = class(TForm)
    WebBrowser1: TWebBrowser;
    ComboBox1: TComboBox;
    procedure FormShow(Sender: TObject);
    procedure WebBrowser1DocumentComplete(Sender: TObject;
      const pDisp: IDispatch; var URL: OleVariant);
    procedure ComboBox1Change(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

uses
  SysUtils, Dialogs, MSHTML;

{$R *.dfm}

procedure TForm1.ComboBox1Change(Sender: TObject);
  { Make browser use selected font }
var
  Doc: IHTMLDocument2;      // current HTML document
  HTMLWindow: IHTMLWindow2; // parent window of current HTML document
  JSFn: string;             // stores JavaScipt function call
begin
  // Get reference to current document
  Doc := WebBrowser1.Document as IHTMLDocument2;
  if not Assigned(Doc) then
    Exit;
  // Get parent window of current document
  HTMLWindow := Doc.parentWindow;
  if not Assigned(HTMLWindow) then
    Exit;
  // Run JavaScript
  try
    JSFn := 'myFunction(''' + ComboBox1.Text + ''')';
    HTMLWindow.execScript(JSFn, 'JavaScript');
  except
    // handle exception in case JavaScript fails to run
    ShowMessage('Error running JavaScript');
  end;
end;

procedure TForm1.FormShow(Sender: TObject);
  { Setup combo box and load document }
begin
  // Store screen fonts in combo box and disabled it
  ComboBox1.Items.Assign(Screen.Fonts);
  ComboBox1.Enabled := False;
  // Load the HTML page
  WebBrowser1.Navigate('C:\Users\Androide\Desktop\article-21-demo\CaseStudy\Test.html');
end;

procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject;
  const pDisp: IDispatch; var URL: OleVariant);
  { Document loaded: enable combo box }
begin
  ComboBox1.Enabled := True;
end;

end.
</code>```

My html:

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
}
</script>

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

When i load the page never press the button. And my goal is when i load the page since my browser press this button, example(when i load the page never press me the button=:

never press the button

So i must to press manually..and show me hello world to check is pressed:
hello word message when i press button

Some way to do automatically not pressing manual.

Reference:

```<code>http://delphidabbler.com/articles?article=21
</code>```

答:
You posted a very similar q yesterday but deleted it before I could post this answer.

It does what you said you wanted in your deleted q, which iirc was to call the JavaScript to change an element's font from Delphi code.  It shouldn't be hard to modify
to do what you want in this one, which seems to differ only in the use of a combobox to select the new font name, and the use of an HTML-embedded button.

Code

```<code>procedure TForm1.Button1Click(Sender: TObject);
begin
  ExecScript(Memo2.Lines.Text);
end;

procedure TForm1.btnLoadFromMemoClick(Sender: TObject);
var
  V : OleVariant;
  Unk : IUnknown;
begin
  WebBrowser1.Navigate('about:blank');
  Doc2 := WebBrowser1.Document as IHTMLDocument2;
  Doc2.DesignMode := 'Off';
  V := VarArrayCreate([0, 0], varVariant);
  V[0] := Memo1.Lines.Text;
  try
    Doc2.Write(PSafeArray(TVarData(v).VArray));
  finally
    Doc2.Close;
  end;
end;

procedure TForm1.ExecScript(const Script: String);
var
  Doc: IHTMLDocument2;
  HTMLWindow: IHTMLWindow2;
begin
  Doc := WebBrowser1.Document as IHTMLDocument2;
  Assert(Doc <> Nil);

  HTMLWindow := Doc.parentWindow;
  Assert(HTMLWindow <> Nil);
  try
    HTMLWindow.execScript(Script, 'JavaScript');
  except
    // handle exception in case JavaScript fails to run
  end;
end;
</code>```

Html (put in Memo1.Lines)

```<code><html>
  <head>
  <script type="text/javascript">
  function SetFont(fontname) {
    document.body.style.fontFamily = fontname;
  }
  </script>
  </head>
  <body>
  Something
  <br>
  <div>some more text</div>
  </body>
</html>
</code>```

JavaScript(put in Memo1.Lines)

```<code>SetFont("Courier New");
</code>```

The following code shows how to click an HTML button whose id is 'mybutton' using Delphi code:

```<code>var
  Doc3: IHTMLDocument3;
  E : IHtmlElement;
begin
  Doc3 := WebBrowser1.Document as IHTMLDocument3;
  Assert(Doc3 <> Nil);
  E := Doc3.GetElementByID('mybutton');
  Assert(E <> Nil);
  E.click;
end;
</code>```

but now I've told you how to call the font-changing JavaScript from Delphi code maybe you don't need to click the HTML button any more.

Body:
I'm having difficulty pressing a button using delphi and javascript. My question is not like other's because in other's the questions are about how to press a image and they are the same title of this post. And the other is about chromium. My question is how in my webbrowser made in delphi i can press a button the code is the follow:

{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$WARNINGS ON}

unit FmDemo;

interface

uses
  SHDocVw, Controls, StdCtrls, Classes, OleCtrls, Forms;

type
  TForm1 = class(TForm)
    WebBrowser1: TWebBrowser;
    ComboBox1: TComboBox;
    procedure FormShow(Sender: TObject);
    procedure WebBrowser1DocumentComplete(Sender: TObject;
      const pDisp: IDispatch; var URL: OleVariant);
    procedure ComboBox1Change(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

uses
  SysUtils, Dialogs, MSHTML;

{$R *.dfm}

procedure TForm1.ComboBox1Change(Sender: TObject);
  { Make browser use selected font }
var
  Doc: IHTMLDocument2;      // current HTML document
  HTMLWindow: IHTMLWindow2; // parent window of current HTML document
  JSFn: string;             // stores JavaScipt function call
begin
  // Get reference to current document
  Doc := WebBrowser1.Document as IHTMLDocument2;
  if not Assigned(Doc) then
    Exit;
  // Get parent window of current document
  HTMLWindow := Doc.parentWindow;
  if not Assigned(HTMLWindow) then
    Exit;
  // Run JavaScript
  try
    JSFn := 'myFunction(''' + ComboBox1.Text + ''')';
    HTMLWindow.execScript(JSFn, 'JavaScript');
  except
    // handle exception in case JavaScript fails to run
    ShowMessage('Error running JavaScript');
  end;
end;

procedure TForm1.FormShow(Sender: TObject);
  { Setup combo box and load document }
begin
  // Store screen fonts in combo box and disabled it
  ComboBox1.Items.Assign(Screen.Fonts);
  ComboBox1.Enabled := False;
  // Load the HTML page
  WebBrowser1.Navigate('C:\Users\Androide\Desktop\article-21-demo\CaseStudy\Test.html');
end;

procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject;
  const pDisp: IDispatch; var URL: OleVariant);
  { Document loaded: enable combo box }
begin
  ComboBox1.Enabled := True;
end;

end.

My html:

<!DOCTYPE html>

Click the button to trigger a function that will output "Hello World" in a p element with id="demo".

<button onclick="myFunction()">Click me</button>

When i load the page never press the button. And my goal is when i load the page since my browser press this button, example(when i load the page never press me the button=:

never press the button

So i must to press manually..and show me hello world to check is pressed:
hello word message when i press button

Some way to do automatically not pressing manual.

Reference:

http://delphidabbler.com/articles?article=21

Body:
You posted a very similar q yesterday but deleted it before I could post this answer.

It does what you said you wanted in your deleted q, which iirc was to call the JavaScript to change an element's font from Delphi code.  It shouldn't be hard to modify
to do what you want in this one, which seems to differ only in the use of a combobox to select the new font name, and the use of an HTML-embedded button.

Code

procedure TForm1.Button1Click(Sender: TObject);
begin
  ExecScript(Memo2.Lines.Text);
end;

procedure TForm1.btnLoadFromMemoClick(Sender: TObject);
var
  V : OleVariant;
  Unk : IUnknown;
begin
  WebBrowser1.Navigate('about:blank');
  Doc2 := WebBrowser1.Document as IHTMLDocument2;
  Doc2.DesignMode := 'Off';
  V := VarArrayCreate([0, 0], varVariant);
  V[0] := Memo1.Lines.Text;
  try
    Doc2.Write(PSafeArray(TVarData(v).VArray));
  finally
    Doc2.Close;
  end;
end;

procedure TForm1.ExecScript(const Script: String);
var
  Doc: IHTMLDocument2;
  HTMLWindow: IHTMLWindow2;
begin
  Doc := WebBrowser1.Document as IHTMLDocument2;
  Assert(Doc <> Nil);

  HTMLWindow := Doc.parentWindow;
  Assert(HTMLWindow <> Nil);
  try
    HTMLWindow.execScript(Script, 'JavaScript');
  except
    // handle exception in case JavaScript fails to run
  end;
end;

Html (put in Memo1.Lines)

<html>
  <head>
  <script type="text/javascript">
  function SetFont(fontname) {
    document.body.style.fontFamily = fontname;
  }
  </script>
  </head>
  <body>
  Something
  <br>
  <div>some more text</div>
  </body>
</html>

JavaScript(put in Memo1.Lines)

SetFont("Courier New");

The following code shows how to click an HTML button whose id is 'mybutton' using Delphi code:

var
  Doc3: IHTMLDocument3;
  E : IHtmlElement;
begin
  Doc3 := WebBrowser1.Document as IHTMLDocument3;
  Assert(Doc3 <> Nil);
  E := Doc3.GetElementByID('mybutton');
  Assert(E <> Nil);
  E.click;
end;

but now I've told you how to call the font-changing JavaScript from Delphi code maybe you don't need to click the HTML button any more.


问:
How to prepare SQL statement with POINT using mysqli when using INSERT
I can't seem to find where documented to successfully prepare a statement that uses the POINT data type.

This previous question (How to use POINT mysql type with mysqli - php) shows something marked as correct, but it doesn't work. I even tried using their simple query in their example:

```<code>$stmt = $this->conn->prepare("INSERT INTO days(day,POINT(lat,lon)) VALUES(?,?,?)");
$stmt->bind_param("sdd", $day, $lat, $lon);
</code>```

This just simply returns and error:

```<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(lat,lon)) VALUES(?,?,?)' at line 1
</code>```

答:
Try like below;</p>

```<code>$stmt = $this->conn->prepare("INSERT INTO days(day,column_name) VALUES(?,POINT(?,?))"); //column_name is name of of column that you want to insert POINT(lat,lon)
    $stmt->bind_param("sdd", $day, $lat, $lon);
    $stmt->execute();
</code>```

Body:
I can't seem to find where documented to successfully prepare a statement that uses the POINT data type.

This previous question (How to use POINT mysql type with mysqli - php) shows something marked as correct, but it doesn't work. I even tried using their simple query in their example:

$stmt = $this->conn->prepare("INSERT INTO days(day,POINT(lat,lon)) VALUES(?,?,?)");
$stmt->bind_param("sdd", $day, $lat, $lon);

This just simply returns and error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(lat,lon)) VALUES(?,?,?)' at line 1

Body:
Try like below;

$stmt = $this->conn->prepare("INSERT INTO days(day,column_name) VALUES(?,POINT(?,?))"); //column_name is name of of column that you want to insert POINT(lat,lon)
    $stmt->bind_param("sdd", $day, $lat, $lon);
    $stmt->execute();


问:
Hanging Excel.exe process in automated program
```<code>var tempFileName = file.Replace(".xlsx", "_Temp.xlsx");
Application excelApp = new Application();
Workbooks books = excelApp.Workbooks;
Workbook excelFile = books.Open(file);
Sheets sheets = excelFile.Worksheets;
var app = excelApp.Application;
DeleteRows(sheets, 3);
excelFile.SaveAs(tempFileName);
excelFile.Close();
books.Close();
app.Quit();
excelApp.Quit();
Marshal.FinalReleaseComObject(sheets);
Marshal.ReleaseComObject(excelFile);
Marshal.ReleaseComObject(books);
Marshal.FinalReleaseComObject(excelApp);
sheets = null;
excelFile = null;
excelApp = null;
books = null;
</code>```

I am trying to dispose of my excel objects, however even the above code still leaves me with hanging EXCEL.EXE processes after the program has finished running. I have seen this question on here a number of times, but most of the askers had not tried the ReleaseComObject() method, however that did not fix anything for me.

EDIT: This is the code i use to read the table after deleting the header

```<code>  System.Data.DataTable schemaTable = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  DataRow schemaRow = schemaTable.Rows[0];
  string sheet = schemaRow["TABLE_NAME"].ToString();
  if (!sheet.EndsWith("_"))
  {
      string query = "SELECT  * FROM [Daily Payment$]";
      OleDbDataAdapter daexcel = new OleDbDataAdapter(query, excelConnection);
      dtexcel.Locale = CultureInfo.CurrentCulture;
      daexcel.Fill(dtexcel);
      var reader = dtexcel.CreateDataReader();
</code>```

and here is the code for DeleteRows:

```<code>void DeleteRows(Sheets sheets, int n)
{
    foreach (Worksheet workSheet in sheets)
    {
        Range range = workSheet.get_Range("A1", "A" + n);
        Range row = range.EntireRow;
        row.Delete(XlDirection.xlUp);
        Marshal.ReleaseComObject(workSheet);
    }
}
</code>```

FINAL EDIT: I have reposted the new code that I have at the top of the post. I am still getting one lingering object (even though i run the process multiple times). Calling Gc.Collect() works, but as a relative neophyte, i figured it was best to avoid something so powerful.

答:
For freeing Office COM interop objects, you can go by the 'one release per . rule'. That is, when you have a chain of member accesses, you need to free all the intermediate objects.

This often means splitting up your code into additional lines.

Following that rule, you're missing one. You need to keep a handle to the Workbooks object you've implicitly created.

```<code>Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Workbooks books = excelApp.Workbooks;
Workbook excelFile = books.Open(file);
DeleteRows(excelFile, 3);
</code>```

Then you need to call:

```<code>Marshal.ReleaseComObject(books);
</code>```

at the end.

Failing this, you can also try calling:

```<code>books.Close()
</code>```

before you quit Excel. And to go overkill, you can change all your ReleaseComObject calls to FinalReleaseComObject.

EDIT:
In your newly posted update, you are not releasing your Row or Range objects. Call FinalReleaseComObject on these, and I'd expect the problem to be solved.

Body:
var tempFileName = file.Replace(".xlsx", "_Temp.xlsx");
Application excelApp = new Application();
Workbooks books = excelApp.Workbooks;
Workbook excelFile = books.Open(file);
Sheets sheets = excelFile.Worksheets;
var app = excelApp.Application;
DeleteRows(sheets, 3);
excelFile.SaveAs(tempFileName);
excelFile.Close();
books.Close();
app.Quit();
excelApp.Quit();
Marshal.FinalReleaseComObject(sheets);
Marshal.ReleaseComObject(excelFile);
Marshal.ReleaseComObject(books);
Marshal.FinalReleaseComObject(excelApp);
sheets = null;
excelFile = null;
excelApp = null;
books = null;

I am trying to dispose of my excel objects, however even the above code still leaves me with hanging EXCEL.EXE processes after the program has finished running. I have seen this question on here a number of times, but most of the askers had not tried the ReleaseComObject() method, however that did not fix anything for me.

EDIT: This is the code i use to read the table after deleting the header

  System.Data.DataTable schemaTable = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  DataRow schemaRow = schemaTable.Rows[0];
  string sheet = schemaRow["TABLE_NAME"].ToString();
  if (!sheet.EndsWith("_"))
  {
      string query = "SELECT  * FROM [Daily Payment$]";
      OleDbDataAdapter daexcel = new OleDbDataAdapter(query, excelConnection);
      dtexcel.Locale = CultureInfo.CurrentCulture;
      daexcel.Fill(dtexcel);
      var reader = dtexcel.CreateDataReader();

and here is the code for DeleteRows:

void DeleteRows(Sheets sheets, int n)
{
    foreach (Worksheet workSheet in sheets)
    {
        Range range = workSheet.get_Range("A1", "A" + n);
        Range row = range.EntireRow;
        row.Delete(XlDirection.xlUp);
        Marshal.ReleaseComObject(workSheet);
    }
}

FINAL EDIT: I have reposted the new code that I have at the top of the post. I am still getting one lingering object (even though i run the process multiple times). Calling Gc.Collect() works, but as a relative neophyte, i figured it was best to avoid something so powerful.

Body:
For freeing Office COM interop objects, you can go by the 'one release per . rule'. That is, when you have a chain of member accesses, you need to free all the intermediate objects.

This often means splitting up your code into additional lines.

Following that rule, you're missing one. You need to keep a handle to the Workbooks object you've implicitly created.

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Workbooks books = excelApp.Workbooks;
Workbook excelFile = books.Open(file);
DeleteRows(excelFile, 3);

Then you need to call:

Marshal.ReleaseComObject(books);

at the end.

Failing this, you can also try calling:

books.Close()

before you quit Excel. And to go overkill, you can change all your ReleaseComObject calls to FinalReleaseComObject.

EDIT:
In your newly posted update, you are not releasing your Row or Range objects. Call FinalReleaseComObject on these, and I'd expect the problem to be solved.


问:
Different ways of comparing NSDecimalNumber
For example, with primitive, I'll do this

```<code>if ( (x >= 6000) && (x <= 20000) )
    // do something here
</code>```

and with NSDecimalNumber, this is what I have

```<code>if ( (([x compare:[NSNumber numberWithInt:6000]] == NSOrderedSame) ||
        ([x compare:[NSNumber numberWithInt:6000]] == NSOrderedDescending))
    && (([x compare:[NSNumber numberWithInt:20000]] == NSOrderedSame) ||
        ([x compare:[NSNumber numberWithInt:6000]] == NSOrderedAscending)) )
{
    // do something here
}
</code>```

Is there any other ways (easier and more elegant) to this comparison? If I convert the value to primitive, what primitive do I use? I don't want to use CGFloat, float or double, as I'm handling with currency here. Or if I do convert them to those mentioned above, can someone verify / explain about the precision?

答:
NSDecimalNumber+Comparison Category Code

```<code>@interface NSDecimalNumber (Comparison)

- (BOOL)isLessThan:(NSDecimalNumber *)decimalNumber;
- (BOOL)isLessThanOrEqualTo:(NSDecimalNumber *)decimalNumber;
- (BOOL)isGreaterThan:(NSDecimalNumber *)decimalNumber;
- (BOOL)isGreaterThanOrEqualTo:(NSDecimalNumber *)decimalNumber;
- (BOOL)isEqualToDecimalNumber:(NSDecimalNumber *)decimalNumber;

@end

@implementation NSDecimalNumber (Comparison)

- (BOOL)isLessThan:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] == NSOrderedAscending;
}

- (BOOL)isLessThanOrEqualTo:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] != NSOrderedDescending;
}

- (BOOL)isGreaterThan:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] == NSOrderedDescending;
}

- (BOOL)isGreaterThanOrEqualTo:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] != NSOrderedAscending;
}

- (BOOL)isEqualToDecimalNumber:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] == NSOrderedSame;
}

@end
</code>```

Unit Tests for good measure

```<code>@interface NSDecimalNumber_Comparison_Tests : XCTestCase

@end

@implementation NSDecimalNumber_Comparison_Tests

#pragma mark - isLessThan: tests

- (void)test_isLessThan_whenGreaterThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isLessThan:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isLessThan_whenLessThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isLessThan:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isLessThan_whenEqualTo_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertFalse(result);
}

#pragma mark - isLessThanOrEqualTo: tests

- (void)test_isLessThanOrEqualTo_whenGreaterThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isLessThanOrEqualTo:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isLessThanOrEqualTo_whenLessThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isLessThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isLessThanOrEqualTo_whenEqualTo_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isLessThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

#pragma mark - isGreaterThan: tests

- (void)test_isGreaterThan_whenGreaterThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isGreaterThan_whenLessThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isGreaterThan_whenEqualTo_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertFalse(result);
}

#pragma mark - isGreaterThanOrEqualTo: tests

- (void)test_isGreaterThanOrEqualTo_whenGreaterThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isGreaterThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isGreaterThanOrEqualTo_whenLessThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isGreaterThanOrEqualTo:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isGreaterThanOrEqualTo_whenEqualTo_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isGreaterThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

#pragma mark - isEqualToDecimalNumber: tests

- (void)test_isEqualToDecimalNumber_whenGreaterThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isEqualToDecimalNumber:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isEqualToDecimalNumber_whenLessThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isEqualToDecimalNumber:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isEqualToDecimalNumber_whenEqualTo_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isEqualToDecimalNumber:decimalNumberB];

    XCTAssertTrue(result);
}

@end
</code>```

Body:
For example, with primitive, I'll do this

if ( (x >= 6000) && (x <= 20000) )
    // do something here

and with NSDecimalNumber, this is what I have

if ( (([x compare:[NSNumber numberWithInt:6000]] == NSOrderedSame) ||
        ([x compare:[NSNumber numberWithInt:6000]] == NSOrderedDescending))
    && (([x compare:[NSNumber numberWithInt:20000]] == NSOrderedSame) ||
        ([x compare:[NSNumber numberWithInt:6000]] == NSOrderedAscending)) )
{
    // do something here
}

Is there any other ways (easier and more elegant) to this comparison? If I convert the value to primitive, what primitive do I use? I don't want to use CGFloat, float or double, as I'm handling with currency here. Or if I do convert them to those mentioned above, can someone verify / explain about the precision?

Body:
NSDecimalNumber+Comparison Category Code

@interface NSDecimalNumber (Comparison)

- (BOOL)isLessThan:(NSDecimalNumber *)decimalNumber;
- (BOOL)isLessThanOrEqualTo:(NSDecimalNumber *)decimalNumber;
- (BOOL)isGreaterThan:(NSDecimalNumber *)decimalNumber;
- (BOOL)isGreaterThanOrEqualTo:(NSDecimalNumber *)decimalNumber;
- (BOOL)isEqualToDecimalNumber:(NSDecimalNumber *)decimalNumber;

@end

@implementation NSDecimalNumber (Comparison)

- (BOOL)isLessThan:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] == NSOrderedAscending;
}

- (BOOL)isLessThanOrEqualTo:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] != NSOrderedDescending;
}

- (BOOL)isGreaterThan:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] == NSOrderedDescending;
}

- (BOOL)isGreaterThanOrEqualTo:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] != NSOrderedAscending;
}

- (BOOL)isEqualToDecimalNumber:(NSDecimalNumber *)decimalNumber
{
    return [self compare:decimalNumber] == NSOrderedSame;
}

@end

Unit Tests for good measure

@interface NSDecimalNumber_Comparison_Tests : XCTestCase

@end

@implementation NSDecimalNumber_Comparison_Tests

#pragma mark - isLessThan: tests

- (void)test_isLessThan_whenGreaterThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isLessThan:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isLessThan_whenLessThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isLessThan:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isLessThan_whenEqualTo_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertFalse(result);
}

#pragma mark - isLessThanOrEqualTo: tests

- (void)test_isLessThanOrEqualTo_whenGreaterThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isLessThanOrEqualTo:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isLessThanOrEqualTo_whenLessThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isLessThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isLessThanOrEqualTo_whenEqualTo_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isLessThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

#pragma mark - isGreaterThan: tests

- (void)test_isGreaterThan_whenGreaterThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isGreaterThan_whenLessThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isGreaterThan_whenEqualTo_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isGreaterThan:decimalNumberB];

    XCTAssertFalse(result);
}

#pragma mark - isGreaterThanOrEqualTo: tests

- (void)test_isGreaterThanOrEqualTo_whenGreaterThan_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isGreaterThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

- (void)test_isGreaterThanOrEqualTo_whenLessThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isGreaterThanOrEqualTo:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isGreaterThanOrEqualTo_whenEqualTo_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isGreaterThanOrEqualTo:decimalNumberB];

    XCTAssertTrue(result);
}

#pragma mark - isEqualToDecimalNumber: tests

- (void)test_isEqualToDecimalNumber_whenGreaterThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6779"];

    BOOL result = [decimalNumberA isEqualToDecimalNumber:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isEqualToDecimalNumber_whenLessThan_returnsNO
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6781"];

    BOOL result = [decimalNumberA isEqualToDecimalNumber:decimalNumberB];

    XCTAssertFalse(result);
}

- (void)test_isEqualToDecimalNumber_whenEqualTo_returnsYES
{
    NSDecimalNumber *decimalNumberA = [NSDecimalNumber decimalNumberWithString:@"4.6780"];
    NSDecimalNumber *decimalNumberB = [NSDecimalNumber decimalNumberWithString:@"4.6780"];

    BOOL result = [decimalNumberA isEqualToDecimalNumber:decimalNumberB];

    XCTAssertTrue(result);
}

@end


问:
Unsafe scripts using pelican
I'm trying to generate a website with pelican. When I run the localhost everything looks good. However, when I upload the content to my github pages and try to see the content it looks like the layout is all messed up. I'm using chrome and it seems like the content includes unauthenticated sources. If I choose the load unsafe scripts option with chrome then the website looks the same as the localhost.

If I look at the developer tool I get a bunch of errors like:

Mixed Content: The page at 'https://username.github.io/' was loaded over HTTPS, but requested an insecure stylesheet 'http://username.github.io/theme/css/bootstrap.simplex.min.css'. This request has been blocked; the content must be served over HTTPS.

Is there a way to "tell" pelican to use a secure stylesheet?

答:
A site loaded via HTTPS may not load unsecured content: in your case, loading a CSS file via HTTP. The reverse is fine: an unsecured site may load secured content. Hence, the probably easiest fix is to always use HTTPS, e.g. for all CSS files, images, etc.

According to this (closed) Pelican issue, SITEURL and/or RELATIVE_URLS are the relevant configuration options to set.

Title: Unsafe scripts using pelican


问:
Gulp livereload error in Chrome
I am trying to get LiveReload to work with Gulp and Chrome. I have installed the Chrome extension (v2.0.9), I have enabled "Allow Access to File URLs", which everyone says to do. I am running a simple PHP server with php -S 127.0.0.1:35729 -t dist. I have installed gulp-livereload and started the watch task with this code:

```<code>var gulp = require('gulp'),
    reload = require('gulp-livereload');

gulp.task('watch', function(){

    reload.listen(35729, function (err) {
        if (err) return console.log(err);
    });

    gulp.watch('dist/**').on('change', function(file) {
        reload.changed();
        console.log('PHP file changed' + ' (' + file.path + ')');
    });
});

gulp.task('default', function(){
    gulp.start('watch');
});
</code>```

I go to 127.0.0.1:35729 in Chrome. I enable LiveReload by clicking the extension button. I go and edit a file. Gulp says:

```<code> [13:28:48] undefined reloaded.
 PHP file changed (M:\path\to\file)
</code>```

The web page does not update. The console in Chrome has this lovely error when the page loads:

```<code>GET http://127.0.0.1:35729/livereload.js?ext=Chrome&extver=2.0.9 injected.js:116
LiveReloadInjected.doEnable injected.js:116
(anonymous function) injected.js:150
. many
. other
. lines
$Array.forEach.publicClass.(anonymous function) extensions::utils:94
dispatchOnMessage extensions::messaging:304
</code>```

I tried something crazy and put the livereload.js file in the root of my server and then I get this error instead:

WebSocket connection to 'ws://127.0.0.1:35729/livereload' failed:
  Connection closed before receiving a handshake response

Also, I would like to run LiveReload on a different port, but when I change the php server and Gulp watch to port 9999 I get this error:

WebSocket connection to 'ws://127.0.0.1:35729/livereload' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

答:
Also got error:

WebSocket connection to 'ws://127.0.0.1:35729/livereload' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

with gulp-livereload.
Resolved the issue by AdBlocker chrome extension disabling.

Title: Gulp livereload error in Chrome

Body:
I am trying to get LiveReload to work with Gulp and Chrome. I have installed the Chrome extension (v2.0.9), I have enabled "Allow Access to File URLs", which everyone says to do. I am running a simple PHP server with php -S 127.0.0.1:35729 -t dist. I have installed gulp-livereload and started the watch task with this code:

var gulp = require('gulp'),
    reload = require('gulp-livereload');

gulp.task('watch', function(){

    reload.listen(35729, function (err) {
        if (err) return console.log(err);
    });

    gulp.watch('dist/**').on('change', function(file) {
        reload.changed();
        console.log('PHP file changed' + ' (' + file.path + ')');
    });
});

gulp.task('default', function(){
    gulp.start('watch');
});

I go to 127.0.0.1:35729 in Chrome. I enable LiveReload by clicking the extension button. I go and edit a file. Gulp says:

 [13:28:48] undefined reloaded.
 PHP file changed (M:\path\to\file)

The web page does not update. The console in Chrome has this lovely error when the page loads:

GET http://127.0.0.1:35729/livereload.js?ext=Chrome&extver=2.0.9 injected.js:116
LiveReloadInjected.doEnable injected.js:116
(anonymous function) injected.js:150
. many
. other
. lines
$Array.forEach.publicClass.(anonymous function) extensions::utils:94
dispatchOnMessage extensions::messaging:304

I tried something crazy and put the livereload.js file in the root of my server and then I get this error instead:

WebSocket connection to 'ws://127.0.0.1:35729/livereload' failed:
  Connection closed before receiving a handshake response

Also, I would like to run LiveReload on a different port, but when I change the php server and Gulp watch to port 9999 I get this error:

WebSocket connection to 'ws://127.0.0.1:35729/livereload' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED


问:
User Interface inspiration for iPhone Apps
Does anyone have any suggestions for a site that potentially has some inspirational user interfaces for building my own iPhone Apps. It's straight forward to continually build out applications with the conventional UIKit widgets, but it does not set you apart from the competition. Some resources on how to build attractive interfaces is highly desired for inspiration. This is for someone with minimal Photoshop/Illustrator skills, but doesn't mind using sites such as iStockPhoto and working with custom views.</p>

答:
I spent a long time getting this one together, it's a full list of every single ios inspiration / mobile css gallery I could find on the internet. Let me know if you find any others so I can add them!

http://www.kintek.com.au/web-design-blog/iphone-mobile-css-gallery-listing-ios-inspiration/


问:
Getting Duplicates in Person ID and ASSIGNMENT_ID
This is the query I'm using:

```<code>select  DISTINCT  "HRG_GOAL_ACCESS"."PERSON_ID" as "PERSON_ID",
     "HRG_GOAL_ACCESS"."BUSINESS_GROUP_ID" as "BUSINESS_GROUP_ID",
     "HRG_GOALS"."GOAL_ID" as "GOAL_ID",
     "HRG_GOALS"."ASSIGNMENT_ID" as "ASSIGNMENT_ID",
     "HRG_GOALS"."GOAL_NAME" as "GOAL_NAME",
     "HRG_MASS_REQ_RESULTS"."ORGANIZATION_ID" as "ORGANIZATION_ID",
     "HRG_MASS_REQ_RESULTS"."RESULT_CODE" as "RESULT_CODE",
     "HRG_GOAL_PLN_ASSIGNMENTS"."CREATED_BY" as "CREATED_BY"
 from   "FUSION"."HRG_GOAL_PLN_ASSIGNMENTS" "HRG_GOAL_PLN_ASSIGNMENTS",
    "FUSION"."HRG_MASS_REQ_RESULTS" "HRG_MASS_REQ_RESULTS",
    "FUSION"."HRG_GOALS" "HRG_GOALS",
    "FUSION"."HRG_GOAL_ACCESS" "HRG_GOAL_ACCESS"
 where   "HRG_GOAL_ACCESS"."PERSON_ID"="HRG_GOALS"."PERSON_ID"
 and     "HRG_MASS_REQ_RESULTS"."PERSON_ID"="HRG_GOALS"."PERSON_ID"
 and     "HRG_GOAL_PLN_ASSIGNMENTS"."PERSON_ID"="HRG_MASS_REQ_RESULTS"."PERSON_ID"
</code>```

Output

```<code>PERSON_ID        BUSINESS_GROUP_ID GOAL_ID          ASSIGNMENT_ID  GOAL_NAME RESULT_CODE          CREATED_BY
---------------- ----------------- --------------- --------------- ------------------ -------------------- -------------------
300000048030404  1                 300000137711224 300000048033078 NANO_CLASS            SUCCESS anonymous  G_1
300000048030404  1                 300000137637946 300000048033078 INCREASE SALES BY 40% SUCCESS REDDI.SAREDDY G_1
300000048030404  1                 300000137637946 300000048033078 INCREASE SALES BY 40% SUCCESS CURTIS.FEITTY
</code>```

答:
Your output does not contain duplicates. You have more than one row for PERSON_ID (300000048030404) but that's because the master table (? HRG_GOAL_ACCESS ?) has multiple rows in its child tables.

Each row has different details, so the set is valid. There are different values of  HRG_GOALS.GOAL_ID, HRG_GOALS.GOAL_NAME and HRG_GOAL_PLN_ASSIGNMENTS.CREATED_BY.

If this response does not make you happy you need to explain more clearly what your desire output would look like. Alternatively you need to figure out your data model and understand why your query returns the data it does. Probably you have a missing join condition; the use of distinct could be hindering you in finding that out.

Body:
This is the query I'm using:

select  DISTINCT  "HRG_GOAL_ACCESS"."PERSON_ID" as "PERSON_ID",
     "HRG_GOAL_ACCESS"."BUSINESS_GROUP_ID" as "BUSINESS_GROUP_ID",
     "HRG_GOALS"."GOAL_ID" as "GOAL_ID",
     "HRG_GOALS"."ASSIGNMENT_ID" as "ASSIGNMENT_ID",
     "HRG_GOALS"."GOAL_NAME" as "GOAL_NAME",
     "HRG_MASS_REQ_RESULTS"."ORGANIZATION_ID" as "ORGANIZATION_ID",
     "HRG_MASS_REQ_RESULTS"."RESULT_CODE" as "RESULT_CODE",
     "HRG_GOAL_PLN_ASSIGNMENTS"."CREATED_BY" as "CREATED_BY"
 from   "FUSION"."HRG_GOAL_PLN_ASSIGNMENTS" "HRG_GOAL_PLN_ASSIGNMENTS",
    "FUSION"."HRG_MASS_REQ_RESULTS" "HRG_MASS_REQ_RESULTS",
    "FUSION"."HRG_GOALS" "HRG_GOALS",
    "FUSION"."HRG_GOAL_ACCESS" "HRG_GOAL_ACCESS"
 where   "HRG_GOAL_ACCESS"."PERSON_ID"="HRG_GOALS"."PERSON_ID"
 and     "HRG_MASS_REQ_RESULTS"."PERSON_ID"="HRG_GOALS"."PERSON_ID"
 and     "HRG_GOAL_PLN_ASSIGNMENTS"."PERSON_ID"="HRG_MASS_REQ_RESULTS"."PERSON_ID"

Output

PERSON_ID        BUSINESS_GROUP_ID GOAL_ID          ASSIGNMENT_ID  GOAL_NAME RESULT_CODE          CREATED_BY
---------------- ----------------- --------------- --------------- ------------------ -------------------- -------------------
300000048030404  1                 300000137711224 300000048033078 NANO_CLASS            SUCCESS anonymous  G_1
300000048030404  1                 300000137637946 300000048033078 INCREASE SALES BY 40% SUCCESS REDDI.SAREDDY G_1
300000048030404  1                 300000137637946 300000048033078 INCREASE SALES BY 40% SUCCESS CURTIS.FEITTY


问:
Pandas: get group-minima together with corresponding index value

Situation

As a simple example, consider the following pandas dataframe:

```<code>import pandas as pd

headers = ["city", "year", "births", "deaths", "immigrations", "emigrations"]
data = [
    ["Gotham", 2016, 1616, 1020, 1541, 1893],
    ["Gotham", 2015, 1785, 1708, 1604, 1776],
    ["Gotham", 2014, 1279, 1946, 1991, 1169],
    ["Gotham", 2013, 1442, 1932, 1960, 1580],
    ["Metropolis", 2016, 6405, 6393, 5390, 6797],
    ["Metropolis", 2015, 6017, 5492, 5647, 6994],
    ["Metropolis", 2014, 6644, 6893, 6759, 5149],
    ["Metropolis", 2013, 6902, 6160, 5294, 5112],
    ["Smallville", 2016, 43, 10, 29, 48],
    ["Smallville", 2015, 16, 21, 17, 19],
    ["Smallville", 2014, 20, 31, 28, 43],
    ["Smallville", 2013, 46, 11, 25, 25],
]

df = pd.DataFrame(data, columns=headers)
df.set_index(["city", "year"], inplace=True)
</code>```

which looks like this in console output:

```<code>                 births  deaths  immigrations  emigrations
city       year
Gotham     2016    1616    1020          1541         1893
           2015    1785    1708          1604         1776
           2014    1279    1946          1991         1169
           2013    1442    1932          1960         1580
Metropolis 2016    6405    6393          5390         6797
           2015    6017    5492          5647         6994
           2014    6644    6893          6759         5149
           2013    6902    6160          5294         5112
Smallville 2016      43      10            29           48
           2015      16      21            17           19
           2014      20      31            28           43
           2013      46      11            25           25
</code>```

Problem

For each data column I'd like to know the per-city minimum, together with the year in which it occurred. Basically, I'm trying to obtain a result dataframe that looks like this:

```<code>            births       deaths       immigrations       emigrations
               min  year    min  year          min  year         min  year
city
Gotham        1279  2014   1020  2016         1541  2016        1169  2014
Metropolis    6017  2015   5492  2015         5294  2013        5112  2013
Smallville      16  2015     10  2016           17  2015          19  2015
</code>```

Tried thus far

I was able to get the per-city minimum values as follows:

```<code>df.groupby(level="city").min()
</code>```

However after that I'm stuck. I haven't been able to find a way to also get the years corresponding to the minimum values. Does anyone here have a good idea for solving this?

答:
```<code>In [180]: df.reset_index(level=0).groupby('city').agg(['min','idxmin','max','idxmax'])
Out[180]:
           births                     deaths                     immigrations  \
              min idxmin   max idxmax    min idxmin   max idxmax          min
city
Gotham       1279   2014  1785   2015   1020   2016  1946   2014         1541
Metropolis   6017   2015  6902   2013   5492   2015  6893   2014         5294
Smallville     16   2015    46   2013     10   2016    31   2014           17

                               emigrations
           idxmin   max idxmax         min idxmin   max idxmax
city
Gotham       2016  1991   2014        1169   2014  1893   2016
Metropolis   2013  6759   2014        5112   2013  6994   2015
Smallville   2015    29   2016          19   2015    48   2016
</code>```

Body:
Situation

As a simple example, consider the following pandas dataframe:

import pandas as pd

headers = ["city", "year", "births", "deaths", "immigrations", "emigrations"]
data = [
    ["Gotham", 2016, 1616, 1020, 1541, 1893],
    ["Gotham", 2015, 1785, 1708, 1604, 1776],
    ["Gotham", 2014, 1279, 1946, 1991, 1169],
    ["Gotham", 2013, 1442, 1932, 1960, 1580],
    ["Metropolis", 2016, 6405, 6393, 5390, 6797],
    ["Metropolis", 2015, 6017, 5492, 5647, 6994],
    ["Metropolis", 2014, 6644, 6893, 6759, 5149],
    ["Metropolis", 2013, 6902, 6160, 5294, 5112],
    ["Smallville", 2016, 43, 10, 29, 48],
    ["Smallville", 2015, 16, 21, 17, 19],
    ["Smallville", 2014, 20, 31, 28, 43],
    ["Smallville", 2013, 46, 11, 25, 25],
]

df = pd.DataFrame(data, columns=headers)
df.set_index(["city", "year"], inplace=True)

which looks like this in console output:

                 births  deaths  immigrations  emigrations
city       year
Gotham     2016    1616    1020          1541         1893
           2015    1785    1708          1604         1776
           2014    1279    1946          1991         1169
           2013    1442    1932          1960         1580
Metropolis 2016    6405    6393          5390         6797
           2015    6017    5492          5647         6994
           2014    6644    6893          6759         5149
           2013    6902    6160          5294         5112
Smallville 2016      43      10            29           48
           2015      16      21            17           19
           2014      20      31            28           43
           2013      46      11            25           25

Problem

For each data column I'd like to know the per-city minimum, together with the year in which it occurred. Basically, I'm trying to obtain a result dataframe that looks like this:

            births       deaths       immigrations       emigrations
               min  year    min  year          min  year         min  year
city
Gotham        1279  2014   1020  2016         1541  2016        1169  2014
Metropolis    6017  2015   5492  2015         5294  2013        5112  2013
Smallville      16  2015     10  2016           17  2015          19  2015

Tried thus far

I was able to get the per-city minimum values as follows:

df.groupby(level="city").min()

However after that I'm stuck. I haven't been able to find a way to also get the years corresponding to the minimum values. Does anyone here have a good idea for solving this?


问:
ftp batch file script
Hoping someone can guide me / help me.

The issue, I have 2 servers one running a Ubuntu which has a website for clients to login and download / view reports. The other is a windows server 2012 R2 which creates / stores the reports. I need to move the files from the windows to the Ubuntu server so clients can view. The data is large currently 7gb and growing at 3 gb a year.

I need a batch file to connect using ftp and then copy the folder to a local folder. However it only needs to copy those files which have modified.

I have only ever written one batch file and I cant seem to find any ftp batch scripts which only copies modifed files.

Your my last resort as I cant seem to find a coder who knows batch script (its a dieing art). I have never used powershell so would not know where to start here.

Any help or advice please let me know.

Thanks
John

答:
You can do it with PowerShell with winscp. Exemple :</p>

```<code>try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "example.com"
    UserName = "user"
    Password = "mypassword"
    SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
}

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Upload files
    $transferOptions = New-Object WinSCP.TransferOptions
    $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

    $transferResult = $session.PutFiles("d:\toupload\*", "/home/user/", $False, $transferOptions)

    # Throw on any error
    $transferResult.Check()

    # Print results
    foreach ($transfer in $transferResult.Transfers)
    {
        Write-Host ("Upload of {0} succeeded" -f $transfer.FileName)
    }
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}

    exit 0
}
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}
</code>```

Title: ftp batch file script

Body:
You can do it with PowerShell with winscp. Exemple :

try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "example.com"
    UserName = "user"
    Password = "mypassword"
    SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
}

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Upload files
    $transferOptions = New-Object WinSCP.TransferOptions
    $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

    $transferResult = $session.PutFiles("d:\toupload\*", "/home/user/", $False, $transferOptions)

    # Throw on any error
    $transferResult.Check()

    # Print results
    foreach ($transfer in $transferResult.Transfers)
    {
        Write-Host ("Upload of {0} succeeded" -f $transfer.FileName)
    }
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}

    exit 0
}
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}


答:
In this line:

```<code>vec.push_back(Monster());
</code>```

You are creating a temporary object of type Monster, which is being copied to the vec. Because it is a temporary object it will be destroyed right after the statement ends at the semicolon. It will be destroyed after it was copied to vec.

```<code>vec.~Monster();
</code>```

This surely does not compile, if you wanted to clear your vector then use vec.clear()

In your code when you write Monster::setname(name);
most programmers will think you are setting a static variable. I hope you don't keep name of your monster as a static variable.

Another thing you need to fix in your code is to make sure it adheres to the rule of three (as it was in comments). Your Monster::n variable is a kind of resource which is being managed by Monster class, and to correctly manage it you need to appropriately modify it in all the constructors and operators which might create/destroy Monster class instance. Without describing it with long text below is a sample code which presents which constructors/operators are bing called in your code:

http://coliru.stacked-crooked.com/a/9184f137b7a90995

```<code>struct Monster {
    Monster() { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n++; }
    ~Monster() { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n--; }
    Monster(const Monster&) { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n++; }
    Monster& operator=(const Monster&) { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n++; return *this; }
    static int n;
};
int Monster::n;

int main()
{
    {
    std::vector<Monster> vec;
    std::cout << "-------------- START\n";
    vec.push_back(Monster());
    std::cout << "-------------- END\n";
    }
    std::cout << Monster::n; // should output 0
}

-------------- START
0:Monster::Monster()                  // temporary created
1:Monster::Monster(const Monster&)    // vector element is copy constructed
                                      //  from temporary here you have missed Monster::n++
2:Monster::~Monster()                 // temporary monster destroyed
-------------- END
1:Monster::~Monster()                 // this is a vector being destroyed
0                                     // this should always be 0, otherwise
                                      //  still something is missing.
</code>```

Title: C++ A constructor triggers a destructor

Body:
In this line:

vec.push_back(Monster());

You are creating a temporary object of type Monster, which is being copied to the vec. Because it is a temporary object it will be destroyed right after the statement ends at the semicolon. It will be destroyed after it was copied to vec.

vec.~Monster();

This surely does not compile, if you wanted to clear your vector then use vec.clear()

In your code when you write Monster::setname(name);
most programmers will think you are setting a static variable. I hope you don't keep name of your monster as a static variable.

Another thing you need to fix in your code is to make sure it adheres to the rule of three (as it was in comments). Your Monster::n variable is a kind of resource which is being managed by Monster class, and to correctly manage it you need to appropriately modify it in all the constructors and operators which might create/destroy Monster class instance. Without describing it with long text below is a sample code which presents which constructors/operators are bing called in your code:

http://coliru.stacked-crooked.com/a/9184f137b7a90995

struct Monster {
    Monster() { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n++; }
    ~Monster() { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n--; }
    Monster(const Monster&) { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n++; }
    Monster& operator=(const Monster&) { std::cout << n << ":" << __PRETTY_FUNCTION__ << "\n"; n++; return *this; }
    static int n;
};
int Monster::n;

int main()
{
    {
    std::vector<Monster> vec;
    std::cout << "-------------- START\n";
    vec.push_back(Monster());
    std::cout << "-------------- END\n";
    }
    std::cout << Monster::n; // should output 0
}

-------------- START
0:Monster::Monster()                  // temporary created
1:Monster::Monster(const Monster&)    // vector element is copy constructed
                                      //  from temporary here you have missed Monster::n++
2:Monster::~Monster()                 // temporary monster destroyed
-------------- END
1:Monster::~Monster()                 // this is a vector being destroyed
0                                     // this should always be 0, otherwise
                                      //  still something is missing.


问:
Change innertext of element dynamically inside for loop of a function
Issue : Upon entering a higher number like 10000, innertext of the new paragraph element is updated only after the for loop ends. Please help to make the innertext get updated for each number.

The increment function is called when an onchange event happens after sending a number as a input to the input element.

JAVASCRIPT :

```<code>function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    for (g = 1; g < count; g++) {
        stat.innerText = Number(g + 1) + " out of " + count + " records have been processed";
    }
}
</code>```

答:
I'm not suggesting that this is a good solution, but this should achieve the effect you're looking for</p>

```<code>function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    updateInnerText(0, count);
}

function updateInnerText(number, max){
    if(number < max){
        stat.innerText = Number(number + 1) + " out of " + count + " records have been processed";
        setTimeout(function(){
            updateInnerText(number+1, max);
        }, 500);
    }
}
</code>```

Body:
Issue : Upon entering a higher number like 10000, innertext of the new paragraph element is updated only after the for loop ends. Please help to make the innertext get updated for each number.

The increment function is called when an onchange event happens after sending a number as a input to the input element.

JAVASCRIPT :

function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    for (g = 1; g < count; g++) {
        stat.innerText = Number(g + 1) + " out of " + count + " records have been processed";
    }
}

Body:
I'm not suggesting that this is a good solution, but this should achieve the effect you're looking for

function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    updateInnerText(0, count);
}

function updateInnerText(number, max){
    if(number < max){
        stat.innerText = Number(number + 1) + " out of " + count + " records have been processed";
        setTimeout(function(){
            updateInnerText(number+1, max);
        }, 500);
    }
}