问:
Config.groovy in grails
In Config.groovy file we are assigning the value of appName to grails.project.groupId

grails.project.groupId = appName

My question is from where we are getting the value for appName.

Thanks in advance.

答:
You should use: grailsApplication.config.my.property

You would have access to all properties defined in config File.

Title: Config.groovy in grails


来源: stackexchange

问:
Show a new select for option selected dynamically jquery
```<code><div class="form-group">
   <label for="options">foo</label>
   <select class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
     <option value="opt1">test1</option>
     <option value="opt2">test2</option>
     <option value="opt3">test3</option>
  </select>
</div>
<script type="text/javascript">
  $("#scope_new_system").change(function() {
     var allSelected = new Array();
     $("#scope_new_system option:selected").each(function() {
       allSelected.push(this.value);
     });
  });
</script>
</code>```

I'm trying to dynamically generate a select with different options based on options selected on the multiple select named "options" above. For example if I click on option test 1 then a select element with options shows to select an option. If I select test 2 then another select shows because I now have 2 options selected. Finally if I unclicked test 1 select option goes away and if i do the same with test 2 it also goes away as well and i'm left with nothing selected. Please help!.

答:
As I pointed So the relation between the two selects just to show/hide it?? or select 2 values depending on select 1 values?? I didn't got that point

But sure Your 1st step is: To check for option:selected length by using $("option:selected" , this).length; or $(this).find("option:selected").length;

