问:
Rails habtm query based on a condition
I have following associations:

```<code>class ConferenceSession < ActiveRecord::Base

  has_many :conference_sessions

end

class ConferenceSession < ActiveRecord::Base

  belongs_to  :conference

  has_and_belongs_to_many  :users

end

class User < ActiveRecord::Base

  has_and_belongs_to_many :conference_sessions

end
</code>```

and a conference_sesssions_users table. Admin can allow specific people to attend a particular session. So I want to form a query that whenever a user logs in and selects a conference he should be allowed to see only those sessions where the admin has allowed him to. I tried this:

```<code>scope :visibility,
    lambda { |user_id| joins(:conference_sessions_users).where('conference_sessions_users.user_id = ?' => user_id) }
</code>```

but I'm getting an error ActiveRecord::ConfigurationError: Association named 'conference_sessions_users' was not found on ConferenceSession; perhaps you misspelled it?

What could be wrong?

答:
The error is referring to the joins(:conference_sessions_users) part of your scope. For the joins argument "The given symbol(s) should match the name of the association(s)."

You've used the name of the join table which isn't right in this situation.

To use the association you'd need: joins(:user)

If you do just want to use the joining table you can use a string to define the join:

```<code>joins("inner join conference_sessions_users
       on conference_session_id = conference_sessions.id")
</code>```

Title: Rails habtm query based on a condition

Body:
I have following associations:

class ConferenceSession < ActiveRecord::Base

  has_many :conference_sessions

end

class ConferenceSession < ActiveRecord::Base

  belongs_to  :conference

  has_and_belongs_to_many  :users

end

class User < ActiveRecord::Base

  has_and_belongs_to_many :conference_sessions

end

and a conference_sesssions_users table. Admin can allow specific people to attend a particular session. So I want to form a query that whenever a user logs in and selects a conference he should be allowed to see only those sessions where the admin has allowed him to. I tried this:

scope :visibility,
    lambda { |user_id| joins(:conference_sessions_users).where('conference_sessions_users.user_id = ?' => user_id) }

but I'm getting an error ActiveRecord::ConfigurationError: Association named 'conference_sessions_users' was not found on ConferenceSession; perhaps you misspelled it?

What could be wrong?

Body:
The error is referring to the joins(:conference_sessions_users) part of your scope. For the joins argument "The given symbol(s) should match the name of the association(s)."

You've used the name of the join table which isn't right in this situation.

To use the association you'd need: joins(:user)

If you do just want to use the joining table you can use a string to define the join:

joins("inner join conference_sessions_users
       on conference_session_id = conference_sessions.id")


来源: stackexchange

问:
mobile scroll not working with fullpage.js and wow.js
I'm using fullpage.js to create my website, and I'm trying to incorporate wow.js and animate.css to create some cool animations. Everything is working fine on desktop, but when I resize the browser to mobile-size, I cannot scroll at all. The animations at the top of my page load, but I cannot scroll at all until I resize to a bigger viewport.

I've tried the 'scrollOverflow: true' on fullpage, but it's not working.

This is what my app.js looks like:

```<code>$(document).ready(function() {

wow = new WOW(
    {
        boxClass:     'wow',      // default
        animateClass: 'animated', // default
        offset:       0,          // default
        mobile:       false,
        live:         true        // default
    }
)
wow.init();

$('#fullpage').fullpage({
    navigation: true,
    navigationPosition: 'left',
    navigationTooltips: ['Home', 'About Me', 'Skills', 'Portfolio', 'Contact', 'Hire Me'],
    resize: false,
    scrollBar: true,
    scrollOverflow: false,

    //RESPONSIVE
    responsiveWidth: 800,
    afterResize: function () {
        if ($(window).width() < 800) {
            //$.fn.fullpage.setAutoScrolling(false);
            var verticalNav = document.getElementById("fp-nav");
            $(verticalNav).hide();
        }
    }
});
});
</code>```

答:
THEY WORK

I am using FullPage.js, scrollOverflow and WOW Animations altogether and they work perfectly fine.

HERE ARE MY SETTINGS

In the HEAD ELEMENT I have these Links

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/jquery.fullPage.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" />
</code>```

And at the bottom before the ending BODY tag I have all these scripts.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/vendors/scrolloverflow.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/jquery.fullPage.min.js"></script>

<script>
    /*** Call function after page has loaded ***/
    $(document).ready(function() {

        /*** Call FullPage.js option ***/
        pageScroll();

        new WOW().init();
        $(window).resize(function() {
            pageScroll();
        });
    });

    /*** FullPage.js Function ***/
    function pageScroll(){
        $('#fullpage').fullpage({
            sectionsColor: ['#06C', '#C06', '#930', '#06C'],
            anchors: ['aa', 'bb', 'cc', 'dd'],
            menu: '.menu',
            navigation: true,
            scrollOverflow: true,
            scrollBar:true,
            fixedElements: '.header',
            paddingTop: '3em',
            slidesNavigation: true,
            paddingBottom: '1em'
        });
    }
</script>
</code>```

Here is a live working site.

https://cleansites.us/

ContentLicense: CC BY-SA 3.0

Body:
I'm using fullpage.js to create my website, and I'm trying to incorporate wow.js and animate.css to create some cool animations. Everything is working fine on desktop, but when I resize the browser to mobile-size, I cannot scroll at all. The animations at the top of my page load, but I cannot scroll at all until I resize to a bigger viewport.

I've tried the 'scrollOverflow: true' on fullpage, but it's not working.

This is what my app.js looks like:

$(document).ready(function() {

wow = new WOW(
    {
        boxClass:     'wow',      // default
        animateClass: 'animated', // default
        offset:       0,          // default
        mobile:       false,
        live:         true        // default
    }
)
wow.init();

$('#fullpage').fullpage({
    navigation: true,
    navigationPosition: 'left',
    navigationTooltips: ['Home', 'About Me', 'Skills', 'Portfolio', 'Contact', 'Hire Me'],
    resize: false,
    scrollBar: true,
    scrollOverflow: false,

    //RESPONSIVE
    responsiveWidth: 800,
    afterResize: function () {
        if ($(window).width() < 800) {
            //$.fn.fullpage.setAutoScrolling(false);
            var verticalNav = document.getElementById("fp-nav");
            $(verticalNav).hide();
        }
    }
});
});

Body:
THEY WORK

I am using FullPage.js, scrollOverflow and WOW Animations altogether and they work perfectly fine.

HERE ARE MY SETTINGS

In the HEAD ELEMENT I have these Links

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/jquery.fullPage.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" />

And at the bottom before the ending BODY tag I have all these scripts.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/vendors/scrolloverflow.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/jquery.fullPage.min.js"></script>

<script>
    /*** Call function after page has loaded ***/
    $(document).ready(function() {

        /*** Call FullPage.js option ***/
        pageScroll();

        new WOW().init();
        $(window).resize(function() {
            pageScroll();
        });
    });

    /*** FullPage.js Function ***/
    function pageScroll(){
        $('#fullpage').fullpage({
            sectionsColor: ['#06C', '#C06', '#930', '#06C'],
            anchors: ['aa', 'bb', 'cc', 'dd'],
            menu: '.menu',
            navigation: true,
            scrollOverflow: true,
            scrollBar:true,
            fixedElements: '.header',
            paddingTop: '3em',
            slidesNavigation: true,
            paddingBottom: '1em'
        });
    }
</script>

Here is a live working site.

https://cleansites.us/


问:
Directory walker written in Go stops with file in use (locked) error
I have this directory walker:

```<code>package main

import (
    "fmt"
    "os"
    "path/filepath"
    "strings"
)

var exts = [...]string{"*.psd", "*.cdr", "*.tiff", "*.svg", "*.png", "*.jpeg", "*.jpg", "*.pdf", "*.txt", "*.rtf", "*.docx", "*.doc", "*.xlsx", "*.xls", "*.ppt", "*.pptx", "*.accdb", "*.csv", "*.dwg", "*.dxf", "*.dng", "*.arw", "*.srf", "*.sr2", "*.bay", "*.crw", "*.cr2", "*.dcr", "*.kdc", "*.erf", "*.mef", "*.mrw", "*.nef", "*.nrw", "*.orf", "*.raf", "*.raw", "*.rwl", "*.rw2", "*.r3d", "*.ptx", "*.pef", "*.srw"}
var skipdir = [...]string{"WINDOWS", "Program Files"}

func VisitFile(fp string, fi os.FileInfo, err error) error {
    proceed := true
    if err != nil {
        fmt.Println(err) // can't walk here,
        return nil       // but continue walking elsewhere
    }
    if fi.IsDir() {
        return nil // not a file.  ignore.
    }
    for _, value := range skipdir {
        if strings.Contains(filepath.Dir(fp), value) {
            proceed = false
            break
        }
    }
    if proceed == true {
        for _, value := range exts {
            matched, err := filepath.Match(value, fi.Name())
            if err != nil {
                fmt.Println(err) // malformed pattern
                return err       // this is fatal.
            }
            if matched {
                fmt.Println(fp)
            }
        }
    } else {
        //fmt.Println(proceed)
        return nil
    }
    return nil
}

func getdrives() (r []string) {
    for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
        _, err := os.Open(string(drive) + ":\\")
        if err == nil {
            r = append(r, string(drive))
        }
    }
    return
}

func main() {
    drives := getdrives()
    for _, value := range drives {
        filepath.Walk(value+":/", VisitFile)
    }
}
</code>```

However, when it gets to pagefile.sys, I get this message:

GetFileAttributesEx C:\pagefile.sys: The process cannot access the file because
      it is being used by another process.

because the file is in use, and program stops. How do I suppress this message to continue walking?

答:
If you want your walk to finish, you should not return the error inside your function. You should collect the errors inside a slice.
Change your function to:

```<code>// Put this var outside your function
var myErrors []error
func VisitFile(fp string, fi os.FileInfo, err error) []error {
</code>```

Just make a variable as slice of errors. And then change the return err

```<code>   if proceed == true {
        for _, value := range exts {
            matched, err := filepath.Match(value, fi.Name())
            if err != nil {
                fmt.Println(err) // malformed pattern
                // collect the error
                myErrors = append(myErrors,err)
                // you could jump out of this by
                return nil
            }
            if matched {
                fmt.Println(fp)
            }
        }
    }
</code>```

At the end you can check the myErrors slice.

Body:
I have this directory walker:

package main

import (
    "fmt"
    "os"
    "path/filepath"
    "strings"
)

var exts = [...]string{"*.psd", "*.cdr", "*.tiff", "*.svg", "*.png", "*.jpeg", "*.jpg", "*.pdf", "*.txt", "*.rtf", "*.docx", "*.doc", "*.xlsx", "*.xls", "*.ppt", "*.pptx", "*.accdb", "*.csv", "*.dwg", "*.dxf", "*.dng", "*.arw", "*.srf", "*.sr2", "*.bay", "*.crw", "*.cr2", "*.dcr", "*.kdc", "*.erf", "*.mef", "*.mrw", "*.nef", "*.nrw", "*.orf", "*.raf", "*.raw", "*.rwl", "*.rw2", "*.r3d", "*.ptx", "*.pef", "*.srw"}
var skipdir = [...]string{"WINDOWS", "Program Files"}

func VisitFile(fp string, fi os.FileInfo, err error) error {
    proceed := true
    if err != nil {
        fmt.Println(err) // can't walk here,
        return nil       // but continue walking elsewhere
    }
    if fi.IsDir() {
        return nil // not a file.  ignore.
    }
    for _, value := range skipdir {
        if strings.Contains(filepath.Dir(fp), value) {
            proceed = false
            break
        }
    }
    if proceed == true {
        for _, value := range exts {
            matched, err := filepath.Match(value, fi.Name())
            if err != nil {
                fmt.Println(err) // malformed pattern
                return err       // this is fatal.
            }
            if matched {
                fmt.Println(fp)
            }
        }
    } else {
        //fmt.Println(proceed)
        return nil
    }
    return nil
}

func getdrives() (r []string) {
    for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
        _, err := os.Open(string(drive) + ":\\")
        if err == nil {
            r = append(r, string(drive))
        }
    }
    return
}