$("#scope_new_system").change(function() {
  var allSelected = [],
      num_of_selected_option = $("option:selected" , this).length;
  if(num_of_selected_option == 0){
    // if nothing selected
    alert('Nothing Selected');
  }else if(num_of_selected_option == 1){
    // if just one selected
    allSelected = [this.value];
    alert('Just one value selected : '+allSelected);
  }else if(num_of_selected_option > 1){
    // if more than one selected
    $("option:selected" , this).each(function(){
      allSelected.push(this.value);
    });
    alert('Selected Values : '+allSelected);
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="options">foo</label>
  <select id="scope_new_system" class="form-control"  name="options" multiple>
   <option value="">-- Choice --</option>
    <option value="opt1">test1</option>
    <option value="opt2">test2</option>
    <option value="opt3">test3</option>
  </select>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
   foo
   <select class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
     <option value="opt1">test1</option>
     <option value="opt2">test2</option>
     <option value="opt3">test3</option>
  </select>

I'm trying to dynamically generate a select with different options based on options selected on the multiple select named "options" above. For example if I click on option test 1 then a select element with options shows to select an option. If I select test 2 then another select shows because I now have 2 options selected. Finally if I unclicked test 1 select option goes away and if i do the same with test 2 it also goes away as well and i'm left with nothing selected. Please help!.

Body:
As I pointed So the relation between the two selects just to show/hide it?? or select 2 values depending on select 1 values?? I didn't got that point

But sure Your 1st step is: To check for option:selected length by using $("option:selected" , this).length; or $(this).find("option:selected").length;

$("#scope_new_system").change(function() {
  var allSelected = [],
      num_of_selected_option = $("option:selected" , this).length;
  if(num_of_selected_option == 0){
    // if nothing selected
    alert('Nothing Selected');
  }else if(num_of_selected_option == 1){
    // if just one selected
    allSelected = [this.value];
    alert('Just one value selected : '+allSelected);
  }else if(num_of_selected_option > 1){
    // if more than one selected
    $("option:selected" , this).each(function(){
      allSelected.push(this.value);
    });
    alert('Selected Values : '+allSelected);
   }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="options">foo</label>
  <select id="scope_new_system" class="form-control"  name="options" multiple>
   <option value="">-- Choice --</option>
    <option value="opt1">test1</option>
    <option value="opt2">test2</option>
    <option value="opt3">test3</option>
  </select>
</div>


问:
Change ng-bootstrap buttons activeClass?
In out AngularJs app, we changed the activeClass of buttons (as in toggle groups) to btn-default (from the default btn-primary), so all our CSS expects that.

I notice that ng-bootstrap also defaults to btn-primary but I don't see how (or if) that can be changed.

Is it possible for me to change the activeClass so my CSS is correct with the new components?

答:
ng-bootstrap make use of bootstrap 4. Bootstrap 4 includes six predefined button styles, each serving its own semantic purpose. But it doesn't include a btn-default but with btn-secondary class you achieve the same styling.

```<code><div class="btn-group" data-toggle="buttons">
  <label class="btn btn-secondary" [class.active]="model.left">
    <input type="checkbox" [(ngModel)]="model.left"> Left (pre-checked)
  </label>
  <label class="btn btn-secondary" [class.active]="model.middle">
    <input type="checkbox" [(ngModel)]="model.middle"> Middle
  </label>
  <label class="btn btn-secondary" [class.active]="model.right">
    <input type="checkbox" [(ngModel)]="model.right"> Right
  </label>
</div>
</code>```

If you still prefer to use the btn-default then you can make a class with that name in your component style and use it.

Body:
ng-bootstrap make use of bootstrap 4. Bootstrap 4 includes six predefined button styles, each serving its own semantic purpose. But it doesn't include a btn-default but with btn-secondary class you achieve the same styling.

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-secondary" [class.active]="model.left">
    <input type="checkbox" [(ngModel)]="model.left"> Left (pre-checked)
  </label>
  <label class="btn btn-secondary" [class.active]="model.middle">
    <input type="checkbox" [(ngModel)]="model.middle"> Middle
  </label>
  <label class="btn btn-secondary" [class.active]="model.right">
    <input type="checkbox" [(ngModel)]="model.right"> Right
  </label>
</div>

If you still prefer to use the btn-default then you can make a class with that name in your component style and use it.


问:
How to check if remote branch exists on a given remote repository?
I need to do a subtree merge for a specific branch, if it exists on a given remote repository. The problem is that the remote repository is not checked out locally, so I can't use git branch -r. All I have is a remote address, something like this  https://github.com/project-name/project-name.git.  Is there a way to list remote branches just by a remote address?  I couldn't find anything usefull :(

答:
```<code>$ git ls-remote --heads origin <branch> | wc -l
</code>```

works most of the time.

But will not work if branch matches partially as below,

```<code>$ git branch -a
creative/dev
qa/dev

$ git ls-remote --heads origin dev | wc -l
2
</code>```

Use

```<code>git ls-remote --heads origin <branch> | \
    cut -d$'\t' -f2 | \
    sed 's,refs/heads/,,' | \
    grep ^<branch>$ | wc -l
</code>```

if you want a reliable way.

If you want to use in script and do not want to assume origin as default remote then

```<code>git ls-remote --heads $(git remote | head -1) "$branch" | \
    cut -d$'\t' -f2 | \
    sed 's,refs/heads/,,' | \
    grep ^"$branch"$ | wc -l
</code>```

should work.

Note that git branch -a | grep ... is not reliable as it may be a while since the last fetch was run.

Body:
$ git ls-remote --heads origin <branch> | wc -l

works most of the time.

But will not work if branch matches partially as below,

$ git branch -a
creative/dev
qa/dev

$ git ls-remote --heads origin dev | wc -l
2

Use

git ls-remote --heads origin <branch> | \
    cut -d$'\t' -f2 | \
    sed 's,refs/heads/,,' | \
    grep ^<branch>$ | wc -l

if you want a reliable way.

If you want to use in script and do not want to assume origin as default remote then

git ls-remote --heads $(git remote | head -1) "$branch" | \
    cut -d$'\t' -f2 | \
    sed 's,refs/heads/,,' | \
    grep ^"$branch"$ | wc -l

should work.

Note that git branch -a | grep ... is not reliable as it may be a while since the last fetch was run.


问:
Convert a list of list of objects to string
I've a list of list of objects like List<List<Event>>.

How can I override ToString() such that each internal list will be shown in a single line of command prompt?

```<code>public override string ToString(List<List<Event>>)
{
     return ?
}
</code>```

答:
```<code>public override string ToString(List<List<Event>> events)
{
     return string.Join(", ",
         events.SelectMany((list) => list)
             .Select((ev) => ev.ToString()));
}
</code>```

Take the list of lists and flatten it with .SelectMany()

Convert each Event to a string re-using .ToString()

Join the array of strings into one string with comma separated (can be changed).

Edit 1
Given that the base method signature is string ToString() without any parameters you probably need to reference a field or property in your class and not define a separate string ToString(List<List<Event>> events).

```<code>public class SO
{

    List<List<Event>> events;

    public override string ToString()
    {
         return string.Join(", ",
             events.SelectMany((list) => list)
                 .Select((ev) => ev.ToString()));
    }
}
</code>```

Body:
I've a list of list of objects like List<List<Event>>.

How can I override ToString() such that each internal list will be shown in a single line of command prompt?

public override string ToString(List<List<Event>>)
{
     return ?
}

Body:
public override string ToString(List<List<Event>> events)
{
     return string.Join(", ",
         events.SelectMany((list) => list)
             .Select((ev) => ev.ToString()));
}

Take the list of lists and flatten it with .SelectMany()

Convert each Event to a string re-using .ToString()

Join the array of strings into one string with comma separated (can be changed).

Edit 1
Given that the base method signature is string ToString() without any parameters you probably need to reference a field or property in your class and not define a separate string ToString(List<List<Event>> events).

public class SO
{

    List<List<Event>> events;

    public override string ToString()
    {
         return string.Join(", ",
             events.SelectMany((list) => list)
                 .Select((ev) => ev.ToString()));
    }
}


问:
How to print a txt file in Python3 if it exists in a directory?
I have something like this:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Print a file to a default printer
last edited: June 2017
"""

import os
import sys
import subprocess
#import win32print

if sys.platform == "linux" or sys.platform == "linux2":
    # linux
    lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
    lpr.stdin.write("This is a print-test sentence")
elif sys.platform == "darwin":
    # MAC OS X
    pass
elif sys.platform == "win32":
    # Windows
    os.startfile("C:/temp/temp.txt", "print")
</code>```

I would like to know how to print a file temp.txt in Linux like in the Win example, how to print any *.txt file if it exists in the directory where the script (it should be only one) is and how to change encoding of that file (I need DOS 852 code page)?

答:
To check for file existence on any system, still the best inbuilt method is I think os.path.isfile( filepath ). If above code works for linux and windows you could do it like this:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Print a file to a default printer
last edited: June 2017
"""
import os
import sys
import subprocess
#import win32print

filepath = 'some_file_path'
if os.path.isfile(filepath):
    if sys.platform == "linux" or sys.platform == "linux2":
        # linux
        lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
        with open(filepath,'r') as file:
            lpr.stdin.write(file.read())

    elif sys.platform == "darwin":
        # MAC OS X
        pass
    elif sys.platform == "win32":
        # Windows
        os.startfile(filepath, "print")
</code>```

Body:
I have something like this:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Print a file to a default printer
last edited: June 2017
"""

import os
import sys
import subprocess
#import win32print

if sys.platform == "linux" or sys.platform == "linux2":
    # linux
    lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
    lpr.stdin.write("This is a print-test sentence")
elif sys.platform == "darwin":
    # MAC OS X
    pass
elif sys.platform == "win32":
    # Windows
    os.startfile("C:/temp/temp.txt", "print")

I would like to know how to print a file temp.txt in Linux like in the Win example, how to print any *.txt file if it exists in the directory where the script (it should be only one) is and how to change encoding of that file (I need DOS 852 code page)?

Body:
To check for file existence on any system, still the best inbuilt method is I think os.path.isfile( filepath ). If above code works for linux and windows you could do it like this:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Print a file to a default printer
last edited: June 2017
"""
import os
import sys
import subprocess
#import win32print

filepath = 'some_file_path'
if os.path.isfile(filepath):
    if sys.platform == "linux" or sys.platform == "linux2":
        # linux
        lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
        with open(filepath,'r') as file:
            lpr.stdin.write(file.read())

    elif sys.platform == "darwin":
        # MAC OS X
        pass
    elif sys.platform == "win32":
        # Windows
        os.startfile(filepath, "print")


问:
How to Delete data in Both Tables in SQL Server?
I have a table TableA, its PK is AId. I have another table TableB, its only column is BId. BId is actually is a subset of AId. Now, we can not use FK (because of this and that reason).

How can I Delete the TOP 1000 rows in TableB and its related rows (if the same id exists in table A) in table A?

A solution is to SELECT TOP 100) from tableB and save to temp table, then use it to delete the data in table A, then delete rows in tableB.

But it should have a more efficient way to do this.

I also tried:

```<code>DELETE TOP (1000) FROM tableA WHERE AId IN (SELECT BId FROM TableB)
</code>```

But how can I make sure the top 1000 BId got deleted?

Thanks

答:
other possible ways:

1) DELETE TOP (1000) from TableB with Output clause (into temp table), and then Delete from TableA where AID is in that output table.

or

2) Implement DELETE trigger for TableB, so when any rows are deleted from TableB, they are also deleted from TableA automatically.

Body:
I have a table TableA, its PK is AId. I have another table TableB, its only column is BId. BId is actually is a subset of AId. Now, we can not use FK (because of this and that reason).

How can I Delete the TOP 1000 rows in TableB and its related rows (if the same id exists in table A) in table A?

A solution is to SELECT TOP 100) from tableB and save to temp table, then use it to delete the data in table A, then delete rows in tableB.

But it should have a more efficient way to do this.

I also tried:

DELETE TOP (1000) FROM tableA WHERE AId IN (SELECT BId FROM TableB)

But how can I make sure the top 1000 BId got deleted?

Thanks


问:
How to create a custom ribbon tab in MS Project 2016?
I have two VBA macros that create a custom tab in MS Project 2013. The three macros are:

```<code>Private Sub Project_Open(ByVal pj As Project)
     AddEVMRibbon
End Sub

Private Sub removeEVMRibbon()
    ribbonXml = "<mso:customUI  xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & "<mso:ribbon></mso:ribbon></mso:customUI>"
    ActiveProject.SetCustomUI (ribbonXml)
End Sub

Private Sub AddEVMRibbon()
Dim ribbonXml As String

    ribbonXml = "<mso:customUI xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">"
    ribbonXml = ribbonXml + "  <mso:ribbon>"
    ribbonXml = ribbonXml + "    <mso:qat/>"
    ribbonXml = ribbonXml + "    <mso:tabs>"
    ribbonXml = ribbonXml + "      <mso:tab id=""macroTab"" label=""EVM"" insertAfterQ=""mso:TabFormat"">"
    ribbonXml = ribbonXml + "        <mso:group id=""testGroup"" label=""Test"" autoScale=""true"">"
    ribbonXml = ribbonXml + "          <mso:button id=""export_to_excel"" label=""Set EVM Calc Method"" "
    ribbonXml = ribbonXml + "imageMso=""DiagramTargetInsertClassic"" onAction=""Set_EVM_Method""/>"
    ribbonXml = ribbonXml + "          <mso:button id=""get_evm_method"" label=""EVM to Excel"" "
    ribbonXml = ribbonXml + "imageMso=""DiagramTargetInsertClassic"" onAction=""evm_to_excel""/>"
    ribbonXml = ribbonXml + "        </mso:group>"
    ribbonXml = ribbonXml + "      </mso:tab>"
    ribbonXml = ribbonXml + "    </mso:tabs>"
    ribbonXml = ribbonXml + "  </mso:ribbon>"
    ribbonXml = ribbonXml + "</mso:customUI>"

    ActiveProject.SetCustomUI (ribbonXml)

End Sub
</code>```

These work correctly in MS Project 2013, but today I got the opportunity to run them with MS Project 2016, and they fail, rather spectacularly.

In both Project 2013 and 2016 the EVM Tab appears correctly and the two options, "Set EVM Method" and "EVM to Excel," appear when that custom tab is clicked.

In Project 2013 clicking on an option executes the VBA macro associated with the option in the XML. In Project 2016 simply hovering the mouse over either of the two options causes Project to fail immediately, giving me the "Microsoft Project has stopped working" then "Microsoft Project is restarting" messages.

I never have a chance to click the option, as it fails immediately when the cursor touches the option.

Has something changed between Project 2013 and 2016 that would cause this custom ribbon bar tab to fail in 2016? I have not been able to find anything referring to such a change.

Do custom tabs and their options in Project 2016 need to be coded differently than in 2013? Any and all help will be appreciated.

答:
Updating project fixed the issue for me.
The link below is to the current Project 2016 update. What exactly in the update fixed the problem is unknown.
https://support.microsoft.com/en-us/help/4020152/may-9-2017-update-for-microsoft-office</p>

Body:
I have two VBA macros that create a custom tab in MS Project 2013. The three macros are:

Private Sub Project_Open(ByVal pj As Project)
     AddEVMRibbon
End Sub

Private Sub removeEVMRibbon()
    ribbonXml = "<mso:customUI  xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & "<mso:ribbon></mso:ribbon></mso:customUI>"
    ActiveProject.SetCustomUI (ribbonXml)
End Sub

Private Sub AddEVMRibbon()
Dim ribbonXml As String

    ribbonXml = "<mso:customUI xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">"
    ribbonXml = ribbonXml + "  <mso:ribbon>"
    ribbonXml = ribbonXml + "    <mso:qat/>"
    ribbonXml = ribbonXml + "    <mso:tabs>"
    ribbonXml = ribbonXml + "      <mso:tab id=""macroTab"" label=""EVM"" insertAfterQ=""mso:TabFormat"">"
    ribbonXml = ribbonXml + "        <mso:group id=""testGroup"" label=""Test"" autoScale=""true"">"
    ribbonXml = ribbonXml + "          <mso:button id=""export_to_excel"" label=""Set EVM Calc Method"" "
    ribbonXml = ribbonXml + "imageMso=""DiagramTargetInsertClassic"" onAction=""Set_EVM_Method""/>"
    ribbonXml = ribbonXml + "          <mso:button id=""get_evm_method"" label=""EVM to Excel"" "
    ribbonXml = ribbonXml + "imageMso=""DiagramTargetInsertClassic"" onAction=""evm_to_excel""/>"
    ribbonXml = ribbonXml + "        </mso:group>"
    ribbonXml = ribbonXml + "      </mso:tab>"
    ribbonXml = ribbonXml + "    </mso:tabs>"
    ribbonXml = ribbonXml + "  </mso:ribbon>"
    ribbonXml = ribbonXml + "</mso:customUI>"

    ActiveProject.SetCustomUI (ribbonXml)

End Sub

These work correctly in MS Project 2013, but today I got the opportunity to run them with MS Project 2016, and they fail, rather spectacularly.

In both Project 2013 and 2016 the EVM Tab appears correctly and the two options, "Set EVM Method" and "EVM to Excel," appear when that custom tab is clicked.

In Project 2013 clicking on an option executes the VBA macro associated with the option in the XML. In Project 2016 simply hovering the mouse over either of the two options causes Project to fail immediately, giving me the "Microsoft Project has stopped working" then "Microsoft Project is restarting" messages.

I never have a chance to click the option, as it fails immediately when the cursor touches the option.

Has something changed between Project 2013 and 2016 that would cause this custom ribbon bar tab to fail in 2016? I have not been able to find anything referring to such a change.

Do custom tabs and their options in Project 2016 need to be coded differently than in 2013? Any and all help will be appreciated.


问:
Mercurial and SQL Server Management Studio GUI plugins?
Does no such plugin exist?

So to be clear, I realize that RedGate has their own SSMS SCC app, and I realize that VSS2k5 will integrate in. I'm looking to stay with Hg as that's where my source already is, and I'ld like to find something that my team can stay consistent with on their tools.

As is, I guess I'm going to have to just run it through TortoiseHg and a folder with manual maintenance. Which isn't terrible, but naturally it would be nicer if there was an app pre-existing that I could consume.

And no, I don't have the time or inclination to write one myself. Not before Summer 2011.

Thoughts or ideas?

答:
There are two versions of HgScc plugin:

HgScc - uses old MS SCCI API, works with MS VS2005/2008/2010 and with some third party IDEs. Last version of this plugin was released in 2008. It is not actively developed anymore, because MS SCCI API is very limiting and does not allow a tight integration with Visual Studio.

HgSccPackage - uses MS SCC Package, works only with MS VS2008/2010. This version of plugin currently in active development.

To get the first version of HgScc follow the instructions here:
MSSCCI compliant Mercurial client

ContentLicense: CC BY-SA 2.5


问:
Make a hyperlink to compose a new email with the receive's email is specified
Hi I'm developing a UWP application with C# and XAML and in the about page I want to have a hyperlink with its content set to "Feedback" and whenever the users click on it, I want it to open their mail app or open the browser and opening they're email account to compose me a message with my email in the To textbox!
What NavigateUri should I write to achieve this?</p>

答:
As far as I know you achieve this by mailto:theEmail@dresse.toWriteTo.

Atleast that is the URL hyperlinks like that actually show.


问:
Eclipse - How to select the Java methods to compile when building the Jar file?
I have finished a Java project in Eclipse and i want to export 2 Jar versions for it. One is a Trial version and the other is a Pro version.

Is there a way in Eclipse to command it to build the Jar using specific classes or methods for the Trial version and when building the Pro version use other classes or methods?

What i'm trying to do is omitting some code in the Trial version to make it secure and prevent it from being hacked as it has happened before in one of my programs.

答:
The method I'd try first would be to shell script this. You can then invoke the scripts using "External Commands" in Eclipse. Thus, you can hook-up your scripts in to Eclipse there.

Going a few thousand steps further, if you use something like github (or gitlab, like me) you can setup the CI tools to run such scripts for you too.

Anyway, there may be better methods, this is what I'd start with based on what I personally know. I've had good success with my own shell scripts invoked by Eclipse. But you may have different needs.


问:
Overload >> in inherited class c++
I've overload the operator << in a inherited class, it's working fine, however when I try to overload  the operator >> , it shows lots of errors.
What's my mistake?

```<code>class Base{
private:
    virtual std::ostream& print(std::ostream&) const = 0;
    virtual std::istream& read(std::istream&);
protected:
    //atributes
public:
    //other functions
    friend std::ostream& operator << (std::ostream& os, const Base& b) {
        return b.print(os);
    }
    friend std::istream& operator >> (std::istream& is, Base& bb) {
        return bb.read(is);
    }
};

class Inherited: public Base{
private:
    //atributes
    std::ostream& print(std::ostream& os) const {
        //things I want to print
    }
    std::istream& read(std::istream& is){
        //things I want to read
        return is;
    }
public:
    //other functions
};
</code>```

Defining istream as virtual pure (virtual...const = 0;) also doesn't work.

答:
You did not declare read to be pure virtual in Base.

```<code>virtual std::istream& read(std::istream&);
</code>```

With the above declaration, the compiler/linker expect an implementation of the function in the base class. To fix the problem, make the function a pure virtual function of Base.

```<code>virtual std::istream& read(std::istream&) = 0;
</code>```

PS Note that it is not a const member function.

Title: Overload >> in inherited class c++

Body:
I've overload the operator << in a inherited class, it's working fine, however when I try to overload  the operator >> , it shows lots of errors.
What's my mistake?

class Base{
private:
    virtual std::ostream& print(std::ostream&) const = 0;
    virtual std::istream& read(std::istream&);
protected:
    //atributes
public:
    //other functions
    friend std::ostream& operator << (std::ostream& os, const Base& b) {
        return b.print(os);
    }
    friend std::istream& operator >> (std::istream& is, Base& bb) {
        return bb.read(is);
    }
};

class Inherited: public Base{
private:
    //atributes
    std::ostream& print(std::ostream& os) const {
        //things I want to print
    }
    std::istream& read(std::istream& is){
        //things I want to read
        return is;
    }
public:
    //other functions
};

Defining istream as virtual pure (virtual...const = 0;) also doesn't work.

Body:
You did not declare read to be pure virtual in Base.

virtual std::istream& read(std::istream&);

With the above declaration, the compiler/linker expect an implementation of the function in the base class. To fix the problem, make the function a pure virtual function of Base.

virtual std::istream& read(std::istream&) = 0;

PS Note that it is not a const member function.


问:
name 'urlpatterns' is not defined when doing translation (+= i18n_patterns)
I want to add a language prefix in URL patterns just like the django documentation homepage. Following this example my urls.py looks like this:

```<code>from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin

from myapp import views
from myapp.views import MyFirstView, MySecondView

myapp_patterns = [
    url(r'^$', views.CategoryView, name='index'),
    url(r'^(?P<name>[a-zA-Z0-9_]+)/$', MyFirstView.as_view(), name='detail'),
    url(r'^(?P<name>[a-zA-Z0-9_]+)/mysecond_view/$', MySecondView, name='mysecond_view')
]

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^categories/', include(myapp_patterns)),
    url(r'^', views.LandingView),
]
</code>```

This works but now when I add += i18n_patterns

```<code>urlpatterns += i18n_patterns [
    url(r'^admin/', admin.site.urls),
    url(r'^categories/', include(myapp_patterns)),
    url(r'^', views.LandingView),
]
</code>```

I get the error: NameError: name 'urlpatterns' is not defined

I did add the LocalMiddleware:

```<code>MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]
</code>```

as well as this:

```<code>LANGUAGE_CODE = 'en-us'

USE_I18N = True

USE_L10N = True

LOCALE_PATHS = (
        os.path.join(BASE_DIR, 'locale'),
)
</code>```

I don't understand how urlpatterns all of the sudden is not defined anymore.
What am I doing wrong here?

答:
Primarily because of +=. There's no previous definition of urlpatterns.

You should start of with assignment = to define it.

Body:
I want to add a language prefix in URL patterns just like the django documentation homepage. Following this example my urls.py looks like this:

from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin

from myapp import views
from myapp.views import MyFirstView, MySecondView

myapp_patterns = [
    url(r'^$', views.CategoryView, name='index'),
    url(r'^(?P<name>[a-zA-Z0-9_]+)/$', MyFirstView.as_view(), name='detail'),
    url(r'^(?P<name>[a-zA-Z0-9_]+)/mysecond_view/$', MySecondView, name='mysecond_view')
]

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^categories/', include(myapp_patterns)),
    url(r'^', views.LandingView),
]

This works but now when I add += i18n_patterns

urlpatterns += i18n_patterns [
    url(r'^admin/', admin.site.urls),
    url(r'^categories/', include(myapp_patterns)),
    url(r'^', views.LandingView),
]

I get the error: NameError: name 'urlpatterns' is not defined

I did add the LocalMiddleware:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

as well as this:

LANGUAGE_CODE = 'en-us'

USE_I18N = True

USE_L10N = True

LOCALE_PATHS = (
        os.path.join(BASE_DIR, 'locale'),
)

I don't understand how urlpatterns all of the sudden is not defined anymore.
What am I doing wrong here?


问:
How to set array to default like definited?
how can i reset array to default? I have some functions that's modifying array and i want to set it like in Dim after click reset button.  </p>

```<code>Dim array() As String = {"H", "C", "N", "O", "Na", "Cl", "Fe", "Mg", "Cu", "Ag", "Au", "Pt", "K", "Pb", "Ca", "S", "P", "Al", "Si", "Zn", "Sn", "I"}

Private Sub reset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles reset.Click
   array() = {"H", "C", "N", "O", "Na", "Cl", "Fe", "Mg", "Cu", "Ag", "Au", "Pt", "K", "Pb", "Ca", "S", "P", "Al", "Si", "Zn", "Sn", "I"}
' it's not working
End Sub
</code>```

Body:
how can i reset array to default? I have some functions that's modifying array and i want to set it like in Dim after click reset button.

Dim array() As String = {"H", "C", "N", "O", "Na", "Cl", "Fe", "Mg", "Cu", "Ag", "Au", "Pt", "K", "Pb", "Ca", "S", "P", "Al", "Si", "Zn", "Sn", "I"}

Private Sub reset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles reset.Click
   array() = {"H", "C", "N", "O", "Na", "Cl", "Fe", "Mg", "Cu", "Ag", "Au", "Pt", "K", "Pb", "Ca", "S", "P", "Al", "Si", "Zn", "Sn", "I"}
' it's not working
End Sub

Body:
Lose the parentheses:

   array = {"H", "C", "N", "O", "Na", "Cl", "Fe", "Mg", "Cu", "Ag", "Au", "Pt", "K", "Pb", "Ca", "S", "P", "Al", "Si", "Zn", "Sn", "I"}


问:
Arraylist user selector
Okay, so I am trying to make a simple secret Santa program, they type in their name, it then removes them from the arraylist, and randomizes the arraylist and outputs the text to a text box, or should I say, I need it to.

```<code>private void button1_Click(object sender, EventArgs e)
{
    ArrayList NameSel = new ArrayList();
    NameSel.Add("name1");
    NameSel.Add("name2");
    NameSel.Add("name3");;
    if (textBox1.Text == "name1")
    {
        NameSel.Remove("name1");
        Random rand = new Random();
        int randoms = rand.Next(NameSel.Count);
        string textbox = NameSel[randoms];
        textBox2.Text = textbox;
    }
</code>```

The problem lies at textbox, specifically "NameSel[randoms];".

Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

I don't work with arraylists at all, for this I usually a string, for example

```<code>string[] names = new string[]
{
     "name1",
     "name2",
     "name3",
};
</code>```

And I tested, and that works, but as far as I am aware, I cant use stringname.remove("name1") or any equivalent, so I am out of my comfort zone, Any help that doesn't massively edit the original code is appreciated!

答:
Your error output is very telling, it's stating you need a cast to a String if you are attempting to pull a value from your list and assign it to a String reference variable.

I.E. string textbox = (string)NameSel[randoms];

You should also be able to take advantage of generics, when declaring your ArrayList in the first place. new ArrayList<String>(). This way the program knows you want a collection of strings vs objects(then cast isn't necessary).

Title: Arraylist user selector

Body:
Okay, so I am trying to make a simple secret Santa program, they type in their name, it then removes them from the arraylist, and randomizes the arraylist and outputs the text to a text box, or should I say, I need it to.

private void button1_Click(object sender, EventArgs e)
{
    ArrayList NameSel = new ArrayList();
    NameSel.Add("name1");
    NameSel.Add("name2");
    NameSel.Add("name3");;
    if (textBox1.Text == "name1")
    {
        NameSel.Remove("name1");
        Random rand = new Random();
        int randoms = rand.Next(NameSel.Count);
        string textbox = NameSel[randoms];
        textBox2.Text = textbox;
    }

The problem lies at textbox, specifically "NameSel[randoms];".

Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

I don't work with arraylists at all, for this I usually a string, for example

string[] names = new string[]
{
     "name1",
     "name2",
     "name3",
};

And I tested, and that works, but as far as I am aware, I cant use stringname.remove("name1") or any equivalent, so I am out of my comfort zone, Any help that doesn't massively edit the original code is appreciated!


答:
```<code>    public override string ToString(List<List<Event>> listOflistOfEvents)
    {
        StringBuilder result = new StringBuilder();
        listOflistOfEvents.ForEach(delegate(List<Event> listOfEvents)
        {
            result.AppendLine();
            listOfEvents.ForEach(events => result.Append(events + ","));
        });
        return result.ToString();
    }
</code>```

Title: Convert a list of list of objects to string


问:
Assign char to array of chars inside an struct thats inside a array of structs thats inside a array of structs thats inside a array of struct
I need to simulate a hard disk for a college assignment. I have a char array inside a struct, another struct has an array of the last struct and so on. The teacher asked for it to be done this way.

```<code>typedef struct block {
    unsigned char bytes_s[512];
} block;

typedef struct  sectror_array {
   block sector[60];
} sectror_array;

typedef struct track_array {
    sectror_array track[5];
} track_array;
</code>```

All of that in a

```<code>track_array cylinder[10];
</code>```

declared as global.

my problem is that i can't seem to access any of these. In my code, i use a loop to assign a variable to the "byte" and then try to print it

```<code>int c=0, t=0, s=0, b=0;
  while(c<11){
    if(b==512){
      b=0;
      s++;
      if(s==60){
        s=0;
        t++;
        if(t==5){
          t=0;
          c++;
          if(c==10){
            return;
          }
        }
      }
    }
    cylinder[c].track[t].sector[s].bytes_s[b]=0;
    b++;
    printf("%d %d %d %d, %c\n",c, t, s ,b,
    cylinder[c].track[t].sector[s].bytes_s[b]);
</code>```

But it shows nothing even as i tryed to assign 'a' to every byte.

Yet it compiles and runs without crashes.

Never had to work with such before and i'm out of ideas of how to fix this.

https://github.com/diceEviscerator/trabOA

code is my_drive.cpp

saved as cpp but is pure c (needed to save as cpp to run gtest)

答:
So far the problem is that i was tring to print the character after the one i changed

```<code>cylinder[c].track[t].sector[s].bytes_s[b]=0;
b++;
printf("%d %d %d %d, %c\n",c, t, s ,b, cylinder[c].track[t].sector[s].bytes_s[b]);
</code>```

where should be:

```<code>cylinder[c].track[t].sector[s].bytes_s[b]=0;
printf("%d %d %d %d, %c\n",c, t, s ,b, cylinder[c].track[t].sector[s].bytes_s[b]);
b++;
</code>```

there are still problems with this code but this problem seems solved. It wasn't clear to me at the time I posted and I wish i could delete since it is so simple thus is no new knowledge , but i can't.

Body:
I need to simulate a hard disk for a college assignment. I have a char array inside a struct, another struct has an array of the last struct and so on. The teacher asked for it to be done this way.

typedef struct block {
    unsigned char bytes_s[512];
} block;

typedef struct  sectror_array {
   block sector[60];
} sectror_array;

typedef struct track_array {
    sectror_array track[5];
} track_array;

All of that in a

track_array cylinder[10];

declared as global.

my problem is that i can't seem to access any of these. In my code, i use a loop to assign a variable to the "byte" and then try to print it

int c=0, t=0, s=0, b=0;
  while(c<11){
    if(b==512){
      b=0;
      s++;
      if(s==60){
        s=0;
        t++;
        if(t==5){
          t=0;
          c++;
          if(c==10){
            return;
          }
        }
      }
    }
    cylinder[c].track[t].sector[s].bytes_s[b]=0;
    b++;
    printf("%d %d %d %d, %c\n",c, t, s ,b,
    cylinder[c].track[t].sector[s].bytes_s[b]);

But it shows nothing even as i tryed to assign 'a' to every byte.

Yet it compiles and runs without crashes.

Never had to work with such before and i'm out of ideas of how to fix this.

https://github.com/diceEviscerator/trabOA

code is my_drive.cpp

saved as cpp but is pure c (needed to save as cpp to run gtest)

Body:
So far the problem is that i was tring to print the character after the one i changed

cylinder[c].track[t].sector[s].bytes_s[b]=0;
b++;
printf("%d %d %d %d, %c\n",c, t, s ,b, cylinder[c].track[t].sector[s].bytes_s[b]);

where should be:

cylinder[c].track[t].sector[s].bytes_s[b]=0;
printf("%d %d %d %d, %c\n",c, t, s ,b, cylinder[c].track[t].sector[s].bytes_s[b]);
b++;

there are still problems with this code but this problem seems solved. It wasn't clear to me at the time I posted and I wish i could delete since it is so simple thus is no new knowledge , but i can't.


问:
Setup of ember-service-worker-cache-fallback to sync data
I'm a beginner in ember and service workers. My goal is to setup a simple ember app that works offline. I basically have a list of elements that are available through an API (GET/POST).

When I'm online, everything works as expected. I can GET the list and POST new items. When I'm offline the app works, but network requests are not executed once I go back online. All network requests are actually executed while I'm offline (and obviously fail). I would expect that the service worker caches the network requests and executes them only once I'm back online. Is this wrong?

Here some information about my setup:

Ember version:

ember-cli: 2.13.1

node: 7.10.0

os: darwin x64

Service Worker Add-ons (as listed in app/package.json):

```<code>"ember-service-worker": "^0.6.6",
"ember-service-worker-asset-cache": "^0.6.1",
"ember-service-worker-cache-fallback": "^0.6.1",
"ember-service-worker-index": "^0.6.1",
</code>```

I should probably also mention that I use ember-django-adapter in version 1.1.3.

This is my app/ember-cli-build.js

```<code>var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    'esw-cache-fallback': {
      // RegExp patterns specifying which URLs to cache.
      patterns: [
        'http://localhost:8000/api/v1/(.*)',
      ],

      // changing this version number will bust the cache
      version: '1'
    }
  });

  return app.toTree();
};
</code>```

My network requests (GET/POST) go to http://localhost:8000/api/v1/properties/.

This is my app/adapters/applications.js

```<code>import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {

  namespace: 'api/v1',
  host: 'http://localhost:8000',
  authorizer: 'authorizer:token',
  headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
  buildURL: function(type, id, record) {
  return this._super(type, id, record) + '/';
  }
});
</code>```

The service worker registers when I open the app:

```<code>(function () {
  'use strict';

  self.addEventListener('install', function installEventListenerCallback(event) {
      return self.skipWaiting();
    });

    self.addEventListener('activate', function installEventListenerCallback(event) {
      return self.clients.claim();
    });

  const FILES = ['assets/connect.css', 'assets/connect.js', 'assets/connect.map', 'assets/failed.png', 'assets/passed.png', 'assets/test-support.css', 'assets/test-support.js', 'assets/test-support.map', 'assets/tests.js', 'assets/tests.map', 'assets/vendor.css', 'assets/vendor.js', 'assets/vendor.map'];
  const PREPEND = undefined;
  const VERSION$1 = '1';
  const REQUEST_MODE = 'cors';

  /*
   * Deletes all caches that start with the `prefix`, except for the
   * cache defined by `currentCache`
   */
  var cleanupCaches = (prefix, currentCache) => {
    return caches.keys().then((cacheNames) => {
      cacheNames.forEach((cacheName) => {
        let isOwnCache = cacheName.indexOf(prefix) === 0;
        let isNotCurrentCache = cacheName !== currentCache;

        if (isOwnCache && isNotCurrentCache) {
          caches.delete(cacheName);
        }
      });
    });
  };

  const CACHE_KEY_PREFIX = 'esw-asset-cache';
  const CACHE_NAME = `${CACHE_KEY_PREFIX}-${VERSION$1}`;
  const CACHE_URLS = FILES.map((file) => {
    return new URL(file, (PREPEND || self.location)).toString();
  });

  /*
   * Removes all cached requests from the cache that aren't in the `CACHE_URLS`
   * list.
   */
  const PRUNE_CURRENT_CACHE = () => {
    caches.open(CACHE_NAME).then((cache) => {
      return cache.keys().then((keys) => {
        keys.forEach((request) => {
          if (CACHE_URLS.indexOf(request.url) === -1) {
            cache.delete(request);
          }
        });
      });
    });
  };

  self.addEventListener('install', (event) => {
    event.waitUntil(
      caches
        .open(CACHE_NAME)
        .then((cache) => {
          return Promise.all(CACHE_URLS.map((url) => {
            let request = new Request(url, { mode: REQUEST_MODE });
            return fetch(request)
              .then((response) => {
                if (response.status >= 400) {
                  throw new Error(`Request for ${url} failed with status ${response.statusText}`);
                }
                return cache.put(url, response);
              })
              .catch(function(error) {
                console.error(`Not caching ${url} due to ${error}`);
              });
          }));
        })
    );
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(
      Promise.all([
        cleanupCaches(CACHE_KEY_PREFIX, CACHE_NAME),
        PRUNE_CURRENT_CACHE()
      ])
    );
  });

  self.addEventListener('fetch', (event) => {
    let isGETRequest = event.request.method === 'GET';
    let shouldRespond = CACHE_URLS.indexOf(event.request.url) !== -1;

    if (isGETRequest && shouldRespond) {
      event.respondWith(
        caches.match(event.request, { cacheName: CACHE_NAME })
          .then((response) => {
            if (response) {
              return response;
            }
            return fetch(event.request);
          })
      );
    }
  });

  const VERSION$2 = '1';
  const PATTERNS = ['http://localhost:8000/api/v1/(.*)'];

  /**
   * Create an absolute URL, allowing regex expressions to pass
   *
   * @param {string} url
   * @param {string|object} baseUrl
   * @public
   */
  function createNormalizedUrl(url, baseUrl = self.location) {
    return decodeURI(new URL(encodeURI(url), baseUrl).toString());
  }

  /**
   * Create an (absolute) URL Regex from a given string
   *
   * @param {string} url
   * @returns {RegExp}
   * @public
   */
  function createUrlRegEx(url) {
    let normalized = createNormalizedUrl(url);
    return new RegExp(`^${normalized}$`);
  }

  /**
   * Check if given URL matches any pattern
   *
   * @param {string} url
   * @param {array} patterns
   * @returns {boolean}
   * @public
   */
  function urlMatchesAnyPattern(url, patterns) {
    return !!patterns.find((pattern) => pattern.test(decodeURI(url)));
  }

  const CACHE_KEY_PREFIX$1 = 'esw-cache-fallback';
  const CACHE_NAME$1 = `${CACHE_KEY_PREFIX$1}-${VERSION$2}`;

  const PATTERN_REGEX = PATTERNS.map(createUrlRegEx);

  self.addEventListener('fetch', (event) => {
    let request = event.request;
    if (request.method !== 'GET' || !/^https?/.test(request.url)) {
      return;
    }

    if (urlMatchesAnyPattern(request.url, PATTERN_REGEX)) {
      event.respondWith(
        caches.open(CACHE_NAME$1).then((cache) => {
          return fetch(request)
            .then((response) => {
              cache.put(request, response.clone());
              return response;
            })
            .catch(() => caches.match(event.request));
        })
      );
    }
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(cleanupCaches(CACHE_KEY_PREFIX$1, CACHE_NAME$1));
  });

  const VERSION$3 = '1';
  const INDEX_HTML_PATH = 'index.html';

  const CACHE_KEY_PREFIX$2 = 'esw-index';
  const CACHE_NAME$2 = `${CACHE_KEY_PREFIX$2}-${VERSION$3}`;

  const INDEX_HTML_URL = new URL(INDEX_HTML_PATH, self.location).toString();

  self.addEventListener('install', (event) => {
    event.waitUntil(
      fetch(INDEX_HTML_URL, { credentials: 'include' }).then((response) => {
        return caches
          .open(CACHE_NAME$2)
          .then((cache) => cache.put(INDEX_HTML_URL, response));
      })
    );
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(cleanupCaches(CACHE_KEY_PREFIX$2, CACHE_NAME$2));
  });

  self.addEventListener('fetch', (event) => {
    let request = event.request;
    let isGETRequest = request.method === 'GET';
    let isHTMLRequest = request.headers.get('accept').indexOf('text/html') !== -1;
    let isLocal = new URL(request.url).origin === location.origin

    if (isGETRequest && isHTMLRequest && isLocal) {
      event.respondWith(
        caches.match(INDEX_HTML_URL, { cacheName: CACHE_NAME$2 })
      );
    }
  });

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

This is how network requests appear in Chrome:Network request while offline

I assume the problem is in the configuration of ember-service-worker-cache-fallback. But I'm not quite sure about that. Any idea or link to a working example is welcome. I didn't find a lot about ember-service-worker-cache-fallback so far.

Thanks!

答:
What you've described is the correct and expected behaviour of ember-service-worker-cache-fallback, that is first try fetch from the network if not possible then fallback to fetch from the cached version in the service worker.

I believe what you are looking for is some kind of queuing mechanism for failed requests. This is not covered in the scope of ember-service-worker-cache-fallback.

Fear not though, I had similar ambitions and came up with my own solution called ember-service-worker-enqueue . It's a ember-service-worker plugin that queues only failed mutation requests eg POST, PUT, PATCH, DELETE using Mozilla's Localforage and then sends them when the network is stable.

It's perfect for protecting you ember app against network failures or server errors which respond with 5xx status codes.

NOTE: In my experience, Service Workers are best when treated on a per use case, so don't blindly install my plugin and expect things to work the same way for you, rather go through the heavily commented code ( < 200 lines), fork the plugin and adjust it to fit your needs. Enjoy,

Ps: I'm also working on another one called ember-service-worker-push-notifications still early days but will follow same heavy comments for anyone looking to gain from it. Cheers!

Body:
I'm a beginner in ember and service workers. My goal is to setup a simple ember app that works offline. I basically have a list of elements that are available through an API (GET/POST).

When I'm online, everything works as expected. I can GET the list and POST new items. When I'm offline the app works, but network requests are not executed once I go back online. All network requests are actually executed while I'm offline (and obviously fail). I would expect that the service worker caches the network requests and executes them only once I'm back online. Is this wrong?

Here some information about my setup:

Ember version:

ember-cli: 2.13.1

node: 7.10.0

os: darwin x64

Service Worker Add-ons (as listed in app/package.json):

"ember-service-worker": "^0.6.6",
"ember-service-worker-asset-cache": "^0.6.1",
"ember-service-worker-cache-fallback": "^0.6.1",
"ember-service-worker-index": "^0.6.1",

I should probably also mention that I use ember-django-adapter in version 1.1.3.

This is my app/ember-cli-build.js

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    'esw-cache-fallback': {
      // RegExp patterns specifying which URLs to cache.
      patterns: [
        'http://localhost:8000/api/v1/(.*)',
      ],

      // changing this version number will bust the cache
      version: '1'
    }
  });

  return app.toTree();
};

My network requests (GET/POST) go to http://localhost:8000/api/v1/properties/.

This is my app/adapters/applications.js

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {

  namespace: 'api/v1',
  host: 'http://localhost:8000',
  authorizer: 'authorizer:token',
  headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
  buildURL: function(type, id, record) {
  return this._super(type, id, record) + '/';
  }
});

The service worker registers when I open the app:

(function () {
  'use strict';

  self.addEventListener('install', function installEventListenerCallback(event) {
      return self.skipWaiting();
    });

    self.addEventListener('activate', function installEventListenerCallback(event) {
      return self.clients.claim();
    });

  const FILES = ['assets/connect.css', 'assets/connect.js', 'assets/connect.map', 'assets/failed.png', 'assets/passed.png', 'assets/test-support.css', 'assets/test-support.js', 'assets/test-support.map', 'assets/tests.js', 'assets/tests.map', 'assets/vendor.css', 'assets/vendor.js', 'assets/vendor.map'];
  const PREPEND = undefined;
  const VERSION$1 = '1';
  const REQUEST_MODE = 'cors';

  /*
   * Deletes all caches that start with the `prefix`, except for the
   * cache defined by `currentCache`
   */
  var cleanupCaches = (prefix, currentCache) => {
    return caches.keys().then((cacheNames) => {
      cacheNames.forEach((cacheName) => {
        let isOwnCache = cacheName.indexOf(prefix) === 0;
        let isNotCurrentCache = cacheName !== currentCache;

        if (isOwnCache && isNotCurrentCache) {
          caches.delete(cacheName);
        }
      });
    });
  };

  const CACHE_KEY_PREFIX = 'esw-asset-cache';
  const CACHE_NAME = `${CACHE_KEY_PREFIX}-${VERSION$1}`;
  const CACHE_URLS = FILES.map((file) => {
    return new URL(file, (PREPEND || self.location)).toString();
  });

  /*
   * Removes all cached requests from the cache that aren't in the `CACHE_URLS`
   * list.
   */
  const PRUNE_CURRENT_CACHE = () => {
    caches.open(CACHE_NAME).then((cache) => {
      return cache.keys().then((keys) => {
        keys.forEach((request) => {
          if (CACHE_URLS.indexOf(request.url) === -1) {
            cache.delete(request);
          }
        });
      });
    });
  };

  self.addEventListener('install', (event) => {
    event.waitUntil(
      caches
        .open(CACHE_NAME)
        .then((cache) => {
          return Promise.all(CACHE_URLS.map((url) => {
            let request = new Request(url, { mode: REQUEST_MODE });
            return fetch(request)
              .then((response) => {
                if (response.status >= 400) {
                  throw new Error(`Request for ${url} failed with status ${response.statusText}`);
                }
                return cache.put(url, response);
              })
              .catch(function(error) {
                console.error(`Not caching ${url} due to ${error}`);
              });
          }));
        })
    );
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(
      Promise.all([
        cleanupCaches(CACHE_KEY_PREFIX, CACHE_NAME),
        PRUNE_CURRENT_CACHE()
      ])
    );
  });

  self.addEventListener('fetch', (event) => {
    let isGETRequest = event.request.method === 'GET';
    let shouldRespond = CACHE_URLS.indexOf(event.request.url) !== -1;

    if (isGETRequest && shouldRespond) {
      event.respondWith(
        caches.match(event.request, { cacheName: CACHE_NAME })
          .then((response) => {
            if (response) {
              return response;
            }
            return fetch(event.request);
          })
      );
    }
  });

  const VERSION$2 = '1';
  const PATTERNS = ['http://localhost:8000/api/v1/(.*)'];

  /**
   * Create an absolute URL, allowing regex expressions to pass
   *
   * @param {string} url
   * @param {string|object} baseUrl
   * @public
   */
  function createNormalizedUrl(url, baseUrl = self.location) {
    return decodeURI(new URL(encodeURI(url), baseUrl).toString());
  }

  /**
   * Create an (absolute) URL Regex from a given string
   *
   * @param {string} url
   * @returns {RegExp}
   * @public
   */
  function createUrlRegEx(url) {
    let normalized = createNormalizedUrl(url);
    return new RegExp(`^${normalized}$`);
  }

  /**
   * Check if given URL matches any pattern
   *
   * @param {string} url
   * @param {array} patterns
   * @returns {boolean}
   * @public
   */
  function urlMatchesAnyPattern(url, patterns) {
    return !!patterns.find((pattern) => pattern.test(decodeURI(url)));
  }

  const CACHE_KEY_PREFIX$1 = 'esw-cache-fallback';
  const CACHE_NAME$1 = `${CACHE_KEY_PREFIX$1}-${VERSION$2}`;

  const PATTERN_REGEX = PATTERNS.map(createUrlRegEx);

  self.addEventListener('fetch', (event) => {
    let request = event.request;
    if (request.method !== 'GET' || !/^https?/.test(request.url)) {
      return;
    }

    if (urlMatchesAnyPattern(request.url, PATTERN_REGEX)) {
      event.respondWith(
        caches.open(CACHE_NAME$1).then((cache) => {
          return fetch(request)
            .then((response) => {
              cache.put(request, response.clone());
              return response;
            })
            .catch(() => caches.match(event.request));
        })
      );
    }
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(cleanupCaches(CACHE_KEY_PREFIX$1, CACHE_NAME$1));
  });

  const VERSION$3 = '1';
  const INDEX_HTML_PATH = 'index.html';

  const CACHE_KEY_PREFIX$2 = 'esw-index';
  const CACHE_NAME$2 = `${CACHE_KEY_PREFIX$2}-${VERSION$3}`;

  const INDEX_HTML_URL = new URL(INDEX_HTML_PATH, self.location).toString();

  self.addEventListener('install', (event) => {
    event.waitUntil(
      fetch(INDEX_HTML_URL, { credentials: 'include' }).then((response) => {
        return caches
          .open(CACHE_NAME$2)
          .then((cache) => cache.put(INDEX_HTML_URL, response));
      })
    );
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(cleanupCaches(CACHE_KEY_PREFIX$2, CACHE_NAME$2));
  });

  self.addEventListener('fetch', (event) => {
    let request = event.request;
    let isGETRequest = request.method === 'GET';
    let isHTMLRequest = request.headers.get('accept').indexOf('text/html') !== -1;
    let isLocal = new URL(request.url).origin === location.origin

    if (isGETRequest && isHTMLRequest && isLocal) {
      event.respondWith(
        caches.match(INDEX_HTML_URL, { cacheName: CACHE_NAME$2 })
      );
    }
  });

}());