func main() {
    drives := getdrives()
    for _, value := range drives {
        filepath.Walk(value+":/", VisitFile)
    }
}

However, when it gets to pagefile.sys, I get this message:

GetFileAttributesEx C:\pagefile.sys: The process cannot access the file because
      it is being used by another process.

because the file is in use, and program stops. How do I suppress this message to continue walking?

Body:
If you want your walk to finish, you should not return the error inside your function. You should collect the errors inside a slice.
Change your function to:

// Put this var outside your function
var myErrors []error
func VisitFile(fp string, fi os.FileInfo, err error) []error {

Just make a variable as slice of errors. And then change the return err

   if proceed == true {
        for _, value := range exts {
            matched, err := filepath.Match(value, fi.Name())
            if err != nil {
                fmt.Println(err) // malformed pattern
                // collect the error
                myErrors = append(myErrors,err)
                // you could jump out of this by
                return nil
            }
            if matched {
                fmt.Println(fp)
            }
        }
    }

At the end you can check the myErrors slice.


问:
How to change the text " Material ActionBar"
How to change the text " Material ActionBar"?
I can't find the code to change it..help.

A Material ActionBar

答:
By default, the Title for your Activity would be the label specified in the AndroidManifest.xml as @Surrender Kumar has given as a solution:

```<code><activity
    android:name=".Activity"
    android:label="Name in Toolbar"
 />
</code>```

But if you would want to override it and set it manually, you could do as @MarcGV says and use the methods inside the onCreate() method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    setTitle("Your Desired Title");
    ...
}
</code>```

Body:
By default, the Title for your Activity would be the label specified in the AndroidManifest.xml as @Surrender Kumar has given as a solution:

<activity
    android:name=".Activity"
    android:label="Name in Toolbar"
 />

But if you would want to override it and set it manually, you could do as @MarcGV says and use the methods inside the onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    setTitle("Your Desired Title");
    ...
}


问:
Button Click does not fire with fancybox2 from webForms
I have a custom control and it's been registered in main page in a hidden div. On page load I show a modal window (fancybox 2) with content the one that has the hidden div.

My problem is that this control has a button and it doesn't fire from the fancybox.

I tried this Fancybox - ASP.NET button not working but nothing changed.

Does anyone know how to fix this? The preferable would be a fix without amending the fancybox.js.

The code where the control is placed in

```<code><a href="#inline" style="display: none" id="trigerButton"></a>
<div id="inline" style="display: none; width: 500px;">
    <asp:PlaceHolder runat="server" ID="PhCtrl"></asp:PlaceHolder>
</div>
</code>```

from codeBehind

```<code>var ctrlName = LoadControl("~/Path/control.ascx");
ctrlName.ID="ctrlID";
PhCtrl.Controls.Add(ctrlName);
var sb = new StringBuilder();
sb.Append("$(document).ready(function() {");
sb.Append("$('#trigerButton').fancybox({modal:true}).trigger('click');");
sb.Append("$('#clickNo').click(function(){$.fancybox.close(true)});");
sb.Append("});");
ClientScript.RegisterStartupScript(typeof(T), "_script", sb.ToString(), true);
</code>```

The custom control

It has a button and this button doesn't fire

```<code><asp:Button runat="server" ID="Button1" Text="Upgrade" OnClick="Button1_click" />
  protected void Button1_click(object s,EventArgs e)
    {
        //Do something
    }
</code>```

I would appreciate any suggestions

Thanks

SOLUTION

I didn't manage to find a solution without editing the fancybox.js, though I replaced every

```<code>appendTo('body')
</code>```

with

```<code>appendTo('form:first')
</code>```

答:
```<code>//Try This
$('.fancybox').fancybox({
     parent: "form:first", // jQuery selector
});
</code>```

Body:
I have a custom control and it's been registered in main page in a hidden div. On page load I show a modal window (fancybox 2) with content the one that has the hidden div.

My problem is that this control has a button and it doesn't fire from the fancybox.

I tried this Fancybox - ASP.NET button not working but nothing changed.

Does anyone know how to fix this? The preferable would be a fix without amending the fancybox.js.

The code where the control is placed in

    <asp:PlaceHolder runat="server" ID="PhCtrl"></asp:PlaceHolder>

from codeBehind

var ctrlName = LoadControl("~/Path/control.ascx");
ctrlName.ID="ctrlID";
PhCtrl.Controls.Add(ctrlName);
var sb = new StringBuilder();
sb.Append("$(document).ready(function() {");
sb.Append("$('#trigerButton').fancybox({modal:true}).trigger('click');");
sb.Append("$('#clickNo').click(function(){$.fancybox.close(true)});");
sb.Append("});");
ClientScript.RegisterStartupScript(typeof(T), "_script", sb.ToString(), true);

The custom control

It has a button and this button doesn't fire

<asp:Button runat="server" ID="Button1" Text="Upgrade" OnClick="Button1_click" />
  protected void Button1_click(object s,EventArgs e)
    {
        //Do something
    }

I would appreciate any suggestions

Thanks

SOLUTION

I didn't manage to find a solution without editing the fancybox.js, though I replaced every

appendTo('body')

with

appendTo('form:first')


问:
How to parse tables without classes and keep grouping
I'm trying to parse the following url http://www.trimslabs.com/mic/300.htm for IUPAC, MIC, and Organism strain. I've been able to do so to some extent, although I can't figure out a way to keep the results grouped together. Here's what I've got so far..

```<code>import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
myurl = 'http://www.trimslabs.com/mic/300.htm'
uClient = uReq(myurl)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
#grab IUPACs
tables = page_soup.findAll("table")
table = tables[0]
IUPACS = []
for i in range (1, 454, 3):
    IUPACs = tables[i].find(text = "IUPAC").findNext('td').get_text(",",     strip = True)
    print(IUPACs)