This is how network requests appear in Chrome:Network request while offline

I assume the problem is in the configuration of ember-service-worker-cache-fallback. But I'm not quite sure about that. Any idea or link to a working example is welcome. I didn't find a lot about ember-service-worker-cache-fallback so far.

Thanks!


问:
Visual Studio post build events stuck waiting for executable to finish before running app in debug mode
Part of the post build on my project is the execution of a program I wrote for testing the main application. Unfortunately, the post build process in visual studio locks up waiting for the executable to exit. So, i'm stuck closing my test program in order to have the post build process complete and my application run. How do I change this so VS does not wait for the program to return before launching? Thanks.</p>

答:
If you utilize cruise control for your builds, you could place this in the publishers section which allows the build to finish before running the publisher tasks.

Additionally a custom msbuild task is quite trivial to build, if you know how to spin off a process in .net then it's really simple to do in msbuild. To do this you could edit your .csproj file or your .proj build script to use that custom task.

```<code>using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MyTasks
{
public class SimpleTask : Task
{
    public override bool Execute()
    {
//something involving Process.Start
        return true;
    }
}
}
</code>```

Then in your build script or csproj file you add the using for the task you created and call it.

Body:
If you utilize cruise control for your builds, you could place this in the publishers section which allows the build to finish before running the publisher tasks.

Additionally a custom msbuild task is quite trivial to build, if you know how to spin off a process in .net then it's really simple to do in msbuild. To do this you could edit your .csproj file or your .proj build script to use that custom task.

using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MyTasks
{
public class SimpleTask : Task
{
    public override bool Execute()
    {
//something involving Process.Start
        return true;
    }
}
}

Then in your build script or csproj file you add the using for the task you created and call it.


问:
Print the value of injected parameter in sqlmap
I using sqlmap for injection and URL look like
python sqlmap.py -u "http://localhost/utility/?site_name=30"
so i just want to know what are the values sqlmap try to give input for site_name for injection.</p>

答:
You just have to add -v option and the value of output you want from 1 to 6. in your case is 4

```<code>python sqlmap.py -u "http://localhost/utility/?site_name=30" -v 4
</code>```

See it
https://github.com/sqlmapproject/sqlmap/wiki/Usage

Body:
You just have to add -v option and the value of output you want from 1 to 6. in your case is 4

python sqlmap.py -u "http://localhost/utility/?site_name=30" -v 4

See it
https://github.com/sqlmapproject/sqlmap/wiki/Usage


问:
How to simulate OSPF routing table in Macintosh or Linux?
I am trying to make a OSPF protocol simulation in Mac or Linux. So, basically I want to run many binary OSPF binaries and they should be able to speak to each other and should be able to use pseudo interface to run OSPF on it. So, if they share the pseudointerface I should be able to assign the same subnet interface on different interfaces.