for i in range (455, 661, 3):
    IUPACs_two = tables[i].find(text = "IUPAC").findNext('td').get_text(",", strip = True)
    print(IUPACs_two)
#grab organism names
organism_list = page_soup.findAll("i")
org = organism_list[1]
for org in organism_list:
    organism = org.text
    print(organism)
#get the MIC numbers
for org in organism_list:
    numbers = org.findNext('td').get_text(",", strip = True)
    print(numbers)
</code>```

this will print most the stuff I want, but I completely lose the information about what antibiotic (IUPAC) number their associated with. Realizing that each antibiotic has 3 tables, I've also tried the following

```<code>chem_tables = []
name_tables = []
org_tables = []
results_tables = []
for i in range (0, 451, 3):
    # 1.  Establish three tables per document
    chem_tables.append(tables[i])
    name_tables.append(tables[i + 1].find(text = "IUPAC").findNext('td').get_text(",", strip = True))
    org_tables.append(tables[i + 2].findAll("i"))
    results_tables.append(tables[i + 2].findAll("i").findNext('td'))
</code>```

Which is nice in that now chem_tables[0], org_tables[0] and name_tables[0] all reference one drug, but I cannot for the life of me figure out how to get the individual organism names out of org_tables without losing information about which drug their associated with...

I've been banging my head against the wall on this problem for 2 days now. Any help would be greatly appreciated.

答:
I would make my approach like this:

1) Find the IUPAC cell;

2) Get the value;

3) From the IUPACcell find the nearest table;

4) Find all that table rows and skip the first two and the last one (Useless data);

5) For each row in the second row cell find all the font tags for the Organism values and;

6) Get each value from the third row cell to get the MICvalues;

7) Get each value from 5) and store into a list

8) Split 6) by the comma and store into a list

9) Join everything in a dictionary;

Example code:

```<code>from bs4 import BeautifulSoup
import requests

response = requests.get('http://www.trimslabs.com/mic/300.htm')

soup = BeautifulSoup(response.content, "html.parser")

MicDatabase = []

for IUPAC in soup.find_all(text="IUPAC"):
    Value = IUPAC.find_next('td').get_text(",", strip = True)

    for tr in IUPAC.find_next('table').find_all("tr")[2:-1]:
        td = tr.find_all("td")[1:]

        Organism = td[0].find_all("font")
        MIC = td[1].get_text(",", strip = True)

    MicDatabase.append(
        {
            "IUPAC": Value,
            "ActivityData": {"Organism": [o.get_text(" ", strip=True) for o in Organism], "MIC": MIC.split(',')}
        })
</code>```

Which outputs:

```<code>[{'ActivityData': {'MIC': [u'2-4', u'1-2', u'1-2', u'1-2', u'2-4', u'2-4', u'2-4', u'1-2', u'>16', u'2-4', u'1-2', u'0.25 - 0.5', u'0.25 - 0.5'], 'Organism': [u'B. pumilus ATCC 14348', u'S. epidermidis ATCC 155', u'E. faecalis ATCC 35550', u'S. aureus ATCC 25923', u'S. aureus ATCC 9144', u'S. aureus ATCC 14154', u'S. aureus ATCC 29213', u'S. aureus ATCC 700699', u'(methicillin-resistant)', u'S. aureus NRS 119', u'(linezolid-resistant)', u'E.faecalis ATCC 14506', u'E.faecalis ATCC 700802', u'(vancomycin-resistant)', u'S.pyogenes ATCC 14289', u'S.pneumoniae ATCC 700904', u'(penicillin-resistant)']}, 'IUPAC': u'2-[(S)-3-(3-Fluoro-4-morpholin-4-yl-phenyl)-2-oxo-oxazolidin-5-yl]-acetamide'}...
</code>```

Body:
I'm trying to parse the following url http://www.trimslabs.com/mic/300.htm for IUPAC, MIC, and Organism strain. I've been able to do so to some extent, although I can't figure out a way to keep the results grouped together. Here's what I've got so far..

import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
myurl = 'http://www.trimslabs.com/mic/300.htm'
uClient = uReq(myurl)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
#grab IUPACs
tables = page_soup.findAll("table")
table = tables[0]
IUPACS = []
for i in range (1, 454, 3):
    IUPACs = tables[i].find(text = "IUPAC").findNext('td').get_text(",",     strip = True)
    print(IUPACs)
for i in range (455, 661, 3):
    IUPACs_two = tables[i].find(text = "IUPAC").findNext('td').get_text(",", strip = True)
    print(IUPACs_two)
#grab organism names
organism_list = page_soup.findAll("i")
org = organism_list[1]
for org in organism_list:
    organism = org.text
    print(organism)
#get the MIC numbers
for org in organism_list:
    numbers = org.findNext('td').get_text(",", strip = True)
    print(numbers)

this will print most the stuff I want, but I completely lose the information about what antibiotic (IUPAC) number their associated with. Realizing that each antibiotic has 3 tables, I've also tried the following

chem_tables = []
name_tables = []
org_tables = []
results_tables = []
for i in range (0, 451, 3):
    # 1.  Establish three tables per document
    chem_tables.append(tables[i])
    name_tables.append(tables[i + 1].find(text = "IUPAC").findNext('td').get_text(",", strip = True))
    org_tables.append(tables[i + 2].findAll("i"))
    results_tables.append(tables[i + 2].findAll("i").findNext('td'))

Which is nice in that now chem_tables[0], org_tables[0] and name_tables[0] all reference one drug, but I cannot for the life of me figure out how to get the individual organism names out of org_tables without losing information about which drug their associated with...

I've been banging my head against the wall on this problem for 2 days now. Any help would be greatly appreciated.

Body:
I would make my approach like this:

1) Find the IUPAC cell;

2) Get the value;

3) From the IUPACcell find the nearest table;

4) Find all that table rows and skip the first two and the last one (Useless data);

5) For each row in the second row cell find all the font tags for the Organism values and;

6) Get each value from the third row cell to get the MICvalues;

7) Get each value from 5) and store into a list

8) Split 6) by the comma and store into a list

9) Join everything in a dictionary;

Example code:

from bs4 import BeautifulSoup
import requests

response = requests.get('http://www.trimslabs.com/mic/300.htm')

soup = BeautifulSoup(response.content, "html.parser")

MicDatabase = []

for IUPAC in soup.find_all(text="IUPAC"):
    Value = IUPAC.find_next('td').get_text(",", strip = True)

    for tr in IUPAC.find_next('table').find_all("tr")[2:-1]:
        td = tr.find_all("td")[1:]

        Organism = td[0].find_all("font")
        MIC = td[1].get_text(",", strip = True)

    MicDatabase.append(
        {
            "IUPAC": Value,
            "ActivityData": {"Organism": [o.get_text(" ", strip=True) for o in Organism], "MIC": MIC.split(',')}
        })

Which outputs:

[{'ActivityData': {'MIC': [u'2-4', u'1-2', u'1-2', u'1-2', u'2-4', u'2-4', u'2-4', u'1-2', u'>16', u'2-4', u'1-2', u'0.25 - 0.5', u'0.25 - 0.5'], 'Organism': [u'B. pumilus ATCC 14348', u'S. epidermidis ATCC 155', u'E. faecalis ATCC 35550', u'S. aureus ATCC 25923', u'S. aureus ATCC 9144', u'S. aureus ATCC 14154', u'S. aureus ATCC 29213', u'S. aureus ATCC 700699', u'(methicillin-resistant)', u'S. aureus NRS 119', u'(linezolid-resistant)', u'E.faecalis ATCC 14506', u'E.faecalis ATCC 700802', u'(vancomycin-resistant)', u'S.pyogenes ATCC 14289', u'S.pneumoniae ATCC 700904', u'(penicillin-resistant)']}, 'IUPAC': u'2-[(S)-3-(3-Fluoro-4-morpholin-4-yl-phenyl)-2-oxo-oxazolidin-5-yl]-acetamide'}...


问:
Averageif cell(s) not blank
I am trying to average a percentage commission range on another sheet. On sheet Lines Sales column K I can enter a percentage commission charge if there is one. More frequently I don't have a commission as I am selling my own property.

Through my various searches on here I found that Excel should ignore blank cells in this function and if I want to ignore zeros I should format like this:

```<code>=AVERAGEIF('Line Sales'!K2:'Line Sales'!K150,"<>0")
</code>```

In using this formula with no commissions entered I get a #DIV/0! error. As soon as I enter a commission percentage on a line I get a valid result. I plan to start a new workbook each year to track what I do but I don't want to spend possibly months looking at that error until I get a commission sale.

What I hope to accomplish is to average only commission percentages from K2 to K150 on the Line Sales sheet and have this formula entered into Totals sheet B13, if there are no commission sales I'd like to see it remain blank or be zero.

答:
#DIV/0! error is the expected result for AVERAGEIF if there is nothing to average (it's basically doing the calculation 0/0), so just wrap in an IFERROR function to make the result blank or zero, e.g.

=IFERROR(AVERAGEIF('Line Sales'!K2:K150,"<>0"),"")

Title: Averageif cell(s) not blank

Body:
I am trying to average a percentage commission range on another sheet. On sheet Lines Sales column K I can enter a percentage commission charge if there is one. More frequently I don't have a commission as I am selling my own property.

Through my various searches on here I found that Excel should ignore blank cells in this function and if I want to ignore zeros I should format like this:

=AVERAGEIF('Line Sales'!K2:'Line Sales'!K150,"<>0")

In using this formula with no commissions entered I get a #DIV/0! error. As soon as I enter a commission percentage on a line I get a valid result. I plan to start a new workbook each year to track what I do but I don't want to spend possibly months looking at that error until I get a commission sale.

What I hope to accomplish is to average only commission percentages from K2 to K150 on the Line Sales sheet and have this formula entered into Totals sheet B13, if there are no commission sales I'd like to see it remain blank or be zero.


问:
pip install doesnt work , InvalidSchema: Missing dependencies for SOCKS support
I am freaking out with this error I am struck on for 2 days. 2 days ago activated my virtualenv, then tried to install some dependencies but pip install keeps throwing this error.

```<code>pip install django
Traceback (most recent call last):
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 792, in get_page
    "Cache-Control": "max-age=600",
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 488, in get
    return self.request('GET', url, **kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/download.py", line 386, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 596, in send
    r = adapter.send(request, **kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/adapter.py", line 47, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 390, in send
    conn = self.get_connection(request.url, proxies)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 290, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
    **proxy_kwargs
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 43, in SOCKSProxyManager
    raise InvalidSchema("Missing dependencies for SOCKS support.")
InvalidSchema: Missing dependencies for SOCKS support.
</code>```

I tried installing request[socks], but then I get an error saying that it cannot make out the socks version

```<code>printenv | grep -i proxy
NO_PROXY=localhost,127.0.0.0/8,::1
http_proxy=http://proxy.iiit.ac.in:8080/
FTP_PROXY=http://proxy.iiit.ac.in:8080/
ftp_proxy=http://proxy.iiit.ac.in:8080/
all_proxy=socks://proxy.iiit.ac.in:8080/
ALL_PROXY=socks://proxy.iiit.ac.in:8080/
https_proxy=http://proxy.iiit.ac.in:8080/
HTTPS_PROXY=http://proxy.iiit.ac.in:8080/
no_proxy=localhost,127.0.0.0/8,::1
HTTP_PROXY=http://proxy.iiit.ac.in:8080/
</code>```

This is proxy setting on my system, can anyone help me with this?
Thanks
edit: I tired reinstalling ubuntu, and I am still facing this error

答:
Unset socks proxy, in your case:

unset all_proxy
unset ALL_PROXY

Install missing dependencies:

pip install pysocks

Reset proxy, source .bashrc, and pip install works again with socks proxy.

Body:
I am freaking out with this error I am struck on for 2 days. 2 days ago activated my virtualenv, then tried to install some dependencies but pip install keeps throwing this error.

pip install django
Traceback (most recent call last):
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/index.py", line 792, in get_page
    "Cache-Control": "max-age=600",
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 488, in get
    return self.request('GET', url, **kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/download.py", line 386, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 596, in send
    r = adapter.send(request, **kwargs)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/adapter.py", line 47, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 390, in send
    conn = self.get_connection(request.url, proxies)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 290, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
    **proxy_kwargs
  File "/home/blackpython/.local/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py", line 43, in SOCKSProxyManager
    raise InvalidSchema("Missing dependencies for SOCKS support.")
InvalidSchema: Missing dependencies for SOCKS support.

I tried installing request[socks], but then I get an error saying that it cannot make out the socks version

printenv | grep -i proxy
NO_PROXY=localhost,127.0.0.0/8,::1
http_proxy=http://proxy.iiit.ac.in:8080/
FTP_PROXY=http://proxy.iiit.ac.in:8080/
ftp_proxy=http://proxy.iiit.ac.in:8080/
all_proxy=socks://proxy.iiit.ac.in:8080/
ALL_PROXY=socks://proxy.iiit.ac.in:8080/
https_proxy=http://proxy.iiit.ac.in:8080/
HTTPS_PROXY=http://proxy.iiit.ac.in:8080/
no_proxy=localhost,127.0.0.0/8,::1
HTTP_PROXY=http://proxy.iiit.ac.in:8080/

This is proxy setting on my system, can anyone help me with this?
Thanks
edit: I tired reinstalling ubuntu, and I am still facing this error


问:
how to use like operator in array laravel 5.2?
I want to add Like operator in array but it gives me error:

Unknown column '0' in 'where clause (admin_id = 2 and 0 = name and Like = %zdgbdsh%) order by id asc limit 10 offset 0)

Here is my query:-

```<code>$conditions = array();
if(!empty($data['name'])) {
    $conditions = array_merge($conditions,array('name','Like'=>'%'.$data['name'].'%'));
}
</code>```

And here is my final query:-

```<code>$querys = DB::table('users')
         ->where($conditions)
         ->skip($iDisplayStart)->take($iDisplayLength)
         ->OrderBy($orderby,$dir)
          ->get();
</code>```

Note: I don't want directly in query like

```<code>where('users.name','like','%'.$data['name'].'%');**
</code>```

I want to do in conditions variable
I am using laravel framework 5.2

答:
This is not the greatest way of applying multiple conditions, But you can always user the whereRaw

so loop through a array with your conditions eg.

```<code>$conditions = [];
if (!empty($data['name'])) {
   $conditions = array_merge(
       $conditions,
       ["name LIKE '%".$data['name']."%'"]
   );
}

$query = DB::table('users');

// apply add raw conditions
foreach($conditions as $condition){ $query->whereRaw($condition); }

$query->skip($iDisplayStart)->take($iDisplayLength)
      ->OrderBy($orderby,$dir)
      ->get();
</code>```

you could also find some packages that will help you out with things like this.

Hope it helps

Body:
I want to add Like operator in array but it gives me error:

Unknown column '0' in 'where clause (admin_id = 2 and 0 = name and Like = %zdgbdsh%) order by id asc limit 10 offset 0)

Here is my query:-

$conditions = array();
if(!empty($data['name'])) {
    $conditions = array_merge($conditions,array('name','Like'=>'%'.$data['name'].'%'));
}

And here is my final query:-

$querys = DB::table('users')
         ->where($conditions)
         ->skip($iDisplayStart)->take($iDisplayLength)
         ->OrderBy($orderby,$dir)
          ->get();

Note: I don't want directly in query like

where('users.name','like','%'.$data['name'].'%');**

I want to do in conditions variable
I am using laravel framework 5.2

Body:
This is not the greatest way of applying multiple conditions, But you can always user the whereRaw

so loop through a array with your conditions eg.

$conditions = [];
if (!empty($data['name'])) {
   $conditions = array_merge(
       $conditions,
       ["name LIKE '%".$data['name']."%'"]
   );
}

$query = DB::table('users');

// apply add raw conditions
foreach($conditions as $condition){ $query->whereRaw($condition); }

$query->skip($iDisplayStart)->take($iDisplayLength)
      ->OrderBy($orderby,$dir)
      ->get();

you could also find some packages that will help you out with things like this.

Hope it helps


问:
Alternatives to the Turing Test
So we learned a bit about the Turing Test in my AI class.  This got me thinking about it.  I can see a few limitations with it:

It's limited to a certain context.  What if I'm not designing an AI to converse with humans?

It favors acting humanly over acting rationally.  For example, if I'm designing an AI to control nuclear missiles, do I really want it to act human?  Granted, this is an extreme example, but you get the idea.

It could be influenced by factors that don't indicate that the computer can think humanly.  For example, suppose I ask what 2334 * 321 is.  I could tell if the device is a computer because it will probably answer me fairly quickly while a human would have to figure it out.  The solution?  Make the computer pause.

Now, I'm sure that the Turing Test still has its place in determining machine intelligence.  But I see it as being fairly limited in scope.  Are there any alternatives?  For that matter, am I wrong as to what I perceive to be its limitations?

EDIT:  Let me be clear:  I'm not suggesting that the Turing Test should be abandoned.  I'm just curious if there are any other tests that overcome its limitations (probably trading them for other limitations).

答:
I think you are missing the point of the Turing Test.  It's not meant to be a judge of the quality of an AI algorithm, but rather the success of an AI algorithm meant to simulate human intelligence.  In that sense it is really more a test of the state of the art in AI rather than any particular AI algorithm.  That is, if we can design an AI algorithm to pass this test, then we can say that we are able with AI to develop machines with human intelligence.

It's reasonable to assume that there are other tests that would be equally sufficient, but this test is elegant in its simplicity and relative lack of constraints.  There are basically no constraints on the inputs except their format.

OwnerDisplayName: Jason Baker

ContentLicense: CC BY-SA 2.5

Title: Alternatives to the Turing Test

LastEditorDisplayName: Rob

OwnerDisplayName: tvanfosson


问:
CSS3 Gradients image to transparent
Is there any way i could do an image to transparent gradient in a Background Image in CSS3?

I have tried this: http://jsfiddle.net/meo/e95pw/3/

The goal is to do a mirroring effect in CSS3.

I can not find out the background color behind the reflection, because it could be that there is a background image or pattern.

Any input is welcome.

edit what i need is Photoshop Image Mask but in CSS.

答:
You can achieve this in pure CSS3:

http://jsfiddle.net/g105b/xaX6r/

```<code>/* Example for webkit only */
img{
    margin: 0;
    padding: 0;
    -webkit-box-reflect: below 1px
    -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.4, transparent), to(white));
}
</code>```

Title: CSS3 Gradients image to transparent

Body:
You can achieve this in pure CSS3:

http://jsfiddle.net/g105b/xaX6r/

/* Example for webkit only */
img{
    margin: 0;
    padding: 0;
    -webkit-box-reflect: below 1px
    -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.4, transparent), to(white));
}


答:
It should be:

```<code>$conditions=array_merge($conditions,array('name' => 'Like %'.$data['name'].'%'));
</code>```

Update

I've just realised that will produce name = Like %data%

You can change it to:

```<code>$conditions=array_merge($conditions,array('name', '%'.$data['name'].'%'));
</code>```

and in where use:

```<code>->where(join(' LIKE ', $conditions))
</code>```

Title: how to use like operator in array laravel 5.2?

Body:
It should be:

$conditions=array_merge($conditions,array('name' => 'Like %'.$data['name'].'%'));

Update

I've just realised that will produce name = Like %data%

You can change it to:

$conditions=array_merge($conditions,array('name', '%'.$data['name'].'%'));

and in where use:

->where(join(' LIKE ', $conditions))


问:
PHP Net_SSH2 cannot conect
I am trying to use Net_SSH2 class for login in ssh server and i get error:

Notice:  No compatible server to client encryption algorithms found in /var/www/html/includes/classes/Net/SSH2.php on line 1389

Code in line 1389 was:

```<code>$decrypt = $this->_array_intersect_first($encryption_algorithms, $this->encryption_algorithms_server_to_client);
        $decryptKeyLength = $this->_encryption_algorithm_to_key_size($decrypt);
        if ($decryptKeyLength === null) {
            user_error('No compatible server to client encryption algorithms found');
            return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
        }
</code>```

My PHP file for process:

```<code>$ssh = new Net_SSH2('192.168.111.159');
if (!$ssh->login('root', 'xxxxxxx')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
</code>```

PS. -> i also get Login Failed, but my login was OK i try true terminal on web server its works fine.

Question is why the login fail bat my data was correct and how fix error.

答:
I add on top of SSH2.PHP

```<code>set_include_path('includes/classes/Net/');
</code>```

And login works fine plus error was gone!

Title: PHP Net_SSH2 cannot conect

Body:
I am trying to use Net_SSH2 class for login in ssh server and i get error:

Notice:  No compatible server to client encryption algorithms found in /var/www/html/includes/classes/Net/SSH2.php on line 1389

Code in line 1389 was:

$decrypt = $this->_array_intersect_first($encryption_algorithms, $this->encryption_algorithms_server_to_client);
        $decryptKeyLength = $this->_encryption_algorithm_to_key_size($decrypt);
        if ($decryptKeyLength === null) {
            user_error('No compatible server to client encryption algorithms found');
            return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
        }

My PHP file for process:

$ssh = new Net_SSH2('192.168.111.159');
if (!$ssh->login('root', 'xxxxxxx')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');

PS. -> i also get Login Failed, but my login was OK i try true terminal on web server its works fine.

Question is why the login fail bat my data was correct and how fix error.

Body:
I add on top of SSH2.PHP

set_include_path('includes/classes/Net/');

And login works fine plus error was gone!


问:
Powershell - Invoke-WebRequest to a URL with literal '/' (%2F) in it
I have been trying to access a URL with a / character in it from powershell, using the following command (it's a query to a gitlab server to retrieve a  project called "foo/bar"):

```<code>Invoke-WebRequest https://server.com/api/v3/projects/foo%2Fbar -Verbose
</code>```

Now, the odd thing is that using the PowerShell ISE or Visual Studio, the request is OK. When using PowerShell itself, the URL is automatically un-escaped and the request fails.
E.g.

In ISE/VS:

```<code>$> Invoke-WebRequest https://server.com/api/v3/projects/foo%2Fbar -Verbose
VERBOSE: GET https://server.com/api/v3/projects/foo%2Fbar with 0-byte payload
VERBOSE: received 19903-byte response of content type application/json

StatusCode        : 200
StatusDescription : OK
Content           : .... data ....
</code>```

In Powershell:

```<code>$> Invoke-WebRequest https://server.com/api/v3/projects/foo%2Fbar -Verbose
VERBOSE: GET https://server.com/api/v3/projects/foo/bar with 0-byte payload
Invoke-WebRequest : {"error":"404 Not Found"}
At line:1 char:1
+ Invoke-WebRequest 'https://server.com/api/v3/projects/foo%2Fbar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
</code>```

I have tried adding single and double quotes around the URL, but nothing is helping.

What could be the reason for this behaviour, and how do I make PS not un-escape the URL string?

Environment: Windows 7, also tested on Server 2012R2 with same results.

```<code>$> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.16406
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2
</code>```

答:
Try the URL through this function</p>

```<code>function fixuri($uri){
  $UnEscapeDotsAndSlashes = 0x2000000;
  $SimpleUserSyntax = 0x20000;

  $type = $uri.GetType();
  $fieldInfo = $type.GetField("m_Syntax", ([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic));

  $uriParser = $fieldInfo.GetValue($uri);
  $typeUriParser = $uriParser.GetType().BaseType;
$fieldInfo = $typeUriParser.GetField("m_Flags", ([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::FlattenHierarchy));
$uriSyntaxFlags = $fieldInfo.GetValue($uriParser);

$uriSyntaxFlags = $uriSyntaxFlags -band (-bnot $UnEscapeDotsAndSlashes);
$uriSyntaxFlags = $uriSyntaxFlags -band (-bnot $SimpleUserSyntax);
$fieldInfo.SetValue($uriParser, $uriSyntaxFlags);
}

$uri = New-Object System.Uri -ArgumentList ("https://server.com/api/v3/projects/foo%2Fbar")
fixuri $uri
</code>```

Body:
I have been trying to access a URL with a / character in it from powershell, using the following command (it's a query to a gitlab server to retrieve a  project called "foo/bar"):

Invoke-WebRequest https://server.com/api/v3/projects/foo%2Fbar -Verbose

Now, the odd thing is that using the PowerShell ISE or Visual Studio, the request is OK. When using PowerShell itself, the URL is automatically un-escaped and the request fails.
E.g.

In ISE/VS:

$> Invoke-WebRequest https://server.com/api/v3/projects/foo%2Fbar -Verbose
VERBOSE: GET https://server.com/api/v3/projects/foo%2Fbar with 0-byte payload
VERBOSE: received 19903-byte response of content type application/json

StatusCode        : 200
StatusDescription : OK
Content           : .... data ....

In Powershell:

$> Invoke-WebRequest https://server.com/api/v3/projects/foo%2Fbar -Verbose
VERBOSE: GET https://server.com/api/v3/projects/foo/bar with 0-byte payload
Invoke-WebRequest : {"error":"404 Not Found"}
At line:1 char:1
+ Invoke-WebRequest 'https://server.com/api/v3/projects/foo%2Fbar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

I have tried adding single and double quotes around the URL, but nothing is helping.

What could be the reason for this behaviour, and how do I make PS not un-escape the URL string?

Environment: Windows 7, also tested on Server 2012R2 with same results.

$> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.16406
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

Body:
Try the URL through this function

function fixuri($uri){
  $UnEscapeDotsAndSlashes = 0x2000000;
  $SimpleUserSyntax = 0x20000;

  $type = $uri.GetType();
  $fieldInfo = $type.GetField("m_Syntax", ([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic));

  $uriParser = $fieldInfo.GetValue($uri);
  $typeUriParser = $uriParser.GetType().BaseType;
$fieldInfo = $typeUriParser.GetField("m_Flags", ([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::FlattenHierarchy));
$uriSyntaxFlags = $fieldInfo.GetValue($uriParser);

$uriSyntaxFlags = $uriSyntaxFlags -band (-bnot $UnEscapeDotsAndSlashes);
$uriSyntaxFlags = $uriSyntaxFlags -band (-bnot $SimpleUserSyntax);
$fieldInfo.SetValue($uriParser, $uriSyntaxFlags);
}

$uri = New-Object System.Uri -ArgumentList ("https://server.com/api/v3/projects/foo%2Fbar")
fixuri $uri


问:
assign value as per ratio defined
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

```<code>PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0
</code>```

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?

答:
Something like

```<code>int_weights = [6, 6, 1]
total_weights = sum(int_weights)

to_share = 10

still_to_share = to_share
left_weight_total = total_weights

shares = []
for weight in int_weights:
    s = int(0.5 + (float(still_to_share) * weight / left_weight_total))
    still_left -= s
    left_weight_total -= weight
    shares.append(s)
</code>```

That gives quite but not absolutely fair (which can not be achieved with ties, cf the link I posted in comment of the Question)

```<code>shares
</code>```

[5, 4, 1]

```<code>sum(shares)
</code>```

0

If you want to achieve fairness to the ties, the best result would be [4, 4, 2] (or [5, 5, 0] [:auto_censored_but_not_totally:] ;-) ?) that you can reach by sorting and take into account previous allocation(s). Until I get to a good argument to be that picky I would keep with a solution like shown here-above.

Title: assign value as per ratio defined

Body:
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?

Body:
Something like

int_weights = [6, 6, 1]
total_weights = sum(int_weights)

to_share = 10

still_to_share = to_share
left_weight_total = total_weights

shares = []
for weight in int_weights:
    s = int(0.5 + (float(still_to_share) * weight / left_weight_total))
    still_left -= s
    left_weight_total -= weight
    shares.append(s)

That gives quite but not absolutely fair (which can not be achieved with ties, cf the link I posted in comment of the Question)

shares

[5, 4, 1]

sum(shares)

0

If you want to achieve fairness to the ties, the best result would be [4, 4, 2] (or [5, 5, 0] [:auto_censored_but_not_totally:] ;-) ?) that you can reach by sorting and take into account previous allocation(s). Until I get to a good argument to be that picky I would keep with a solution like shown here-above.


问:
Why do we need two interfaces to enumerate a collection?
It is quite a while that I have been trying to understand the idea behind IEnumerable and IEnumerator. I read all the questions and answers I could find over the net, and on StackOverflow in particular, but I am not satisfied. I got to the point where I understand how those interfaces should be used, but not why they are used this way.

I think that the essence of my misunderstanding is that we need two interfaces for one operation. I realized that if both are needed, one was probably not enough. So I took the "hard coded" equivalent of foreach (as I found here):

```<code>while (enumerator.MoveNext())
{
    object item = enumerator.Current;

    // logic
}
</code>```

and tried to get it to work with one interface, thinking something would go wrong which would make me understand why another interface is needed.

So I created a collection class, and implemented IForeachable:

```<code>class Collection : IForeachable
{
    private int[] array = { 1, 2, 3, 4, 5 };
    private int index = -1;

    public int Current => array[index];

    public bool MoveNext()
    {
        if (index < array.Length - 1)
        {
            index++;
            return true;
        }

        index = -1;
        return false;
    }
}
</code>```

and used the foreach equivalent to nominate the collection:

```<code>var collection = new Collection();

while (collection.MoveNext())
{
    object item = collection.Current;

    Console.WriteLine(item);
}
</code>```

And it works! So what is missing here that make another interface required?

Thanks.

Edit:
My question is not a duplicate of the questions listed in the comments:

This question is why interfaces are needed for enumerating in the first place.

This question and this question are about what are those interfaces and how should they be used.

My question is why they are designed the way they are, not what are they, how they work, and why do we need them in the first place.

答:
What are the two interfaces and what do they do?

The IEnumerable interface is placed on the collection object and defines the GetEnumerator() method, this returns a (normally new) object that has implements the IEnumerator interface. The foreach statement in C# and For Each statement in VB.NET use IEnumerable to access the enumerator in order to loop over the elements in the collection.

The IEnumerator interface is esentially the contract placed on the object that actually does the iteration. It stores the state of the iteration and updates it as the code moves through the collection.

Why not just have the collection be the enumerator too? Why have two separate interfaces?

There is nothing to stop IEnumerator and IEnumerable being implemented on the same class. However, there is a penalty for doing this – It won’t be possible to have two, or more, loops on the same collection at the same time. If it can be absolutely guaranteed that there won’t ever be a need to loop on the collection twice at the same time then that’s fine. But in the majority of circumstances that isn’t possible.

When would someone iterate over a collection more than once at a time?

Here are two examples.

The first example is when there are two loops nested inside each other on the same collection. If the collection was also the enumerator then it wouldn’t be possible to support nested loops on the same collection, when the code gets to the inner loop it is going to collide with the outer loop.

The second example is when there are two, or more, threads accessing the same collection. Again, if the collection was also the enumerator then it wouldn’t be possible to support safe multithreaded iteration over the same collection. When the second thread attempts to loop over the elements in the collection the state of the two enumerations will collide.

Also, because the iteration model used in .NET does not permit alterations to a collection during enumeration these operations are otherwise completely safe.

-- This was from a blog post I wrote many years ago: https://colinmackay.scot/2007/06/24/iteration-in-net-with-ienumerable-and-ienumerator/

Body:
It is quite a while that I have been trying to understand the idea behind IEnumerable and IEnumerator. I read all the questions and answers I could find over the net, and on StackOverflow in particular, but I am not satisfied. I got to the point where I understand how those interfaces should be used, but not why they are used this way.

I think that the essence of my misunderstanding is that we need two interfaces for one operation. I realized that if both are needed, one was probably not enough. So I took the "hard coded" equivalent of foreach (as I found here):

while (enumerator.MoveNext())
{
    object item = enumerator.Current;

    // logic
}

and tried to get it to work with one interface, thinking something would go wrong which would make me understand why another interface is needed.

So I created a collection class, and implemented IForeachable:

class Collection : IForeachable
{
    private int[] array = { 1, 2, 3, 4, 5 };
    private int index = -1;

    public int Current => array[index];

    public bool MoveNext()
    {
        if (index < array.Length - 1)
        {
            index++;
            return true;
        }

        index = -1;
        return false;
    }
}

and used the foreach equivalent to nominate the collection:

var collection = new Collection();

while (collection.MoveNext())
{
    object item = collection.Current;

    Console.WriteLine(item);
}

And it works! So what is missing here that make another interface required?

Thanks.

Edit:
My question is not a duplicate of the questions listed in the comments:

This question is why interfaces are needed for enumerating in the first place.

This question and this question are about what are those interfaces and how should they be used.

My question is why they are designed the way they are, not what are they, how they work, and why do we need them in the first place.


问:
Blank output for an ASP.NET NUnit test application
I am currently working with NUnit to write test cases for an ASP.NET application.

I have created a sample test project and have added NUnit latest version (3.6.1) and NUnitTestAdapter 2.1.1.

If I run the application by clicking on menu Test → Windows → Text Explorer, I am getting a blank screen in the Output Window. Why?

My code is:

```<code>[TestFixture]
public class SampleTest
{
    [Test]
    public void StringCheck()
    {
        string str = "Hello";
        Assert.That(str, Is.EqualTo("Hello"));
    }

    [Test]
    public void EmptyCheck()
    {
        string str = "siva";

        Assert.That(str, Is.EqualTo(string.Empty));
    }

    [Test]
    public void NumberCheck()
    {
        int i = 0;
        Assert.That(i, Is.EqualTo(0));
    }
}
</code>```

答:
You are using the adapter for the NUnit 2.x series, rather than the NUnit 3 adapter. NUnit versions 2 and 3 differ substantially, and there are two separate Visual Studio adapters to run the tests.

This is the one you'll need to run NUnit 3.6.1 tests:

NUnit 3 Test Adapter

ContentLicense: CC BY-SA 4.0

Body:
I am currently working with NUnit to write test cases for an ASP.NET application.

I have created a sample test project and have added NUnit latest version (3.6.1) and NUnitTestAdapter 2.1.1.

If I run the application by clicking on menu Test → Windows → Text Explorer, I am getting a blank screen in the Output Window. Why?

My code is:

[TestFixture]
public class SampleTest
{
    [Test]
    public void StringCheck()
    {
        string str = "Hello";
        Assert.That(str, Is.EqualTo("Hello"));
    }

    [Test]
    public void EmptyCheck()
    {
        string str = "siva";

        Assert.That(str, Is.EqualTo(string.Empty));
    }

    [Test]
    public void NumberCheck()
    {
        int i = 0;
        Assert.That(i, Is.EqualTo(0));
    }
}


问:
ActionView::Template::Error (Model User does not respond to password):
After upgrading rails from 3.0.0 to 3.0.1 and passenger to 3.0 I am getting this error in production:

```<code>ActionView::Template::Error (Model User does not respond to password):
23:
24: <p>
25:     <%= f.label :password %><br />
26:     <%= f.password_field :password %>
27:   </p>
28: <p>
29:     <%= f.label :password_confirmation %><br />
app/views/users/new.html.erb:26:in `_app_views_users_new_html_erb___104064734$
</code>```

In development this page works fine but with some deprecation warnings:

```<code>Started GET "/users/new" for 127.0.0.1 at Sat Nov 06 22:08:49 -0700 2010
Processing by UsersController#new as HTML
DEPRECATION WARNING: Base.named_scope has been deprecated, please use Base.scope instead. (called from included at /home/sean/chief/vendor/plugins/authlogic/lib/authlogic/acts_as_authentic/logged_in_status.rb:35)
DEPRECATION WARNING: Base.named_scope has been deprecated, please use Base.scope instead. (called from included at /home/sean/chief/vendor/plugins/authlogic/lib/authlogic/acts_as_authentic/logged_in_status.rb:36)
Rendered users/new.html.erb within layouts/application (25.3ms)
Completed 200 OK in 70ms (Views: 32.5ms | ActiveRecord: 1.0ms)
</code>```

答:
I ran into a similar error when testing my application on heroku. For me, the fix was as simple as updating my rails gem to the latest 3.0.3 (I am also using authlogic from a git source). I.e. my Gemfile contains the following:

```<code>gem 'rails', '3.0.3'
gem 'authlogic', :git => 'git://github.com/odorcicd/authlogic.git', :branch => 'rails3'
</code>```

I then ran:

```<code>bundle update
</code>```

To rebuild my snapshot from scratch, and this resolved the (Model  does not respond to password) error that I was getting.

Hope this fixes your similar problem as well.

Body:
After upgrading rails from 3.0.0 to 3.0.1 and passenger to 3.0 I am getting this error in production:

ActionView::Template::Error (Model User does not respond to password):
23:
24:

25:     <%= f.label :password %>

26:     <%= f.password_field :password %>
27:

28:

29:     <%= f.label :password_confirmation %>

app/views/users/new.html.erb:26:in `_app_views_users_new_html_erb___104064734$

In development this page works fine but with some deprecation warnings:

Started GET "/users/new" for 127.0.0.1 at Sat Nov 06 22:08:49 -0700 2010
Processing by UsersController#new as HTML
DEPRECATION WARNING: Base.named_scope has been deprecated, please use Base.scope instead. (called from included at /home/sean/chief/vendor/plugins/authlogic/lib/authlogic/acts_as_authentic/logged_in_status.rb:35)
DEPRECATION WARNING: Base.named_scope has been deprecated, please use Base.scope instead. (called from included at /home/sean/chief/vendor/plugins/authlogic/lib/authlogic/acts_as_authentic/logged_in_status.rb:36)
Rendered users/new.html.erb within layouts/application (25.3ms)
Completed 200 OK in 70ms (Views: 32.5ms | ActiveRecord: 1.0ms)

Body:
I ran into a similar error when testing my application on heroku. For me, the fix was as simple as updating my rails gem to the latest 3.0.3 (I am also using authlogic from a git source). I.e. my Gemfile contains the following:

gem 'rails', '3.0.3'
gem 'authlogic', :git => 'git://github.com/odorcicd/authlogic.git', :branch => 'rails3'

I then ran:

bundle update

To rebuild my snapshot from scratch, and this resolved the (Model  does not respond to password) error that I was getting.

Hope this fixes your similar problem as well.


问:
plt.tight_layout buggy with long titles?
The problem:

How come every plt.tight_layout() shrinks the figure a bit more even after a fresh start with plt.clf()?

Take this snippet:

```<code>plt.figure(1).clf()
plt.plot(range(10))
plt.title("Blah")
plt.tight_layout()

for _ in range(5):
    plt.figure(2).clf()
    plt.plot(range(10))
    plt.title("Blah")
    plt.tight_layout()
</code>```

As expected figures 1 and 2 are identical.

But now make the title very long:

```<code>plt.figure(3).clf()
plt.plot(range(10))
plt.title("Blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
plt.tight_layout()

for _ in range(5):
    plt.figure(4).clf()
    plt.plot(range(10))
    plt.title("Blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
    plt.tight_layout()
</code>```

and figures 3 and 4 are non longer identical, figure 4 being shrunk horizontally  and this shrinkage increases with the number of loops.

If someone can shed some light on this...

Some background info:

You might ask "Why on earth would you put such plotting stuff in a for loop?". I actually don't but I have an interactive script where I may replot the same figure several times with some variation, and this shrinkage appears just the same...

My python version is:

```<code>Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)]
</code>```

And BTW, if you increase the number of plt.tight_layout() calls enough, you eventually get an error:

```<code>Traceback (most recent call last):

  File "<ipython-input-89-1a59da108bdf>", line 5, in <module>
    plt.tight_layout()

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\pyplot.py", line 1379, in tight_layout
    fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1756, in tight_layout
    self.subplots_adjust(**kwargs)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1612, in subplots_adjust
    self.subplotpars.update(*args, **kwargs)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 226, in update
    raise ValueError('left cannot be >= right')

ValueError: left cannot be >= right
</code>```

答:
While you are clearing the figure, the figure keeps its SubplotParams, which have been adjusted by the call to tight_layout.

Consider the following code:

```<code>import matplotlib.pyplot as plt

left = []; right = []
def print_subplotparams(sp):
    t = "left={left:.3f}, right={right:.3f}, top={top:.3f}, bottom={bottom:.3f}"
    t = t.format(left=sp.left, right=sp.right, top=sp.top, bottom=sp.bottom)
    left.append(sp.left); right.append(sp.right)
    print(t)

fig = plt.figure(1)
print_subplotparams(fig.subplotpars)
fig.clear()

for _ in range(8):
    fig = plt.figure(1)
    # uncomment to see difference
    #fig.subplots_adjust(left=0.125, right=0.900, top=0.880, bottom=0.110)
    plt.plot(range(10))
    plt.title("Blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
    plt.tight_layout()
    print_subplotparams(fig.subplotpars)
    fig.clear()

fig = plt.figure(2, figsize=(5,3))
plt.plot(range(len(left)), left, label="left")
plt.plot(range(len(right)), right, label="right")
plt.title("SubplotParams left/right as function of calls to tight_layout")
plt.xlabel("number of call to tight_layout")
plt.ylabel("left/right parameter")
plt.tight_layout()
plt.show()
</code>```

which produces:

As can be seen, in each loop step tight_layout adjusts from the already adjusted paramters and makes them even smaller.

To prevent that one might reset the SubplotParams in each step

```<code>fig.subplots_adjust(left=0.125, right=0.900, top=0.880, bottom=0.110)
</code>```

In this case tight_layout always optimizes starting with the same initial parameters and their final values will not change.

Body:
The problem:

How come every plt.tight_layout() shrinks the figure a bit more even after a fresh start with plt.clf()?

Take this snippet:

plt.figure(1).clf()
plt.plot(range(10))
plt.title("Blah")
plt.tight_layout()

for _ in range(5):
    plt.figure(2).clf()
    plt.plot(range(10))
    plt.title("Blah")
    plt.tight_layout()

As expected figures 1 and 2 are identical.

But now make the title very long:

plt.figure(3).clf()
plt.plot(range(10))
plt.title("Blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
plt.tight_layout()

for _ in range(5):
    plt.figure(4).clf()
    plt.plot(range(10))
    plt.title("Blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
    plt.tight_layout()

and figures 3 and 4 are non longer identical, figure 4 being shrunk horizontally  and this shrinkage increases with the number of loops.

If someone can shed some light on this...

Some background info:

You might ask "Why on earth would you put such plotting stuff in a for loop?". I actually don't but I have an interactive script where I may replot the same figure several times with some variation, and this shrinkage appears just the same...

My python version is:

Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)]

And BTW, if you increase the number of plt.tight_layout() calls enough, you eventually get an error:

Traceback (most recent call last):

  File "<ipython-input-89-1a59da108bdf>", line 5, in <module>
    plt.tight_layout()

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\pyplot.py", line 1379, in tight_layout
    fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1756, in tight_layout
    self.subplots_adjust(**kwargs)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1612, in subplots_adjust
    self.subplotpars.update(*args, **kwargs)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 226, in update
    raise ValueError('left cannot be >= right')

ValueError: left cannot be >= right

Body:
While you are clearing the figure, the figure keeps its SubplotParams, which have been adjusted by the call to tight_layout.

Consider the following code:

import matplotlib.pyplot as plt

left = []; right = []
def print_subplotparams(sp):
    t = "left={left:.3f}, right={right:.3f}, top={top:.3f}, bottom={bottom:.3f}"
    t = t.format(left=sp.left, right=sp.right, top=sp.top, bottom=sp.bottom)
    left.append(sp.left); right.append(sp.right)
    print(t)

fig = plt.figure(1)
print_subplotparams(fig.subplotpars)
fig.clear()

for _ in range(8):
    fig = plt.figure(1)
    # uncomment to see difference
    #fig.subplots_adjust(left=0.125, right=0.900, top=0.880, bottom=0.110)
    plt.plot(range(10))
    plt.title("Blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
    plt.tight_layout()
    print_subplotparams(fig.subplotpars)
    fig.clear()

fig = plt.figure(2, figsize=(5,3))
plt.plot(range(len(left)), left, label="left")
plt.plot(range(len(right)), right, label="right")
plt.title("SubplotParams left/right as function of calls to tight_layout")
plt.xlabel("number of call to tight_layout")
plt.ylabel("left/right parameter")
plt.tight_layout()
plt.show()

which produces:

As can be seen, in each loop step tight_layout adjusts from the already adjusted paramters and makes them even smaller.

To prevent that one might reset the SubplotParams in each step

fig.subplots_adjust(left=0.125, right=0.900, top=0.880, bottom=0.110)

In this case tight_layout always optimizes starting with the same initial parameters and their final values will not change.


问:
Python/Django displaying images
I'm new in django and i got a problem. I have a html table with images and some data and depending on which one you select image should be displayed on next page, but i have problem with displaying the image, all i get is broken icon. Images work on first page but something is wrong with the selected page.
Could anyone help me? (I'm using django 1.10)

models.py

```<code>class Tags(models.Model):
    tag_name = models.CharField(max_length=250)
    tag_chip_type = models.CharField(max_length=250)
    tag_size = models.CharField(max_length=250)
    tag_frequency = models.CharField(max_length=250)
    tag_standards = models.CharField(max_length=250, null=True, blank=True)
    tag_memory = models.CharField(max_length=250)
    tag_reading_distance = models.CharField(max_length=250)
    tag_environment = models.CharField(max_length=250)
    tag_mounting_method = models.CharField(max_length=250)
    tag_operating_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_storage_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_chemical_and_environmental_resistances = models.CharField(max_length=500, null=True, blank=True)
    tag_image = models.FileField()

    def __unicode__(self):
        return self.tag_name + ' ' + self.tag_image.url

    def get_absolute_url(self):
        return reverse('tag:index')
</code>```

views.py

```<code>def selected(request):
    tags = request.GET.getlist('selected')
    return render(request, 'tag/selected.html', {'all_tags':tags})
</code>```

urls.py

```<code>if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

index.html

```<code><form action="{% url 'tag:selected' %}" method="get">
        <table id="selected" class="white-table table-bordered table-hover" style="width:95%; margin: 3% auto;">
             <thead>
                 <tr>
                     <th style="text-align:center;"><input type="checkbox" onClick="toggle(this)"></th>
                     <th></th>
                     <th style="text-align:center;">Name</th>
                     <th style="text-align:center;">Chip Type</th>
                     <th style="text-align:center;">Size</th>
                     <th style="text-align:center;">Frequency</th>
                     <th style="text-align:center;">Memory</th>
                     <th style="text-align:center;">Reading distance</th>
                     <th class="null" style="text-align:center;">Environment</th>
                     <th class="null" style="text-align:center;">Mounting method</th>
                 </tr>
             </thead>
  <tbody>
  {% for tags in all_tags %}

            <tr>
            <td style="text-align:center;"><input type="checkbox"  name="selected" value="{{ tags.tag_image.url }}"></td>
            <td><a href="{% url 'tag:detail' tags.id %}"> <img src="{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" /> </a></td>
            <td style="text-align:center;"> {{ tags.tag_name }} </td>
            <td style="text-align:center;"> {{ tags.tag_chip_type }} </td>
            <td style="text-align:center;"> {{ tags.tag_size }} </td>
            <td style="text-align:center;"> {{ tags.tag_frequency }} </td>
            <td style="text-align:center;"> {{ tags.tag_memory }} </td>
            <td style="text-align:center;"> {{ tags.tag_reading_distance }} </td>
            <td class="null" style="text-align:center;"> {{ tags.tag_environment }} </td>
            <td class="null" style="text-align:center;"> {{ tags.tag_mounting_method }} </td>
            </tr>
  {% endfor %}
            </tbody>
        </table>
        <input class="btn-primary" style="float:right; margin-right:2.5%; margin-bottom:3%;" type="submit" value="Submit">
    </form>

{% endblock %}
</code>```

settings.py

```<code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code>```

selected.html

```<code>{% block body %}

{% for tags in all_tags %}
    <div class=" col-md-4">
            <div class="panel panel-default">
                <div class="panel-body">
<img src=" '/media/'{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" />
        </div>
    </div>
</div>
{% endfor %}
{% endblock %}
</code>```

答: First you have to make sure your pictures can be displayed, with http: //xxxxxxx/xxx/you.jpg in the browser test</p>

Title: Python/Django displaying images

Body:
I'm new in django and i got a problem. I have a html table with images and some data and depending on which one you select image should be displayed on next page, but i have problem with displaying the image, all i get is broken icon. Images work on first page but something is wrong with the selected page.
Could anyone help me? (I'm using django 1.10)

models.py

class Tags(models.Model):
    tag_name = models.CharField(max_length=250)
    tag_chip_type = models.CharField(max_length=250)
    tag_size = models.CharField(max_length=250)
    tag_frequency = models.CharField(max_length=250)
    tag_standards = models.CharField(max_length=250, null=True, blank=True)
    tag_memory = models.CharField(max_length=250)
    tag_reading_distance = models.CharField(max_length=250)
    tag_environment = models.CharField(max_length=250)
    tag_mounting_method = models.CharField(max_length=250)
    tag_operating_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_storage_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_chemical_and_environmental_resistances = models.CharField(max_length=500, null=True, blank=True)
    tag_image = models.FileField()

    def __unicode__(self):
        return self.tag_name + ' ' + self.tag_image.url

    def get_absolute_url(self):
        return reverse('tag:index')

views.py

def selected(request):
    tags = request.GET.getlist('selected')
    return render(request, 'tag/selected.html', {'all_tags':tags})

urls.py

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

index.html

<form action="{% url 'tag:selected' %}" method="get">

                     <input type="checkbox" onClick="toggle(this)">

                     Name
                     Chip Type
                     Size
                     Frequency
                     Memory
                     Reading distance
                     Environment
                     Mounting method

  {% for tags in all_tags %}

            <input type="checkbox"  name="selected" value="{{ tags.tag_image.url }}">

             {{ tags.tag_name }}
             {{ tags.tag_chip_type }}
             {{ tags.tag_size }}
             {{ tags.tag_frequency }}
             {{ tags.tag_memory }}
             {{ tags.tag_reading_distance }}
             {{ tags.tag_environment }}
             {{ tags.tag_mounting_method }}

  {% endfor %}

        <input class="btn-primary" style="float:right; margin-right:2.5%; margin-bottom:3%;" type="submit" value="Submit">
    </form>

{% endblock %}

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

selected.html

{% block body %}

{% for tags in all_tags %}

{% endfor %}
{% endblock %}


问:
query with order by and where does not work
I am trying to get visit_no using below query:

```<code>String strNumber = "SELECT visit_no from tracking order by id DESC limit 1 where c_no = '" + string1 + "' ";
Log.d("strNumber:", strNumber);
</code>```

Whenever, I run above query getting same query in a log, not the actual visit_no because, later I need to use same visit_no in below query see visit_no = strNumber.

```<code>db.execSQL("update csv set visit_no = strNumber where c_no = '" + string1 + "' ");
</code>```

So here is the complete method, where I have written everything

```<code>public void checkingRecord(String string1) {

  SQLiteDatabase db = this.getWritableDatabase();

  String strNumber = "SELECT visit_no from tracking order by id DESC limit 1 where c_no = '" + string1 + "' ";
  // db.execSQL(strNumber);

  db.execSQL("update csv set visit_no = strNumber where c_no = '" + string1 + "' ");

  db.close();

}
</code>```

答:
As shown in the documentation, the WHERE clause must come before the ORDER BY.

And when string1 contains a quote, everything will blow up. You should use parameters to insert strings into SQL.

And if you have two queries, you have to execute the first one, read its result, and then execute the second one.
But it is possible to do everythig at once with a subquery:

String sql = "UPDATE csv "+
             "SET visit_no = (SELECT visit_no "+
                             "FROM tracking "+
                             "WHERE c_no = ? "+
                             "ORDER BY id DESC "+
                             "LIMIT 1 "+
                            ") "+
             "WHERE c_no = ?";
db.execSQL(sql, new Object[]{ string1, string1 });
```

Body:
I am trying to get visit_no using below query:

String strNumber = "SELECT visit_no from tracking order by id DESC limit 1 where c_no = '" + string1 + "' ";
Log.d("strNumber:", strNumber);

Whenever, I run above query getting same query in a log, not the actual visit_no because, later I need to use same visit_no in below query see visit_no = strNumber.

db.execSQL("update csv set visit_no = strNumber where c_no = '" + string1 + "' ");

So here is the complete method, where I have written everything

public void checkingRecord(String string1) {

  SQLiteDatabase db = this.getWritableDatabase();

  String strNumber = "SELECT visit_no from tracking order by id DESC limit 1 where c_no = '" + string1 + "' ";
  // db.execSQL(strNumber);

  db.execSQL("update csv set visit_no = strNumber where c_no = '" + string1 + "' ");

  db.close();

}