For example, R1 - OSPF Sim1 has 3 pseudo networking interface. The pseudo networking interface IP is en0 - 192.168.2.1/24 and en1 is 111.111.10.1/24.
The loopback is 1.1.1.1

now, I have R2 - OSPF sim2 has two pseudo networking interface. The pseudo networking interface is en0 - 192.168.2.1/24 and loopback is 2.2.2.2

Now, I have R3 - OSPF sim3 has two pseudo networking interface. The pseudo networking interface is en1 - 111.111.10.2/24 and loopback is 3.3.3.3

I want to simulate in such a way that those are in the subnet can ping each other and rest not. Any idea? Also, I want them to install routes so that kernel is aware of it.

答:
I would suggest to use VirtualBox to create three identical linux virtual machines, each one running its own quagga packages.

To do so, I would use Alpine Linux as base (it is a extremely compact and functional linux distribution, which has quagga packages available). To create Alpine-based VM, there is a detailed instruction here

There are several examples of OSPF testbeds, this one seems particularly relevant to what you want to achieve.

Hope it help!


问:
pandas rolling apply to allow nan
I have a very simple Pandas Series:

```<code>xx = pd.Series([1, 2, np.nan, np.nan, 3, 4, 5])
</code>```

If I run this I get what I want:

```<code>>>> xx.rolling(3,1).mean()
0    1.0
1    1.5
2    1.5
3    2.0
4    3.0
5    3.5
6    4.0
</code>```

But if I have to use .apply() I cannot get it to work by ignoring NaNs in the mean() operation:

```<code>>>> xx.rolling(3,1).apply(np.mean)
0    1.0
1    1.5
2    NaN
3    NaN
4    NaN
5    NaN
6    4.0

>>> xx.rolling(3,1).apply(lambda x : np.mean(x))
0    1.0
1    1.5
2    NaN
3    NaN
4    NaN
5    NaN
6    4.0
</code>```

What should I do in order to both use .apply() and have the result in the first output? My actual problem is more complicated that I have to use .apply() to realize but it boils down to this issue.

答:
You can use np.nanmean()

```<code>xx.rolling(3,1).apply(lambda x : np.nanmean(x))
Out[59]:
0    1.0
1    1.5
2    1.5
3    2.0
4    3.0
5    3.5
6    4.0
dtype: float64
</code>```

If you have to process the nans explicitly, you can do:

```<code>xx.rolling(3,1).apply(lambda x : np.mean(x[~np.isnan(x)]))
Out[94]:
0    1.0
1    1.5
2    1.5
3    2.0
4    3.0
5    3.5
6    4.0
dtype: float64
</code>```

Title: pandas rolling apply to allow nan

Body:
I have a very simple Pandas Series:

xx = pd.Series([1, 2, np.nan, np.nan, 3, 4, 5])

If I run this I get what I want:

>>> xx.rolling(3,1).mean()
0    1.0
1    1.5
2    1.5
3    2.0
4    3.0
5    3.5
6    4.0

But if I have to use .apply() I cannot get it to work by ignoring NaNs in the mean() operation:

>>> xx.rolling(3,1).apply(np.mean)
0    1.0
1    1.5
2    NaN
3    NaN
4    NaN
5    NaN
6    4.0

>>> xx.rolling(3,1).apply(lambda x : np.mean(x))
0    1.0
1    1.5
2    NaN
3    NaN
4    NaN
5    NaN
6    4.0

What should I do in order to both use .apply() and have the result in the first output? My actual problem is more complicated that I have to use .apply() to realize but it boils down to this issue.

Body:
You can use np.nanmean()

xx.rolling(3,1).apply(lambda x : np.nanmean(x))
Out[59]:
0    1.0
1    1.5
2    1.5
3    2.0
4    3.0
5    3.5
6    4.0
dtype: float64

If you have to process the nans explicitly, you can do:

xx.rolling(3,1).apply(lambda x : np.mean(x[~np.isnan(x)]))
Out[94]:
0    1.0
1    1.5
2    1.5
3    2.0
4    3.0
5    3.5
6    4.0
dtype: float64


问:
count distinct values in spreadsheet
I have a Google spreadsheet with a column that looks like this:

```<code>City
----
London
Paris
London
Berlin
Rome
Paris
</code>```

I want to count the appearances of each distinct city (so I need the city name and the number of appearances).

```<code>City   | Count
-------+------
London |  2
Paris  |  2
Berlin |  1
Rome   |  1
</code>```

How do I do that?

答:
You can use the query function, so if your data were in col A where the first row was the column title...

```<code>=query(A2:A,"select A, count(A) where A != '' group by A order by count(A) desc label A 'City'", 0)
</code>```

yields

```<code>City    count
London  2
Paris   2
Berlin  1
Rome    1
</code>```

Link to working Google Sheet.

https://docs.google.com/spreadsheets/d/1N5xw8-YP2GEPYOaRkX8iRA6DoeRXI86OkfuYxwXUCbc/edit#gid=0

ContentLicense: CC BY-SA 4.0

Title: count distinct values in spreadsheet

Body:
I have a Google spreadsheet with a column that looks like this:

City
----
London
Paris
London
Berlin
Rome
Paris

I want to count the appearances of each distinct city (so I need the city name and the number of appearances).

City   | Count
-------+------
London |  2
Paris  |  2
Berlin |  1
Rome   |  1

How do I do that?

Body:
You can use the query function, so if your data were in col A where the first row was the column title...

=query(A2:A,"select A, count(A) where A != '' group by A order by count(A) desc label A 'City'", 0)

yields

City    count
London  2
Paris   2
Berlin  1
Rome    1

Link to working Google Sheet.

https://docs.google.com/spreadsheets/d/1N5xw8-YP2GEPYOaRkX8iRA6DoeRXI86OkfuYxwXUCbc/edit#gid=0


问:
Couldn't find Person with 'login'=
I never developed anything for web before, but now I have to make a simple application to show some data from an existing database.

Thing is, each user should only see his/her respective data, so I need some form of authentication to do querys joining that user and other tables. I tried to keep things simple, all the user have to do is type it's username, which is the primary key on the Pessoa table (no passwords, no email confirmation, no nothing).

I've read a few tutorials about Rails on RailsGuides, and www.rubypigeon.com/posts/how-to-implement-simple-authentication-without-devise/ for the authentication, but I just can't get my login to work.

Here's my code so far:

HomeController:

```<code>class HomeController < ApplicationController
  def index
  end

  def login
    @user = Pessoa.new
  end

  def sign_in
    @user = Pessoa.find(params[:id])

    if @user
      session.clear
      session[:user_id] = @user.id
      render '/'
    else
      @error = 'Username or password was incorrect'
      erb :sign_in
    end
  end

  def sign_out
    session.clear
    render '/'
  end

  helper_method :current_user
  def current_user
    if session[:user_id]
      Pessoa.find (session[:user_id])
    else
      nil
    end
  end
end
</code>```

views/home/login.html.erb:

```<code><%= form_for @user, url: home_sign_in_path do |f| %>

  <div class="field">
    <%= f.label :"digite seu login" %>
    <%= f.text_field :id %>
  </div>

  <div class="actions">
    <%= f.submit :entrar %>
  </div>

<% end %>
</code>```

Routes.rb

```<code>Rails.application.routes.draw do
  root 'home#index'
  get 'home/index'

  get 'home/login', to: 'home#login'
  post 'home/sign_in', to: 'home#sign_in'
  post 'home/sign_out', to: 'home#sign_out'

  resources :pessoas
end
</code>```

/views/home/index.html.erb have a lot of static HTML stuff, the only Ruby code on it is a

```<code><%= link_to 'Login', home_login_path %>
</code>```

Pessoa.rb

```<code>class Pessoa < ApplicationRecord
  self.table_name = 'pessoa'
  self.primary_key = 'login'
end
</code>```

I'm working with legacy tables on PostgreSQL, that's why primary key had to be changed.

Whenever I go to localhost:3000/home/login and type my login, I get this
error message. The weird part is if I run the exact same line that gives me the error on the console, it works just fine.

As I said, I'm very new to Rails and web development in general, so I think it's a tiny detail that I aparently can't see. Any help would be appreciated.

Btw, don't mind the resource name, "Pessoa" means "Person" in portuguese, which is my native language.

development.log:

```<code>Started GET "/home/login" for 127.0.0.1 at 2017-06-06 20:22:45 -0300
Processing by HomeController#login as HTML
  Rendering home/login.html.erb within layouts/application
  Rendered home/login.html.erb within layouts/application (12.4ms)
Completed 200 OK in 1504ms (Views: 1369.5ms | ActiveRecord: 0.0ms)

Started POST "/home/sign_in" for 127.0.0.1 at 2017-06-06 20:22:50 -0300
Processing by HomeController#sign_in as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Jzt0Yeven91Kl8DrfjpJa8I9PJjr7SzKmE43lwprjlopV7l+zFU6EUjUgAiKYJhzemm7xu8NGfiPj3E5h5EiYw==", "pessoa"=>{"id"=>"gabrielbrito"}, "commit"=>"entrar"}
  [1m[36mPessoa Load (1.5ms)[0m  [1m[34mSELECT  "pessoa".* FROM "pessoa" WHERE "pessoa"."login" = $1 LIMIT $2[0m  [["login", nil], ["LIMIT", 1]]
Completed 404 Not Found in 9ms (ActiveRecord: 1.5ms)

ActiveRecord::RecordNotFound (Couldn't find Pessoa with 'login'=):

app/controllers/home_controller.rb:10:in `sign_in'
Started PUT "/__web_console/repl_sessions/ed3bb60f3a72a0c0b0c951fa03c0f23d" for 127.0.0.1 at 2017-06-06 20:22:56 -0300
Started PUT "/__web_console/repl_sessions/ed3bb60f3a72a0c0b0c951fa03c0f23d" for 127.0.0.1 at 2017-06-06 20:22:58 -0300
Started PUT "/__web_console/repl_sessions/ed3bb60f3a72a0c0b0c951fa03c0f23d" for 127.0.0.1 at 2017-06-06 20:23:04 -0300
[1m[36mPessoa Load (1.2ms)[0m  [1m[34mSELECT  "pessoa".* FROM "pessoa" WHERE "pessoa"."login" = $1 LIMIT $2[0m  [["login", "gabrielbrito"], ["LIMIT", 1]]

Started GET "/home/login" for 127.0.0.1 at 2017-06-06 21:27:45 -0300
Processing by HomeController#login as HTML
  Rendering home/login.html.erb within layouts/application
  Rendered home/login.html.erb within layouts/application (6.2ms)
Completed 200 OK in 1626ms (Views: 1152.5ms | ActiveRecord: 7.5ms)

Started POST "/home/sign_in" for 127.0.0.1 at 2017-06-06 21:27:52 -0300
Processing by HomeController#sign_in as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"q2ffWM1gqaXfCrsFm7KlGKwR/iTDoQBflquem2BKSaeMyKBiIaUrtnIkoEXNztUWRasIGGg0qZZxpdYao8xb9Q==", "pessoa"=>{"id"=>"gabrielbrito"}, "commit"=>"entrar"}
  [1m[36mPessoa Load (2.8ms)[0m  [1m[34mSELECT  "pessoa".* FROM "pessoa" WHERE "pessoa"."login" = $1 LIMIT $2[0m  [["login", "gabrielbrito"], ["LIMIT", 1]]
Completed 500 Internal Server Error in 23ms (ActiveRecord: 2.8ms)

NoMethodError (undefined method `empty?' for nil:NilClass):

app/controllers/home_controller.rb:15:in `sign_in'
</code>```

EDIT: Solved, thanks to @Gerry's help.

答:
UPDATE

It seems to be an issue with self.primary_key = 'login' in your model, so try adding that key to your routes:

```<code>resources :pessoas, param: :login
</code>```

To be consistent, you should also change any reference of id to login, that is, in your controller:

```<code>@user = Pessoa.find_by(login: params[:pessoa][:login])
</code>```

And in your view:

```<code><div class="field">
  <%= f.label :"digite seu login" %>
  <%= f.text_field :login %>
</div>
</code>```

Regarding

"undefined method 'empty?' for nil:NilClass" on line render '/'

You should change render '/' to either a redirect_to (to redirect to another page) or render view_name where view_name is the name of the view you want to render.

For example, if you want to redirect to home, you could do this:

```<code>redirect_to home_path
</code>```

Also, you should use find_by instead of find to avoid getting the same error when a user enters an invalid login (i.e. one that does not exist in DB):

```<code>@user = Pessoa.find_by(login: params[:pessoa][:login])
</code>```

Since this way you will get an empty collection instead of an error (exception), you will also need to update how you evaluate if a User was found:

```<code>if @user.present?
  # success code
else
  # failure code
end
</code>```

Putting it all together, your sign_in action should look like this:

```<code>def sign_in
  @user = Pessoa.find_by(login: params[:pessoa][:login])

  if @user.present?
    session.clear
    session[:user_id] = @user.id
    redirect_to home_path
  else
    @error = 'Username or password was incorrect'
  end
end
</code>```

Title: Couldn't find Person with 'login'=

Body:
I never developed anything for web before, but now I have to make a simple application to show some data from an existing database.

Thing is, each user should only see his/her respective data, so I need some form of authentication to do querys joining that user and other tables. I tried to keep things simple, all the user have to do is type it's username, which is the primary key on the Pessoa table (no passwords, no email confirmation, no nothing).

I've read a few tutorials about Rails on RailsGuides, and www.rubypigeon.com/posts/how-to-implement-simple-authentication-without-devise/ for the authentication, but I just can't get my login to work.

Here's my code so far:

HomeController:

class HomeController < ApplicationController
  def index
  end

  def login
    @user = Pessoa.new
  end

  def sign_in
    @user = Pessoa.find(params[:id])

    if @user
      session.clear
      session[:user_id] = @user.id
      render '/'
    else
      @error = 'Username or password was incorrect'
      erb :sign_in
    end
  end

  def sign_out
    session.clear
    render '/'
  end

  helper_method :current_user
  def current_user
    if session[:user_id]
      Pessoa.find (session[:user_id])
    else
      nil
    end
  end
end

views/home/login.html.erb:

<%= form_for @user, url: home_sign_in_path do |f| %>

    <%= f.label :"digite seu login" %>
    <%= f.text_field :id %>

    <%= f.submit :entrar %>

<% end %>

Routes.rb

Rails.application.routes.draw do
  root 'home#index'
  get 'home/index'

  get 'home/login', to: 'home#login'
  post 'home/sign_in', to: 'home#sign_in'
  post 'home/sign_out', to: 'home#sign_out'

  resources :pessoas
end

/views/home/index.html.erb have a lot of static HTML stuff, the only Ruby code on it is a

<%= link_to 'Login', home_login_path %>

Pessoa.rb

class Pessoa < ApplicationRecord
  self.table_name = 'pessoa'
  self.primary_key = 'login'
end

I'm working with legacy tables on PostgreSQL, that's why primary key had to be changed.

Whenever I go to localhost:3000/home/login and type my login, I get this
error message. The weird part is if I run the exact same line that gives me the error on the console, it works just fine.

As I said, I'm very new to Rails and web development in general, so I think it's a tiny detail that I aparently can't see. Any help would be appreciated.

Btw, don't mind the resource name, "Pessoa" means "Person" in portuguese, which is my native language.

development.log:

Started GET "/home/login" for 127.0.0.1 at 2017-06-06 20:22:45 -0300
Processing by HomeController#login as HTML
  Rendering home/login.html.erb within layouts/application
  Rendered home/login.html.erb within layouts/application (12.4ms)
Completed 200 OK in 1504ms (Views: 1369.5ms | ActiveRecord: 0.0ms)

Started POST "/home/sign_in" for 127.0.0.1 at 2017-06-06 20:22:50 -0300
Processing by HomeController#sign_in as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Jzt0Yeven91Kl8DrfjpJa8I9PJjr7SzKmE43lwprjlopV7l+zFU6EUjUgAiKYJhzemm7xu8NGfiPj3E5h5EiYw==", "pessoa"=>{"id"=>"gabrielbrito"}, "commit"=>"entrar"}
  [1m[36mPessoa Load (1.5ms)[0m  [1m[34mSELECT  "pessoa".* FROM "pessoa" WHERE "pessoa"."login" = $1 LIMIT $2[0m  [["login", nil], ["LIMIT", 1]]
Completed 404 Not Found in 9ms (ActiveRecord: 1.5ms)

ActiveRecord::RecordNotFound (Couldn't find Pessoa with 'login'=):

app/controllers/home_controller.rb:10:in `sign_in'
Started PUT "/__web_console/repl_sessions/ed3bb60f3a72a0c0b0c951fa03c0f23d" for 127.0.0.1 at 2017-06-06 20:22:56 -0300
Started PUT "/__web_console/repl_sessions/ed3bb60f3a72a0c0b0c951fa03c0f23d" for 127.0.0.1 at 2017-06-06 20:22:58 -0300
Started PUT "/__web_console/repl_sessions/ed3bb60f3a72a0c0b0c951fa03c0f23d" for 127.0.0.1 at 2017-06-06 20:23:04 -0300
[1m[36mPessoa Load (1.2ms)[0m  [1m[34mSELECT  "pessoa".* FROM "pessoa" WHERE "pessoa"."login" = $1 LIMIT $2[0m  [["login", "gabrielbrito"], ["LIMIT", 1]]

Started GET "/home/login" for 127.0.0.1 at 2017-06-06 21:27:45 -0300
Processing by HomeController#login as HTML
  Rendering home/login.html.erb within layouts/application
  Rendered home/login.html.erb within layouts/application (6.2ms)
Completed 200 OK in 1626ms (Views: 1152.5ms | ActiveRecord: 7.5ms)

Started POST "/home/sign_in" for 127.0.0.1 at 2017-06-06 21:27:52 -0300
Processing by HomeController#sign_in as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"q2ffWM1gqaXfCrsFm7KlGKwR/iTDoQBflquem2BKSaeMyKBiIaUrtnIkoEXNztUWRasIGGg0qZZxpdYao8xb9Q==", "pessoa"=>{"id"=>"gabrielbrito"}, "commit"=>"entrar"}
  [1m[36mPessoa Load (2.8ms)[0m  [1m[34mSELECT  "pessoa".* FROM "pessoa" WHERE "pessoa"."login" = $1 LIMIT $2[0m  [["login", "gabrielbrito"], ["LIMIT", 1]]
Completed 500 Internal Server Error in 23ms (ActiveRecord: 2.8ms)

NoMethodError (undefined method `empty?' for nil:NilClass):

app/controllers/home_controller.rb:15:in `sign_in'

EDIT: Solved, thanks to @Gerry's help.

Body:
UPDATE

It seems to be an issue with self.primary_key = 'login' in your model, so try adding that key to your routes:

resources :pessoas, param: :login

To be consistent, you should also change any reference of id to login, that is, in your controller:

@user = Pessoa.find_by(login: params[:pessoa][:login])

And in your view:

<div class="field">
  <%= f.label :"digite seu login" %>
  <%= f.text_field :login %>
</div>

Regarding

"undefined method 'empty?' for nil:NilClass" on line render '/'

You should change render '/' to either a redirect_to (to redirect to another page) or render view_name where view_name is the name of the view you want to render.

For example, if you want to redirect to home, you could do this:

redirect_to home_path

Also, you should use find_by instead of find to avoid getting the same error when a user enters an invalid login (i.e. one that does not exist in DB):

@user = Pessoa.find_by(login: params[:pessoa][:login])

Since this way you will get an empty collection instead of an error (exception), you will also need to update how you evaluate if a User was found:

if @user.present?
  # success code
else
  # failure code
end

Putting it all together, your sign_in action should look like this:

def sign_in
  @user = Pessoa.find_by(login: params[:pessoa][:login])

  if @user.present?
    session.clear
    session[:user_id] = @user.id
    redirect_to home_path
  else
    @error = 'Username or password was incorrect'
  end
end


问:
PYQT from Table widget to SQLite Database
I was wondering what the best method is for transfer data from a qtablewidget to an SQLite database and if im on the right try if you could help me find a way to generate some SQL code. I am making a program to keep track of current projects or my company and I have a GUI with a table that a user will add data too. I would like to be able to transfer that data into a database. So far the best method I can think of is to loop through the table to get all the values and then when it is finished then have it generate code to send to the database. The problem I'm having is I'm not sure how to generate the SQL code at the end. I have working code to connect to my database and my table, but just generating the code that goes in the VALUE

```<code>db_filename = '.\DB\ProgramManagerDB.sqlite'
with sqlite3.connect(db_filename) as conn:
    cursorProject = conn.cursor()
    cursorProject.execute(""" INSERT INTO  contacts(Name,Number,title,company,email,main_contact) VALUES (?,?,?,?,?,?)""",(This is what im not sure how to generate))
</code>```

Is there a better way of doing this or is that the most efficient way of doing it? Thank you for your help and advice.

Code for looping through table and getting values

```<code>for i in range(0,self.AddProjects.tableWidget_Contacts.rowCount()):
    contactName = self.AddProjects.tableWidget_Contacts.item(i,0).text()
    contactNumber = self.AddProjects.tableWidget_Contacts.item(i,1).text()
    title = self.AddProjects.tableWidget_Contacts.item(i,2).text()
    company = self.AddProjects.tableWidget_Contacts.item(i,3).text()
    email = self.AddProjects.tableWidget_Contacts.item(i,4).text()
    mainContact = self.AddProjects.tableWidget_Contacts.item(i,5).text()
</code>```

答:
Assuming everything else is good to go, try using "append" here:

```<code>cursorProject.execute(""" INSERT INTO  contacts(Name,Number,title,company,email,main_contact) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')""".append(contactName, contactNumber, title, company, email, mainContact) )
</code>```

Note: You may want to generate the SQL first as a string, then pass it to .execute(), or you may want to pass those values as a parameter if your particular sql supports it.

Note 2: There may be more efficient ways to do what you're attempting, but this looks like a great start!

Body:
I was wondering what the best method is for transfer data from a qtablewidget to an SQLite database and if im on the right try if you could help me find a way to generate some SQL code. I am making a program to keep track of current projects or my company and I have a GUI with a table that a user will add data too. I would like to be able to transfer that data into a database. So far the best method I can think of is to loop through the table to get all the values and then when it is finished then have it generate code to send to the database. The problem I'm having is I'm not sure how to generate the SQL code at the end. I have working code to connect to my database and my table, but just generating the code that goes in the VALUE

db_filename = '.\DB\ProgramManagerDB.sqlite'
with sqlite3.connect(db_filename) as conn:
    cursorProject = conn.cursor()
    cursorProject.execute(""" INSERT INTO  contacts(Name,Number,title,company,email,main_contact) VALUES (?,?,?,?,?,?)""",(This is what im not sure how to generate))

Is there a better way of doing this or is that the most efficient way of doing it? Thank you for your help and advice.

Code for looping through table and getting values

for i in range(0,self.AddProjects.tableWidget_Contacts.rowCount()):
    contactName = self.AddProjects.tableWidget_Contacts.item(i,0).text()
    contactNumber = self.AddProjects.tableWidget_Contacts.item(i,1).text()
    title = self.AddProjects.tableWidget_Contacts.item(i,2).text()
    company = self.AddProjects.tableWidget_Contacts.item(i,3).text()
    email = self.AddProjects.tableWidget_Contacts.item(i,4).text()
    mainContact = self.AddProjects.tableWidget_Contacts.item(i,5).text()

Body:
Assuming everything else is good to go, try using "append" here:

cursorProject.execute(""" INSERT INTO  contacts(Name,Number,title,company,email,main_contact) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')""".append(contactName, contactNumber, title, company, email, mainContact) )

Note: You may want to generate the SQL first as a string, then pass it to .execute(), or you may want to pass those values as a parameter if your particular sql supports it.

Note 2: There may be more efficient ways to do what you're attempting, but this looks like a great start!


问:
Neo4j - trouble with multi level hierarchies
I have the following structure in Neo4j:

Neo Structure

The business rules are such that:

Manager 1 MANAGES team leader 1 and team leader 2

Team Leader 1 MANAGES salesperson 1, 2 and 3

Team Leader 2 MANAGES salesperson 4, 5 and 6

Salesperson 4 MANAGES salesperson 7

Salesperson 1 OWNS broker 1

Salesperson 2 OWNS broker 2

Salesperson 3 OWNS broker 3

Salesperson 5 OWNS broker 5

Salesperson 6 OWNS broker 6

Salesperson 7 OWNS broker 4

Broker 1 is a BROKER_ON application 1

Broker 2 is a BROKER_ON application 2

Broker 3 is a BROKER_ON application 3

Broker 4 is a BROKER_ON applications 4 and 5

Broker 5 is a BROKER_ON application 6

Broker 6 is a BROKER_ON application 7

I am struggling with the cypher query so that:

Manager 1 should return applications 1, 2, 3, 4, 5, 6 and 7

Team leader 1 should return applications 1, 2 and 3

Team leader 2 should return applications 4, 5, 6, and 7

Salesperson 1 should return application 1

Salesperson 2 should return application 2

Salesperson 3 should return application 3

Salesperson 4 should return applications 4 and 5

Salesperson 5 should return application 6

Salesperson 6 should return application 7

Salesperson 7 should return applications 4 and 5

Any help would be greatly appreciated

Regards,

Craig

答:
In the following, I will assume that all managers, leaders, and salespeople are represented by nodes with a Person label. (The nodes can also have Manager, Leader, and SalesPerson labels, as appropriate, but that is not required for the purposes of this answer.)

To get a collection of all the Application nodes for the Person with an id of 123, you'd just have to use this simple query:

```<code>MATCH (p:Person {id: 123})-[*]->(a:Application)
RETURN p, COLLECT(a) AS apps;
</code>```

The query relies on the variable length relationship pattern [*] to match any path length (of at least 1).

Body:
In the following, I will assume that all managers, leaders, and salespeople are represented by nodes with a Person label. (The nodes can also have Manager, Leader, and SalesPerson labels, as appropriate, but that is not required for the purposes of this answer.)

To get a collection of all the Application nodes for the Person with an id of 123, you'd just have to use this simple query:

MATCH (p:Person {id: 123})-[*]->(a:Application)
RETURN p, COLLECT(a) AS apps;

The query relies on the variable length relationship pattern [*] to match any path length (of at least 1).


问:
Closing android application from fragment
I have only one activity in my application with multiple fragments. Whenever a user opens the app, it starts with startupFragment. Whenever user navigate through the fragments and presses  back, it takes him back to startupFragment. But when in the startupFragment, I want user, when clicked back, to be able to close the application. Now, here is the code, when the application is started for creating the fragment.:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Set starting fragment
    StartupFragment startupFragment = new StartupFragment();
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().add(R.id.content_main, startupFragment, "startupFragmentTag").commit();

}
</code>```

As you can see, I have added the tag "startupFragmentTag" to be able to identify it. This is my code onBackPressed:

```<code>@Override
public void onBackPressed()
{

    Fragment startup = getFragmentManager().findFragmentByTag("startupFragmentTag");

    if(startup == null) {

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        StartupFragment startupFragment = new StartupFragment();
        manager.beginTransaction().replace(R.id.content_main, startupFragment, "startupFragmentTag").commit();

    } else {

        finish();

    }
}
</code>```

So basically what I tried here, is when user is in another fragment, when the user presses back, it will take him/her back to startupFragment. But when in that fragment, when pressing back again, I want the user to be able to exit the application, which won't happen given the code now.

I find the startupFragment by its tag and check if it exists. If not, it will take back the user to it. But if it exists, user should be able to quit, that why finish() is called.

Does the previous fragments not get destroyed? But that shouldn't be the case, because even if I open the app and instantly press back, it won't exit the app.

What am I doing here wrong?

答:
It looks like all you need to do is add each Fragment to the back stack on each FragmentTransaction, and then pop each Fragment from the back stack in onBackPressed().

First, modify onCreate() so that on each transaction, it calls addToBackStack():

```<code>  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      //Set starting fragment
      StartupFragment startupFragment = new StartupFragment();
      android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
      fragmentManager.beginTransaction()
        .add(R.id.content_main, startupFragment, "startupFragmentTag")
        .addToBackStack(null)
        .commit();
  }
</code>```

Then, in onBackPressed(), just pop from the back stack if you're not on the starting Fragment.  If you're on the starting Fragment, and back is pressed, just call super.onBackPressed(), which will exit the app:

```<code>@Override
public void onBackPressed() {
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    if (fragmentManager.getBackStackEntryCount() > 1) {
        //Go back to previous Fragment
        fragmentManager.popBackStackImmediate();
    } else {
        //Nothing in the back stack, so exit
        super.onBackPressed();
    }
}
</code>```

Body:
I have only one activity in my application with multiple fragments. Whenever a user opens the app, it starts with startupFragment. Whenever user navigate through the fragments and presses  back, it takes him back to startupFragment. But when in the startupFragment, I want user, when clicked back, to be able to close the application. Now, here is the code, when the application is started for creating the fragment.:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Set starting fragment
    StartupFragment startupFragment = new StartupFragment();
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().add(R.id.content_main, startupFragment, "startupFragmentTag").commit();

}

As you can see, I have added the tag "startupFragmentTag" to be able to identify it. This is my code onBackPressed:

@Override
public void onBackPressed()
{

    Fragment startup = getFragmentManager().findFragmentByTag("startupFragmentTag");

    if(startup == null) {

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        StartupFragment startupFragment = new StartupFragment();
        manager.beginTransaction().replace(R.id.content_main, startupFragment, "startupFragmentTag").commit();

    } else {

        finish();

    }
}

So basically what I tried here, is when user is in another fragment, when the user presses back, it will take him/her back to startupFragment. But when in that fragment, when pressing back again, I want the user to be able to exit the application, which won't happen given the code now.

I find the startupFragment by its tag and check if it exists. If not, it will take back the user to it. But if it exists, user should be able to quit, that why finish() is called.

Does the previous fragments not get destroyed? But that shouldn't be the case, because even if I open the app and instantly press back, it won't exit the app.

What am I doing here wrong?

Body:
It looks like all you need to do is add each Fragment to the back stack on each FragmentTransaction, and then pop each Fragment from the back stack in onBackPressed().

First, modify onCreate() so that on each transaction, it calls addToBackStack():

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      //Set starting fragment
      StartupFragment startupFragment = new StartupFragment();
      android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
      fragmentManager.beginTransaction()
        .add(R.id.content_main, startupFragment, "startupFragmentTag")
        .addToBackStack(null)
        .commit();
  }

Then, in onBackPressed(), just pop from the back stack if you're not on the starting Fragment.  If you're on the starting Fragment, and back is pressed, just call super.onBackPressed(), which will exit the app:

@Override
public void onBackPressed() {
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    if (fragmentManager.getBackStackEntryCount() > 1) {
        //Go back to previous Fragment
        fragmentManager.popBackStackImmediate();
    } else {
        //Nothing in the back stack, so exit
        super.onBackPressed();
    }
}