问:
Error when If statement to definition. (Python)
so I'm very basic with coding and Python. I used to be much better but haven't used it in some time and I'm trying to get back into the swing of things. I'm trying to execute an If statement, where input is asked for a username and password, if correct it then goes to a "definition" I think it's called, where it then executes the code in def access()

Code:

```<code>def main():

    userName = ("u123")
    userPass = ("p123")

    userNameInput = input("Username: ")
    userPassInput = input("Password: ")

    if userPassInput == userPass and userNameInput == userName:
        print("Access granted")
        access()

    else:
        print("Access denied")
        return main()

    def access():

        print("Welcome, " + userName)

    access()

main()
</code>```

However, I get this error when the correct inputs are executed:

```<code>Username: u123
Password: p123
Access granted
Traceback (most recent call last):
  File "C:/Users/Tom/Desktop/test.py", line 23, in <module>
    main()
  File "C:/Users/Tom/Desktop/test.py", line 11, in main
    access()
UnboundLocalError: local variable 'access' referenced before assignment
>>>
</code>```

Any help will be appreciated, thank you.

答:
You're trying to invoke access() before it is declared! This is because the code defining access() is placed after its declaration, so your code is essentially trying to find a function that doesn't exist (yet)! This is a scoping issue, and is fairly common!

The code below (by placing the definition of access() outside of main()) works:

```<code>def main():

    userName = ("u123")
    userPass = ("p123")

    userNameInput = input("Username: ")
    userPassInput = input("Password: ")

    if userPassInput == userPass and userNameInput == userName:
        print("Access granted")
        access(userName)

    else:
        print("Access denied")
        return main()

def access(userName):
    print("Welcome, " + userName)

main()
</code>```

I also do not believe it is recommended to define a function within a function (for this type of project), rather you can create a class with various functions inside:

```<code>class Login:
    def __init__(self):
        self.users = {}
        self.userName = ("u123")
        self.userPass = ("p123")

    def addUser(self, uname, upass):
        self.users[uname] = upass;

    def login(self):
        userNameInput = input("Username: ")
        userPassInput = input("Password: ")
        if userNameInput in self.users:
            if self.users[userNameInput] == userPassInput:
                print("Access granted")
                self.access(userNameInput)
            else:
                print("Access denied")
                return self.login()
        else:
            print("Access denied")
            return self.login()

    def access(self, username):
        print("Welcome, "+username+"!")

def main():
    mylogin = Login()
    mylogin.addUser("u123","p123")
    mylogin.login()

main()
</code>```

Going forward, you'll have to implement some sort of security (the code above has NONE! so be sure not to use it for important things. DO NOT use dictionaries of users and passwords, that's just for show!).

Hope it helps rekindle your love of Python!

Body:
so I'm very basic with coding and Python. I used to be much better but haven't used it in some time and I'm trying to get back into the swing of things. I'm trying to execute an If statement, where input is asked for a username and password, if correct it then goes to a "definition" I think it's called, where it then executes the code in def access()

Code:

def main():

    userName = ("u123")
    userPass = ("p123")

    userNameInput = input("Username: ")
    userPassInput = input("Password: ")

    if userPassInput == userPass and userNameInput == userName:
        print("Access granted")
        access()

    else:
        print("Access denied")
        return main()

    def access():

        print("Welcome, " + userName)

    access()

main()

However, I get this error when the correct inputs are executed:

Username: u123
Password: p123
Access granted
Traceback (most recent call last):
  File "C:/Users/Tom/Desktop/test.py", line 23, in <module>
    main()
  File "C:/Users/Tom/Desktop/test.py", line 11, in main
    access()
UnboundLocalError: local variable 'access' referenced before assignment
>>>

Any help will be appreciated, thank you.

Body:
You're trying to invoke access() before it is declared! This is because the code defining access() is placed after its declaration, so your code is essentially trying to find a function that doesn't exist (yet)! This is a scoping issue, and is fairly common!

The code below (by placing the definition of access() outside of main()) works:

def main():

    userName = ("u123")
    userPass = ("p123")

    userNameInput = input("Username: ")
    userPassInput = input("Password: ")

    if userPassInput == userPass and userNameInput == userName:
        print("Access granted")
        access(userName)

    else:
        print("Access denied")
        return main()

def access(userName):
    print("Welcome, " + userName)

main()

I also do not believe it is recommended to define a function within a function (for this type of project), rather you can create a class with various functions inside:

class Login:
    def __init__(self):
        self.users = {}
        self.userName = ("u123")
        self.userPass = ("p123")

    def addUser(self, uname, upass):
        self.users[uname] = upass;

    def login(self):
        userNameInput = input("Username: ")
        userPassInput = input("Password: ")
        if userNameInput in self.users:
            if self.users[userNameInput] == userPassInput:
                print("Access granted")
                self.access(userNameInput)
            else:
                print("Access denied")
                return self.login()
        else:
            print("Access denied")
            return self.login()

    def access(self, username):
        print("Welcome, "+username+"!")

def main():
    mylogin = Login()
    mylogin.addUser("u123","p123")
    mylogin.login()

main()

Going forward, you'll have to implement some sort of security (the code above has NONE! so be sure not to use it for important things. DO NOT use dictionaries of users and passwords, that's just for show!).

Hope it helps rekindle your love of Python!


来源: stackexchange

问:
HtmlUnit: saving pdf link
How do I download a pdfLink from a website using HtmlUnit?
The default return from HtmlClient.getPage() is an HtmlPage. This does not handle pdf Files.</p>

答:
The answer is that HtmlClient.getPage will return an UnexpectedPage if the response was not  an html file. THen you can get the pdf as an inputstream and save.

```<code>private void grabPdf(String urlNow)
{
    OutputStream outStream =null;
    InputStream is = null;
    try
    {
        if(urlNow.endsWith(".pdf"))
        {
            final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_45);
            try
            {
                setWebClientOptions(webClient);
                final UnexpectedPage pdfPage = webClient.getPage(urlNow);
                is = pdfPage.getWebResponse().getContentAsStream();

                String fileName = "myfilename";
                fileName = fileName.replaceAll("[^A-Za-z0-9]", "");

                File targetFile = new File(outputPath + File.separator + fileName  + ".pdf");
                outStream = new FileOutputStream(targetFile);
                byte[] buffer = new byte[8 * 1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1)
                {
                    outStream.write(buffer, 0, bytesRead);
                }

            }
            catch (Exception e)
            {
                NioLog.getLogger().error(e.getMessage(), e);
            }
            finally
            {
                webClient.close();
                if(null!=is)
                {
                    is.close();
                }
                if(null!=outStream)
                {
                    outStream.close();
                }
            }
        }
    }
    catch (Exception e)
    {
        NioLog.getLogger().error(e.getMessage(), e);
    }

}
</code>```

Sidenote. I didn't use try with resources because the outputstream can only be initialized within the try block. I could break into two methods but that would be cognitively slower for the programmer to read.

ContentLicense: CC BY-SA 3.0

Title: HtmlUnit: saving pdf link

Body:
The answer is that HtmlClient.getPage will return an UnexpectedPage if the response was not  an html file. THen you can get the pdf as an inputstream and save.

private void grabPdf(String urlNow)
{
    OutputStream outStream =null;
    InputStream is = null;
    try
    {
        if(urlNow.endsWith(".pdf"))
        {
            final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_45);
            try
            {
                setWebClientOptions(webClient);
                final UnexpectedPage pdfPage = webClient.getPage(urlNow);
                is = pdfPage.getWebResponse().getContentAsStream();

                String fileName = "myfilename";
                fileName = fileName.replaceAll("[^A-Za-z0-9]", "");

                File targetFile = new File(outputPath + File.separator + fileName  + ".pdf");
                outStream = new FileOutputStream(targetFile);
                byte[] buffer = new byte[8 * 1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1)
                {
                    outStream.write(buffer, 0, bytesRead);
                }

            }
            catch (Exception e)
            {
                NioLog.getLogger().error(e.getMessage(), e);
            }
            finally
            {
                webClient.close();
                if(null!=is)
                {
                    is.close();
                }
                if(null!=outStream)
                {
                    outStream.close();
                }
            }
        }
    }
    catch (Exception e)
    {
        NioLog.getLogger().error(e.getMessage(), e);
    }

}

Sidenote. I didn't use try with resources because the outputstream can only be initialized within the try block. I could break into two methods but that would be cognitively slower for the programmer to read.


问:
awk to match on keyword and check sub pattern of another field
In the awk below I am trying to print the entire line, along with the header row, if $3 is SNV or MNV or INDEL. If that condition is met or it true, then in $4 the sub pattern :GMAF= is found and the value after the = sign is checked. If that value is less than or equal to .01 then the entire line, along with header row, is printed.

Since it is possible for $3 to be SNV and $4 to be blank or null, then I am not sure how to capture this as well. Line 2 is an example of this. The assumption is that if there is no value in $4 then this is the same as zero so may be significant and is extracted. I am also not sure how to include the header row minus the # in the print. The --- are not part of the file, they are just there to indicate the header. I added comments to each line as well.  Thank you :).

file  tab-delimited

```<code>##.....
##.....
#ID Name    Func    List     ---- header row ----
1   1   REF
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
</code>```

desired output  tab-delimited

```<code>ID  Name    Func    List
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
</code>```

awk

```<code>awk -F'\t' -v OFS='\t' 'NR>3   # define FS and OFS as tab and look in 3 row of file
        $3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL"{   # start block and look in row 3 in`$2` for any of these words
        sub(/:GMAF=*/,"",$4);  # if found then search `$4` for `:GMAF=`
        VAL=substr($4,RSTART+4,RLENGTH-4);   3 extract the 4 digits after the = sign as VAL
                                             }  # close block
            for(i=1;i<=num;i++){   # create a loop to iterate over each line as i
                    if(VAL[i] <= 0.01){  3 check each VAL in iand if less then or equal to 0.01
                    {  # start block
                                    print $1, $2, $3, VAL;  # print output
                                      }  # end block
                next   # process next line
                }  # end block
                1' file
</code>```

Edit by Ed Morton just to format the above code to be easier to understand:

```<code>awk -F'\t' -v OFS='\t' '                           # define FS and OFS as tab
    NR>3                                           # and look in 3 row of file

    $3 == "SNV" || $3 == "MNV" || $3 == "INDEL" {  # start block and look in row 3 in`$2` for any of these words
        sub(/:GMAF=*/,"",$4);                      # if found then search `$4` for `:GMAF=`
        VAL=substr($4,RSTART+4,RLENGTH-4);         3 extract the 4 digits after the = sign as VAL
    }                                              # close block

    for(i=1;i<=num;i++) {                          # create a loop to iterate over each line as i
        if(VAL[i] <= 0.01) {                       3 check each VAL in iand if less then or equal to 0.01
            {                                      # start block
                print $1, $2, $3, VAL;             # print output
            }                                      # end block
            next                                   # process next line
        }                                          # end block
1' file
</code>```

答:
Short answer:

To catch the case that $4 is unset/blank/non existing, that would mean for awk that total number of fields is 3 (NF==3)

To delete the # in front of header row, you can use any subsitute technique (i.e sub). I used gensub in my test.

Full answer:

The bellow code seems that fits to your needs. Though i have not used a tab-delimited file, but you can adjust accordingly to your tabulated file.

```<code>$ cat file4
##.....
##.....
#ID Name    Func    List
1   1   REF
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
4   4   RNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
5   5   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.14
6   6   INDEL
7   7   RNV
8   8   SNV GMAF=0.0041:EMAF=0.0:AMAF=0.0014
9   9   SNV EMAF=0.0041:GMAF=0.1:AMAF=0.0014

$ awk 'NR<3{next}NR==3{print gensub(/^#/,"","1");next}($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") && NF==3{print;next}
($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") {val=gensub(/.*GMAF=(.[^:]*).*/,"\\1","g",$4);if (val<=0.1) print}' file4
ID  Name    Func    List
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
6   6   INDEL
8   8   SNV GMAF=0.0041:EMAF=0.0:AMAF=0.0014
9   9   SNV EMAF=0.0041:GMAF=0.1:AMAF=0.0014
</code>```

Explanation:

```<code>awk 'NR<3{next}                                                       # skip the first two lines
     NR==3{print gensub(/^#/,"","1");next}                            # print the third line (header) by removing the leading #
     ($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") && NF==3{print;next} # Print the lines missing $4 and go to next line
     ($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") {                    # if $3 fullfils the criteria then
        val=gensub(/.*GMAF=(.[^:]*).*/,"\\1","g",$4);                 # isolate the value of GMAF with regex
        if (val<=0.1) print;                                          # compare and print
        }' file4
</code>```

Body:
In the awk below I am trying to print the entire line, along with the header row, if $3 is SNV or MNV or INDEL. If that condition is met or it true, then in $4 the sub pattern :GMAF= is found and the value after the = sign is checked. If that value is less than or equal to .01 then the entire line, along with header row, is printed.

Since it is possible for $3 to be SNV and $4 to be blank or null, then I am not sure how to capture this as well. Line 2 is an example of this. The assumption is that if there is no value in $4 then this is the same as zero so may be significant and is extracted. I am also not sure how to include the header row minus the # in the print. The --- are not part of the file, they are just there to indicate the header. I added comments to each line as well.  Thank you :).

file  tab-delimited

##.....
##.....
#ID Name    Func    List     ---- header row ----
1   1   REF
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014

desired output  tab-delimited

ID  Name    Func    List
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014

awk

awk -F'\t' -v OFS='\t' 'NR>3   # define FS and OFS as tab and look in 3 row of file
        $3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL"{   # start block and look in row 3 in`$2` for any of these words
        sub(/:GMAF=*/,"",$4);  # if found then search `$4` for `:GMAF=`
        VAL=substr($4,RSTART+4,RLENGTH-4);   3 extract the 4 digits after the = sign as VAL
                                             }  # close block
            for(i=1;i<=num;i++){   # create a loop to iterate over each line as i
                    if(VAL[i] <= 0.01){  3 check each VAL in iand if less then or equal to 0.01
                    {  # start block
                                    print $1, $2, $3, VAL;  # print output
                                      }  # end block
                next   # process next line
                }  # end block
                1' file

Edit by Ed Morton just to format the above code to be easier to understand:

awk -F'\t' -v OFS='\t' '                           # define FS and OFS as tab
    NR>3                                           # and look in 3 row of file

    $3 == "SNV" || $3 == "MNV" || $3 == "INDEL" {  # start block and look in row 3 in`$2` for any of these words
        sub(/:GMAF=*/,"",$4);                      # if found then search `$4` for `:GMAF=`
        VAL=substr($4,RSTART+4,RLENGTH-4);         3 extract the 4 digits after the = sign as VAL
    }                                              # close block

    for(i=1;i<=num;i++) {                          # create a loop to iterate over each line as i
        if(VAL[i] <= 0.01) {                       3 check each VAL in iand if less then or equal to 0.01
            {                                      # start block
                print $1, $2, $3, VAL;             # print output
            }                                      # end block
            next                                   # process next line
        }                                          # end block
1' file

Body:
Short answer:

To catch the case that $4 is unset/blank/non existing, that would mean for awk that total number of fields is 3 (NF==3)

To delete the # in front of header row, you can use any subsitute technique (i.e sub). I used gensub in my test.

Full answer:

The bellow code seems that fits to your needs. Though i have not used a tab-delimited file, but you can adjust accordingly to your tabulated file.

$ cat file4
##.....
##.....
#ID Name    Func    List
1   1   REF
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
4   4   RNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
5   5   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.14
6   6   INDEL
7   7   RNV
8   8   SNV GMAF=0.0041:EMAF=0.0:AMAF=0.0014
9   9   SNV EMAF=0.0041:GMAF=0.1:AMAF=0.0014

$ awk 'NR<3{next}NR==3{print gensub(/^#/,"","1");next}($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") && NF==3{print;next}
($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") {val=gensub(/.*GMAF=(.[^:]*).*/,"\\1","g",$4);if (val<=0.1) print}' file4
ID  Name    Func    List
2   2   SNV
3   3   SNV AMAF=0.0041:EMAF=0.0:GMAF=0.0014
6   6   INDEL
8   8   SNV GMAF=0.0041:EMAF=0.0:AMAF=0.0014
9   9   SNV EMAF=0.0041:GMAF=0.1:AMAF=0.0014

Explanation:

awk 'NR<3{next}                                                       # skip the first two lines
     NR==3{print gensub(/^#/,"","1");next}                            # print the third line (header) by removing the leading #
     ($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") && NF==3{print;next} # Print the lines missing $4 and go to next line
     ($3 == "SNV"|| $3 == "MNV"|| $3 == "INDEL") {                    # if $3 fullfils the criteria then
        val=gensub(/.*GMAF=(.[^:]*).*/,"\\1","g",$4);                 # isolate the value of GMAF with regex
        if (val<=0.1) print;                                          # compare and print
        }' file4


问:
Email extraction from csv using regex
I have the following regex:

/(.+?)((?:(?:[^<>()\[\]\\.,;:\s@"]+(?:\.[^<>()\[\]\\.,;:\s@"]+)*)|(?:".+"))@(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,})))/gi

Used to extract email address and name from the following different formats and avoid duplicates,

"FName LName" <fname.lname@gmail.com>, "Eg Name" <egname@gmail.com>,
Closed Call<close_call@gmail.co.um>

toys@urs.com

serima<serima@google.com>

One <one@one.com>;Two <two@two.com>; "New <new@new.com>"

Have couple of problems with it:

On test case #2 t gets trimmed, getting only oys@urs.com, this happens only on the first email address.

Second capturing group returns Name (if present along with a < if present) and then had to strip out the < separately

Any way to extract the above as follows, in much more elegant/efficient way

[{'name':'FName LName', 'email':'fname.lname@gmail.com'},
{'name':'Eg Name', 'email':'egname@gmail.com'},
{'name':'Closed Call', 'email':'close_call@gmail.co.um'}]

[{'name':'', 'email':'toys@urs.com'}]

[{'name':'serima', 'email':'serima@google.com'}]

[{'name':'One', 'email':'one@one.com'},
{'name':'Two', 'email':'two@two.com'},
{'name':'New', 'email':'new@new.com'}]

Note: Name may/maynot be enclosed with double quotes, there may/may not be space between the name and <

Title: Email extraction from csv using regex

Body:
Problem#1 solved by making the first capturing group a little more greedy,

/(.*?)((?:(?:[^<>()\[\]\\.,;:\s@"]+(?:\.[^<>()\[\]\\.,;:\s@"]+)*)|(?:".+"))@(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,})))/gi

Problem#2 will save it for tonight's dream-time ;-)


问:
Pyspark Streaming transform error
Hi I am new to Pyspark Streaming.

```<code>numbers0 = sc.parallelize([1,2,3,4,5])

numbers1 = sc.parallelize([2,3,4,5,6])

numbers2 = sc.parallelize([3,4,5,6,7])

stream0 = ssc.queueStream([numbers0, numbers1, numbers2])

stream0.pprint()

ssc.start()
ssc.awaitTermination(20)
ssc.stop()
</code>```

This works fine but as soon as I do the following I get an error:

```<code>stream1 = stream0.transform(lambda x: x.mean())

stream1.pprint()

ssc.start()
ssc.awaitTermination(20)
ssc.stop()
</code>```

What I want is stream that only consists of the mean of my previous stream.
Does anyone know what I must do?

答:
The error you are getting when calling transform is because it requires an RDD-to-RDD function as stated in Spark's documentation for the transform operation. When mean is called on an RDD, it does not return a new RDD and therefore the error.

Now, from what I understand you want to calculate the mean of each RDD that consists the DStream. The DStream is created with the queueStream and since the named parameter oneAtATime is left to default, your program will consume one RDD at every batch interval.

To calculate the mean for each RDD, you would normally do this inside a forEachRDD output operation like this

```<code># Create stream0 as you do in your example

def calculate_mean(rdd):
    mean_value = rdd.mean()
    # do other stuff with mean_value like saving it to a database or just print it

stream0.forEachRDD(calculate_mean)

# Start and stop the Streaming Context
</code>```

Title: Pyspark Streaming transform error

Body:
Hi I am new to Pyspark Streaming.

numbers0 = sc.parallelize([1,2,3,4,5])

numbers1 = sc.parallelize([2,3,4,5,6])

numbers2 = sc.parallelize([3,4,5,6,7])

stream0 = ssc.queueStream([numbers0, numbers1, numbers2])

stream0.pprint()

ssc.start()
ssc.awaitTermination(20)
ssc.stop()

This works fine but as soon as I do the following I get an error:

stream1 = stream0.transform(lambda x: x.mean())

stream1.pprint()

ssc.start()
ssc.awaitTermination(20)
ssc.stop()

What I want is stream that only consists of the mean of my previous stream.
Does anyone know what I must do?

Body:
The error you are getting when calling transform is because it requires an RDD-to-RDD function as stated in Spark's documentation for the transform operation. When mean is called on an RDD, it does not return a new RDD and therefore the error.

Now, from what I understand you want to calculate the mean of each RDD that consists the DStream. The DStream is created with the queueStream and since the named parameter oneAtATime is left to default, your program will consume one RDD at every batch interval.

To calculate the mean for each RDD, you would normally do this inside a forEachRDD output operation like this

# Create stream0 as you do in your example

def calculate_mean(rdd):
    mean_value = rdd.mean()
    # do other stuff with mean_value like saving it to a database or just print it

stream0.forEachRDD(calculate_mean)

# Start and stop the Streaming Context


问:
728x90 Ad Size not showing ads on https
We're in the middle of switching our website from http to https.

Our ads seem to be working on the https version of the website, we use DFP and we bring in competition via PreBid.

But for whatever reason, our 728x90 ads are always showing as house ads, whereas the 300x250, 320x250, and 300x600 ads are correctly working and showing ads.

Any idea why on the secure version of our website, the 728x90 ads wouldn't be working?

答:
There is no generic response for that situation. There are too many possible issues.

The first thing you need to do is to:

Create a simple HTML file with the 728x90 slot inside it and of course the JavaScript code to call DFP.

Open this HTML file with Chrome.

Use the F12 key to open Chrome DevTools.

Check the Console.

For any unsecured resources, Chrome displays a “Mixed Content” message
  in the Console. Some text will be in red or yellow.

Red: Errors that indicate the resource was blocked.

Yellow: Warnings that should be fixed.

Title: 728x90 Ad Size not showing ads on https


问:
What is the best approach to find and store all pair distances in a weighted tree?
What is the best approach to find and store all pair distances in a weighted tree?

My current approach is to run bfs on every node. But obviously this approach approach suffers from large complexity. Can we improve it further ?

答:
If you need to find the distance for all pairs, you can't do better than that. There're O(N^2) pairs so you need at least O(N^2) time to generate the answer.

If you don't need to compute all of them (say, you get pairs as query parameters later on), other solutions with their own trade-offs are possible.


问:
google maps api -> set max cruising speed
how can I set the max cruising speed, if I calc a new route?

I use the Google Maps API at my site for trucks and want to set a "max speed limit" by 80 km/h. Any idea?

答:
It should. Any travel guidance system which provides a time needs to take all sorts of factors into the calculation - just see how effective TomTom IQ routes is! It uses not only speed limits but actual real-time speed data gathered from Tomtom users. Also, I tow a caravan and so a 70mph speed on a UK motorway is not applicable, but I can set a maximum speed of 60mph (the max in the UK on motorways, if towing), which makes the transit times pretty close to reality most of the time. Google maps times are meaningless.
KC</p>


问:
How to assign value to one graph with the other graph who has the same structure in tensorflow?
I'm trying to implement DQN in tensorflow. Here I have one target network and one training network who have the same structure with each other. In the beginning of every 10000 training steps, I want to load the value from checkpoint to target network and training network, then stop_gradient target network. However, I tried those ways, and none of them worked:

1, Put the two networks in one graph. However, every time I load them, I don't know how to assign the value of training network part to target network part.(They are saved in different values, since one is stop gradient.)

2, Define two graphs using tf.graph() and run two session respectively. However, I can't load the checkpoint of one graph to another, even they have the same structure. After all, they are two different graphs.

So, any one who can give me some advice? Very appreciated!

答:
The typical approach would be to put everything in one graph, put your two networks in two name scopes, and then create tf.assign ops for each variable in one scope to the another and use the tf.group to construct a final "copying" operation. Lets assume that function create_net() builds a single network

```<code>with tf.name_scope('main_network'):
  main_net = create_net()

with tf.name_scope('target_network):
  target_network = create_net()

main_variables = tf.get_collection(tf.GraphKeys.VARIABLES, scope='main_network')
target_variables = tf.get_collection(tf.GraphKeys.VARIABLES, scope='target_network')

# I am assuming get_collection returns variables in the same order, please double
# check this is actually happening

assign_ops = []
for main_var, target_var in zip(main_variables, target_variables):
  assign_ops.append(tf.assign(target_var, tf.identity(main_var)))

copy_operation = tf.group(*assign_ops)
</code>```

Now executing copy_operation in session.run should copy your main network parameters to the target network. The above code should be considered a pseudo code, rather than something you can copy&paste.

Body:
The typical approach would be to put everything in one graph, put your two networks in two name scopes, and then create tf.assign ops for each variable in one scope to the another and use the tf.group to construct a final "copying" operation. Lets assume that function create_net() builds a single network

with tf.name_scope('main_network'):
  main_net = create_net()

with tf.name_scope('target_network):
  target_network = create_net()

main_variables = tf.get_collection(tf.GraphKeys.VARIABLES, scope='main_network')
target_variables = tf.get_collection(tf.GraphKeys.VARIABLES, scope='target_network')

# I am assuming get_collection returns variables in the same order, please double
# check this is actually happening

assign_ops = []
for main_var, target_var in zip(main_variables, target_variables):
  assign_ops.append(tf.assign(target_var, tf.identity(main_var)))

copy_operation = tf.group(*assign_ops)

Now executing copy_operation in session.run should copy your main network parameters to the target network. The above code should be considered a pseudo code, rather than something you can copy&paste.


问:
pthread_kill to a GCD-managed thread
I am attempting to send a signal to a specific thread with pthread_kill. I use pthread_from_mach_thread_np() to get a handle and then use pthread_kill to send the signal.

This worked well in my other testing, but now I see that when attempting to signal a thread internally created by GCD, I get a return code of 45 from pthread_kill.

GCD API that spawned that thread:

```<code>dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ ... });
</code>```

Any reason this is happening?

—-

To add some further information, I am not attempting to kill threads. pthread_kill() is the standard POSIX API to send signals to threads. If a signal handler is installed, the thread’s context is switched with a trampoline to the handler.

While what I attempt to achieve using my signal handler can be achieved in better ways, this is not in question here. Even if for purely academic reasons, I would like to understand what is going on here internally.

答:
That is a very bad idea. You don't own GCDs thread-pool, and you absolutely must not kill its threads out from under it.

The answer to your question is DO NOT DO THAT UNDER ANY CIRCUMSTANCES.

Title: pthread_kill to a GCD-managed thread

Body:
I am attempting to send a signal to a specific thread with pthread_kill. I use pthread_from_mach_thread_np() to get a handle and then use pthread_kill to send the signal.

This worked well in my other testing, but now I see that when attempting to signal a thread internally created by GCD, I get a return code of 45 from pthread_kill.

GCD API that spawned that thread:

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ ... });

Any reason this is happening?

—-

To add some further information, I am not attempting to kill threads. pthread_kill() is the standard POSIX API to send signals to threads. If a signal handler is installed, the thread’s context is switched with a trampoline to the handler.

While what I attempt to achieve using my signal handler can be achieved in better ways, this is not in question here. Even if for purely academic reasons, I would like to understand what is going on here internally.


问:
Why does this method consume so much memory? Or rather, why isn't GC freeing the memory?
I'm building some software that requires image panning, zooming, and brightness controls. I set up a small project to to build a simple brightness control after finding a lot of examples online, so please ignore that I'm doing everything in the main form

When I start to use the trackbar controller, which fires the event below when the value (-100 to 100) is changed, memory usage stacks up into the Gigabytes in seconds. It'll then sit there and never free the memory. Moving the trackbar again eats up even more memory

```<code>private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
    {
        float value = trackBarBrightness.Value * 0.01f;
        float[][] colorMatrixElements =
        {
            new float[] {
                1,
                0,
                0,
                0,
                0
            },
            new float[] {
                0,
                1,
                0,
                0,
                0
            },
            new float[] {
                0,
                0,
                1,
                0,
                0
            },
            new float[] {
                0,
                0,
                0,
                1,
                0
            },
            new float[] {
                value,
                value,
                value,
                0,
                1
            }
        };

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        ImageAttributes imageAttributes = new ImageAttributes();

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        //Image img = this.pictureEdit.Image;
        Image img = originalImage;
        Graphics g = default(Graphics);
        Bitmap bm = new Bitmap(Convert.ToInt32(img.Width), Convert.ToInt32(img.Height));
        g = Graphics.FromImage(bm);
        g.DrawImage(img, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel, imageAttributes);
        pictureEdit.Image = bm;
    }
</code>```

Any guidance would be much appreciated

答:
The issue is that you are not calling Dispose on your Bitmap. A Bitmap in .Net is essentially just a small managed object that wraps around a large unmanged GDI+ bitmap (source). It is this GDI+ bitmap that is storing the pixel data and, therefore, responsible for the memory consumption. The managed .Net Bitmap, being just a wrapper, is much smaller in comparison.

The reason GC.Collect() is freeing the memory is because you are forcing the GC to free all those bitmaps that are no longer being referenced which is in turn releasing all the unmanaged memory they are pointing to. The reason the GC is not doing this for you automatically is because the GC only tracks managed memory not unmanaged memory. So from the GC's point of view all these managed bitmaps you have left laying around are small and not taking up a lot of room so it is not important that it collect them. When, in fact, they are quite large.
From the MSDN:

If a small managed object allocates a large amount of unmanaged memory, the runtime takes into account only the managed memory, and thus underestimates the urgency of scheduling garbage collection.

By calling Dispose on your Bitmap when you no longer need it you will immediately free the unmanaged memory being used by the GDI+ bitmap. The managed .Net Bitmap will still hang around until the GC gets around to collecting it but who cares, that's tiny.

Body:
I'm building some software that requires image panning, zooming, and brightness controls. I set up a small project to to build a simple brightness control after finding a lot of examples online, so please ignore that I'm doing everything in the main form

When I start to use the trackbar controller, which fires the event below when the value (-100 to 100) is changed, memory usage stacks up into the Gigabytes in seconds. It'll then sit there and never free the memory. Moving the trackbar again eats up even more memory

private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
    {
        float value = trackBarBrightness.Value * 0.01f;
        float[][] colorMatrixElements =
        {
            new float[] {
                1,
                0,
                0,
                0,
                0
            },
            new float[] {
                0,
                1,
                0,
                0,
                0
            },
            new float[] {
                0,
                0,
                1,
                0,
                0
            },
            new float[] {
                0,
                0,
                0,
                1,
                0
            },
            new float[] {
                value,
                value,
                value,
                0,
                1
            }
        };

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        ImageAttributes imageAttributes = new ImageAttributes();

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        //Image img = this.pictureEdit.Image;
        Image img = originalImage;
        Graphics g = default(Graphics);
        Bitmap bm = new Bitmap(Convert.ToInt32(img.Width), Convert.ToInt32(img.Height));
        g = Graphics.FromImage(bm);
        g.DrawImage(img, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel, imageAttributes);
        pictureEdit.Image = bm;
    }

Any guidance would be much appreciated


问:
yield is not showing nothing
Im with some doubts about how to strucure the views folder on laravel. For example a blog site where we have this structure in the homepage:

Header (where we have a menu with: a link to homepage, search bar to search for posts, sign in and login buttons)

Then a section with the last 5 posts.

Then a section with the most viewed posts.

And then a footer.

How we can structure this homepage in terms of views?  For example maybe we can something like this:

```<code>-views

  - layouts
    - header.blade.php
    - footer.blade.php
  - posts
     - lastposts.blade.php
     - mostviewed.blade.php
     - single.blade.php
  - layout.blade.php
</code>```

Do you think its ok? Because Im testing this and it is not working. For example in the layout.blade.php I have:

```<code><!DOCTYPE html>
<html lang="en">
<head>
....
<link href="css/app.css" rel="stylesheet">
</head>

<body>

@include('layouts.nav')

@yield('lastposts')

@yield('mostviewed')

@include(layouts.footer')

</body>

</html>
</code>```

And I get the header and the footer when I access the page corretly, but the both @yields dont show nothing.

In the lastposts.blade.php to show the last 5 posts I have:

```<code>@extends('layout')
@section('lastposts')
<div>
   <h4>Title</h4>
    <p>Text</p>
  </div>
</div>
<div>
   <h4>Title</h4>
    <p>Text</p>
  </div>
</div>
<div>
   <h4>Title</h4>
    <p>Text</p>
  </div>
</div>
<div>
   <h4>Title</h4>
    <p>Text</p>
  </div>
</div>
<div>
   <h4>Title</h4>
    <p>Text</p>
  </div>
</div>
@endsection
</code>```

I have the same logic for the mostviewed.blade.php, but again, the @yield('mostviewed') dont show nothing.

Do you know what is not corret?

Routes file:

```<code>Route::get('/', function () {
   return view('layout');
}
</code>```

I have just this route because I just have the homepage for now.

答:
You created the wrong view. The parent view is layout, it doesn't know about mostviewed and lastposts. That's why you wrote @extends('layout'), that way when you create your content view, it will know that it has to extend stuff from layout.</p>

```<code>Route::get('/', function () {
   return view('posts.mostviewed');
}
</code>```

Title: yield is not showing nothing

Body:
Im with some doubts about how to strucure the views folder on laravel. For example a blog site where we have this structure in the homepage:

Header (where we have a menu with: a link to homepage, search bar to search for posts, sign in and login buttons)

Then a section with the last 5 posts.

Then a section with the most viewed posts.

And then a footer.

How we can structure this homepage in terms of views?  For example maybe we can something like this:

-views

  - layouts
    - header.blade.php
    - footer.blade.php
  - posts
     - lastposts.blade.php
     - mostviewed.blade.php
     - single.blade.php
  - layout.blade.php

Do you think its ok? Because Im testing this and it is not working. For example in the layout.blade.php I have:

<!DOCTYPE html>

....
<link href="css/app.css" rel="stylesheet">

@include('layouts.nav')

@yield('lastposts')

@yield('mostviewed')

@include(layouts.footer')

And I get the header and the footer when I access the page corretly, but the both @yields dont show nothing.

In the lastposts.blade.php to show the last 5 posts I have:

@extends('layout')
@section('lastposts')

Title

Text

Title

Text

Title

Text

Title

Text

Title

Text

@endsection

I have the same logic for the mostviewed.blade.php, but again, the @yield('mostviewed') dont show nothing.

Do you know what is not corret?

Routes file:

Route::get('/', function () {
   return view('layout');
}

I have just this route because I just have the homepage for now.

Body:
You created the wrong view. The parent view is layout, it doesn't know about mostviewed and lastposts. That's why you wrote @extends('layout'), that way when you create your content view, it will know that it has to extend stuff from layout.

Route::get('/', function () {
   return view('posts.mostviewed');
}


问:
How do you feel about including ie7.js or ie8.js in your page?
See here: http://code.google.com/p/ie7-js/

Does anyone have any experience or remarks about this javascript?  Is it worth including?  Do you recommend it?

答: well its beautiful and works grate way u can use cs3 features like li:hover. we did lost of project last time using ie8.js and it works great way. </p>

OwnerDisplayName: Bryan Denny

ContentLicense: CC BY-SA 2.5


问:
Check if a file is available (not used by another process) in Python
I'm looking for some code to check if a file in the file system is available (not used by another process). How could I do it in Python? Thanks!

How I'll use it: cylically check if file is available and when it is (processes don't need it anymore) delete it.

答:
If the file other process has the file open and you delete it, it will not be removed from the filesystem until all processes close their handles to it.

If the other process merely needs its file handle/object to continue to work you may safely delete the file, it will be removed when the process closes its handle. If you want to be able to call open() on the file until the process has finished with it, both processes need to use locks (see fcntl.flock()).


问:
Should I use "onmousedown" event, if I want to target desktop and mobile devices?
I´d like to know. If I want to make a responsive website, should I use the "onmousedown" event? Would it be triggered on all devices?
I have tested the simulation of Firefox, on mobile I get the "onmousedown" event.

Is there such an event? That would be triggered on mouse down and/or on touch , in desktop and mobile devices?

Thanks.

答:
Guarantee for all devices is nearly impossible due to the versions, nonstandard browsers, embedded browsers etc. You should first think about what your target platforms and what are the minimum browser versions. Then, you should follow the web standards and use common functions. Yes "onmousedown" is a standard event supported by majority of modern browsers, however it has also exceptions such as

The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.

stated in the onmousedown documentation.


问:
Finding Maximum Value of Array
I'm trying to loop through my array to find the maximum value and print the value. However, nothing is being printed to the console. Can you please take a look at my code below to see what I've done incorrectly.

```<code>for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
  array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 0; c < n; c++) {
    if (array[c] > maxInt) {
        maxInt = array[c];
    }
    else {
        break;
    }
}
System.out.println("Max int is: " + maxInt);
}
</code>```

EDIT:

Full class:

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

public class MaxMinOfArray {
public static void main(String[] args) {
int c, n, search, array[];
int maxInt, minInt;

Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt(); //asks user to specify array size
array = new int[n]; //creates array of specified array size

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 1; c < n; c++) {
if (array[c] > maxInt) {
    maxInt = array[c];
}
}
System.out.println("Max int is: " + maxInt);
}
}
</code>```

答:
Remove:

```<code>else {
        break;
    }
</code>```

And start from c=1

Title: Finding Maximum Value of Array

Body:
I'm trying to loop through my array to find the maximum value and print the value. However, nothing is being printed to the console. Can you please take a look at my code below to see what I've done incorrectly.

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
  array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 0; c < n; c++) {
    if (array[c] > maxInt) {
        maxInt = array[c];
    }
    else {
        break;
    }
}
System.out.println("Max int is: " + maxInt);
}

EDIT:

Full class:

import java.util.Scanner;

public class MaxMinOfArray {
public static void main(String[] args) {
int c, n, search, array[];
int maxInt, minInt;

Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt(); //asks user to specify array size
array = new int[n]; //creates array of specified array size

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 1; c < n; c++) {
if (array[c] > maxInt) {
    maxInt = array[c];
}
}
System.out.println("Max int is: " + maxInt);
}
}

Body:
Remove:

else {
        break;
    }

And start from c=1


问:
how to make Autocomplete show data from another table using foreign key according to "where" condition
i have created an auto complete search box in 'booking' table successfully , but i want the auto complete search box to show data from table 'patient' according to a specific condition using 'where' condition ,

This is the Booking Controller that i add autocomplete in it:

```<code> namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Booking;
use App\Patient;
use App\User;
use Session;
use DB;
use Auth;
use Input;
class BookingController extends Controller
{
   public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

$search = \Request::get('search');

$bookings = Booking::whereHas('patient', function ($query) use ($search) {
     $query->where('patient_name', 'like', '%' . $search . '%');
})->where('status','=', null)->whereHas('patient', function ($query){
  $query->where('company_id','=' ,Auth::user()->company_id);
})->paginate(10);

         return view('booking.index')->withBookings($bookings);
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */

public function autoComplete(Request $request) {
        $query = $request->get('term','');

        $bookings=Booking::whereHas('patient', function ($query){
        $query->where('company_id','=' ,Auth::user()->company_id);

        })->$data=array();
        foreach ($bookings as $booking) {
                $data[]=array('value'=>$booking->patient->patient_name,'id'=>$booking->id);
        }
        if(count($data))
             return $data;
        else
            return ['value'=>'No Result Found','id'=>''];
    }
</code>```

and this is the Booking Model :

```<code>class Booking extends Eloquent
{

 public function patient()
    {
    return $this->belongsTo('App\Patient');

    }

    public function user()
    {
    return $this->belongsTo('App\User');

    }
}
</code>```

and this is the patient Model:

```<code>class Patient extends Eloquent
{
     public function booking()
    {
    return $this->hasMany('App\Booking');

    }

     public function user()
    {
    return $this->belongsTo('App\User');

    }
}
</code>```

and i used this code in view :

```<code>{!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!}
</code>```

i want to show data from "patient" table   and there is a one to many relationship between "booking" and "patient" table and i have successfully made a search box to search in patient table as you can see in index function , but i dont know to show data from "patient" table using where condition to show patient_name that his company_id equal Authenticated user company_id

Sorry for my Bad Language .

答:
You should be able to load the patient relationship using with:

```<code>$bookings = Booking::with('patient')
    ->whereHas('patient', function ($query) use ($search) {
        $query->where('company_id', Auth::user()->company_id)
            ->where('patient_name', 'like', '%' . $search . '%');
    })
    ->whereNull('status')
    ->paginate(10);
</code>```

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

Also, you only need to use ->whereHas('patient'... once.

Hope this helps!

Body:
i have created an auto complete search box in 'booking' table successfully , but i want the auto complete search box to show data from table 'patient' according to a specific condition using 'where' condition ,

This is the Booking Controller that i add autocomplete in it:

 namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Booking;
use App\Patient;
use App\User;
use Session;
use DB;
use Auth;
use Input;
class BookingController extends Controller
{
   public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

$search = \Request::get('search');

$bookings = Booking::whereHas('patient', function ($query) use ($search) {
     $query->where('patient_name', 'like', '%' . $search . '%');
})->where('status','=', null)->whereHas('patient', function ($query){
  $query->where('company_id','=' ,Auth::user()->company_id);
})->paginate(10);

         return view('booking.index')->withBookings($bookings);
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */

public function autoComplete(Request $request) {
        $query = $request->get('term','');

        $bookings=Booking::whereHas('patient', function ($query){
        $query->where('company_id','=' ,Auth::user()->company_id);

        })->$data=array();
        foreach ($bookings as $booking) {
                $data[]=array('value'=>$booking->patient->patient_name,'id'=>$booking->id);
        }
        if(count($data))
             return $data;
        else
            return ['value'=>'No Result Found','id'=>''];
    }

and this is the Booking Model :

class Booking extends Eloquent
{

 public function patient()
    {
    return $this->belongsTo('App\Patient');

    }

    public function user()
    {
    return $this->belongsTo('App\User');

    }
}

and this is the patient Model:

class Patient extends Eloquent
{
     public function booking()
    {
    return $this->hasMany('App\Booking');

    }

     public function user()
    {
    return $this->belongsTo('App\User');

    }
}

and i used this code in view :

{!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!}

i want to show data from "patient" table   and there is a one to many relationship between "booking" and "patient" table and i have successfully made a search box to search in patient table as you can see in index function , but i dont know to show data from "patient" table using where condition to show patient_name that his company_id equal Authenticated user company_id

Sorry for my Bad Language .

Body:
You should be able to load the patient relationship using with:

$bookings = Booking::with('patient')
    ->whereHas('patient', function ($query) use ($search) {
        $query->where('company_id', Auth::user()->company_id)
            ->where('patient_name', 'like', '%' . $search . '%');
    })
    ->whereNull('status')
    ->paginate(10);

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

Also, you only need to use ->whereHas('patient'... once.

Hope this helps!


问:
Placing two actions buttons beside each other in a shiny app
I am trying to place two action buttons in a Shiny app in a sidebar. Is this at all possible? I don't want to resort to using columns  if I can   keep things simple

```<code>ui.R:
fluidPage(
 # Application title
 titlePanel("Place Two Buttons"),

 sidebarLayout(
# Sidebar with a slider and selection inputs
sidebarPanel(

  actionButton("read", "Change"),
  hr(),
  actionButton("write", "Change")
),

mainPanel(
  plotOutput("plot")
  )
)
)
</code>```

and my server :

```<code>server.R:
function(input, output, session) {

}
</code>```

All what I found so far was using css expressions or using Bootstrappage. Any help?

答:
You can remove the hr() to get the two buttons side by side:

```<code>ui <- fluidPage(
  # Application title
  titlePanel("Place Two Buttons"),

  sidebarLayout(
    # Sidebar with a slider and selection inputs
    sidebarPanel(
      actionButton("read", "Change"),
      actionButton("write", "Change")
    ),

    mainPanel(
      plotOutput("plot")
    )
  )
)

server <- function(input, output, session) {}
shinyApp( ui = ui, server = server )
</code>```

Which gives this:

Body:
I am trying to place two action buttons in a Shiny app in a sidebar. Is this at all possible? I don't want to resort to using columns  if I can   keep things simple

ui.R:
fluidPage(
 # Application title
 titlePanel("Place Two Buttons"),

 sidebarLayout(
# Sidebar with a slider and selection inputs
sidebarPanel(

  actionButton("read", "Change"),
  hr(),
  actionButton("write", "Change")
),

mainPanel(
  plotOutput("plot")
  )
)
)

and my server :

server.R:
function(input, output, session) {

}

All what I found so far was using css expressions or using Bootstrappage. Any help?

Body:
You can remove the hr() to get the two buttons side by side:

ui <- fluidPage(
  # Application title
  titlePanel("Place Two Buttons"),

  sidebarLayout(
    # Sidebar with a slider and selection inputs
    sidebarPanel(
      actionButton("read", "Change"),
      actionButton("write", "Change")
    ),

    mainPanel(
      plotOutput("plot")
    )
  )
)

server <- function(input, output, session) {}
shinyApp( ui = ui, server = server )

Which gives this:


问:
Have trouble uninstall scipy on osx
I've faced this specific trouble with multi-version python as 2.7 and 3.4.
python2.7 was installed by apple itself and I installed 3.4 myself and it works just fine.

When i use pip to install sklearn series(scikit-learn numpy scipy), since this pip was bound to python3.4 so python2.7 couldnt use it, and my project needs 2.7 this time.
I'm not going to uninstall 3.4.

```<code>sh-3.2# python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
</code>```

this means my default version of python is 2.7

My Question is when i use pip install & uninstall just with pip, the extras in python3.4 works fine.

And to install numpy and scipy to python2.7 I download those package and find those setup.py and run them with sudo python setup.py install.

The numpy seems fine but the scipy have this trouble as

```<code>error: Command "/usr/local/bin/gfortran -Wall -g -ffixed-form -fno-second-underscore -arch x86_64 -fPIC -I/Library/Python/2.7/site-packages/numpy-1.12.0.dev0_d69c147-py2.7-macosx-10.11-intel.egg/numpy/core/include -c -c scipy/integrate/mach/d1mach.f -o build/temp.macosx-10.11-intel-2.7/scipy/integrate/mach/d1mach.o" failed with exit status 1
</code>```

I run this "sudo python setup.py install" under scipy when i didnt have gfortran(of course i failed and find out that i need one). And after get gfortran im stuck with this annoying error.

my plan is uninstall scipy with pip first but i cant as im facing this

```<code>$ pip2.7 uninstall scipy
DEPRECATION: Uninstalling a distutils installed project (scipy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
Uninstalling scipy-0.13.0b1:

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy-0.13.0b1-py2.7.egg-info
Proceed (y/n)? y
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/uninstall.py", line 76, in run
    requirement_set.uninstall(auto_confirm=options.yes)
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 336, in uninstall
    req.uninstall(auto_confirm=auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/var/folders/8k/7_gm8zxx0zlg0nx4r5dg4rz00000gn/T/pip-hA6VUE-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy-0.13.0b1-py2.7.egg-info'
</code>```

Im very frustrated but still working on it. and seeking for help.

Im not an english speaker.so sorry for my poor english.

UPDATE:just with this problem and ive fix all others like pandas or sklearn

```<code>sudo pip2.7 install numpy --upgrade
The directory '/Users/ink/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/ink/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting numpy
  Downloading numpy-1.11.0-cp27-cp27m-<br>macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.9MB)
    100% |████████████████████████████████| 3.9MB 275kB/s
Installing collected packages: numpy
  Found existing installation: numpy 1.8.0rc1
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.0rc1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 736, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-gJ8Ao6-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'
</code>```

答: Had a similar issue that was resolved by reinstalling python https://www.python.org/downloads/</p>

Title: Have trouble uninstall scipy on osx

Body:
I've faced this specific trouble with multi-version python as 2.7 and 3.4.
python2.7 was installed by apple itself and I installed 3.4 myself and it works just fine.

When i use pip to install sklearn series(scikit-learn numpy scipy), since this pip was bound to python3.4 so python2.7 couldnt use it, and my project needs 2.7 this time.
I'm not going to uninstall 3.4.

sh-3.2# python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

this means my default version of python is 2.7

My Question is when i use pip install & uninstall just with pip, the extras in python3.4 works fine.

And to install numpy and scipy to python2.7 I download those package and find those setup.py and run them with sudo python setup.py install.

The numpy seems fine but the scipy have this trouble as

error: Command "/usr/local/bin/gfortran -Wall -g -ffixed-form -fno-second-underscore -arch x86_64 -fPIC -I/Library/Python/2.7/site-packages/numpy-1.12.0.dev0_d69c147-py2.7-macosx-10.11-intel.egg/numpy/core/include -c -c scipy/integrate/mach/d1mach.f -o build/temp.macosx-10.11-intel-2.7/scipy/integrate/mach/d1mach.o" failed with exit status 1

I run this "sudo python setup.py install" under scipy when i didnt have gfortran(of course i failed and find out that i need one). And after get gfortran im stuck with this annoying error.

my plan is uninstall scipy with pip first but i cant as im facing this

$ pip2.7 uninstall scipy
DEPRECATION: Uninstalling a distutils installed project (scipy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
Uninstalling scipy-0.13.0b1:

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy-0.13.0b1-py2.7.egg-info
Proceed (y/n)? y
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/uninstall.py", line 76, in run
    requirement_set.uninstall(auto_confirm=options.yes)
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 336, in uninstall
    req.uninstall(auto_confirm=auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/var/folders/8k/7_gm8zxx0zlg0nx4r5dg4rz00000gn/T/pip-hA6VUE-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy-0.13.0b1-py2.7.egg-info'

Im very frustrated but still working on it. and seeking for help.

Im not an english speaker.so sorry for my poor english.

UPDATE:just with this problem and ive fix all others like pandas or sklearn

sudo pip2.7 install numpy --upgrade
The directory '/Users/ink/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/ink/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting numpy
  Downloading numpy-1.11.0-cp27-cp27m-
macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.9MB)
    100% |████████████████████████████████| 3.9MB 275kB/s
Installing collected packages: numpy
  Found existing installation: numpy 1.8.0rc1
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.0rc1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 736, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-gJ8Ao6-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'


问:
Most Recent Entries in PHP/MySQL Ordered by Ascending
I would like to display the seven most recent entries, but I want the entries sorted in ascending order using PHP/MySQL. This is my current code:

```<code>$sql="SELECT date, weight, COUNT(*) AS 'count' FROM weights GROUP BY date ORDER BY date ASC";
</code>```

Note: I have tried adding "LIMIT 7," but that will only show entries 1-7 (not, say 15-21, which is what I want).

Also note: I have tried searching on Stack Overflow and Google, but the code didn't work.

答:
I got this to work thanks to some other Stack Overflow threads.

Note: My code is slightly different.

This is my code:

```<code>$sql="SELECT id, date, weight FROM (SELECT id, date, weight, COUNT(*) AS 'count' FROM weights GROUP BY date ORDER BY id DESC LIMIT 7) t ORDER BY id ASC";
</code>```

References:

MYSQL select last 3 rows, order by ASC

Select last 20 order by ascending - PHP/MySQL

Note: I do not know the difference between...

```<code>t ORDER BY id ASC
</code>```

and...

```<code>tmp order by tmp.id asc
</code>```

I went with the first one, because it happened to be the first one I got to work (this took a while) and it looked simpler.

If anyone knows if the GROUP BY and ORDER BY values are correct, please comment.

Please also comment to let me know which version of the ASC I should use.

Body:
I would like to display the seven most recent entries, but I want the entries sorted in ascending order using PHP/MySQL. This is my current code:

$sql="SELECT date, weight, COUNT(*) AS 'count' FROM weights GROUP BY date ORDER BY date ASC";

Note: I have tried adding "LIMIT 7," but that will only show entries 1-7 (not, say 15-21, which is what I want).

Also note: I have tried searching on Stack Overflow and Google, but the code didn't work.

Body:
I got this to work thanks to some other Stack Overflow threads.

Note: My code is slightly different.

This is my code:

$sql="SELECT id, date, weight FROM (SELECT id, date, weight, COUNT(*) AS 'count' FROM weights GROUP BY date ORDER BY id DESC LIMIT 7) t ORDER BY id ASC";

References:

MYSQL select last 3 rows, order by ASC

Select last 20 order by ascending - PHP/MySQL

Note: I do not know the difference between...

t ORDER BY id ASC

and...

tmp order by tmp.id asc

I went with the first one, because it happened to be the first one I got to work (this took a while) and it looked simpler.

If anyone knows if the GROUP BY and ORDER BY values are correct, please comment.

Please also comment to let me know which version of the ASC I should use.


问:
Unable to generate FMX in oracle apps r12.1.3
I am new to the oracle apps form development.
i am unable to generate .FMX file using below command in putty.

```<code>frmcmp_batch.sh module=/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/EMP.fmb
userid=apps/apps
    output_file=/u01/install/APPS/apps/apps_st/appl/po/12.0.0/forms/US/EMP.fmx module_type=form
</code>```

Please help me on the same.

Thanks&Regards,
Vivek

答:
you may call a script from the command line

```<code>$ appCompile.sh EMP.fmb
</code>```

where appCompile.sh maybe like below one

```<code>ORACLE_HOME=/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US; export ORACLE_HOME
export NLS_LANG=american_america.we8iso8859p9 #for Turkish
NLS_DATE_FORMAT=DD/MM/YYYY; export NLS_DATE_FORMAT
FORMS_PATH=/data/aski_kodlar/standard; export FORMS_PATH
alias oh='cd $ORACLE_HOME'
LD_LIBRARY_PATH=/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/lib:/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/jdk/jre/lib/sparcv9:
/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/jdk/jre/lib/sparcv9/server:/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/jdk/jre/lib/sparcv9/native_threads
export LD_LIBRARY_PATH
export ORACLE_TERM=vt220
export TERM=xterm
type=$2

if test "$type" = ""
then
 type=form
fi

echo Compiling Form $1 ....
filename=`echo $1|cut -f1 -d.`
/u01/install/APPS/apps/apps_st/appl/scripts/frmcmp_batch.sh userid=apps/apps@db_name Module_Type=$type  compile_all=yes window_state=minimize batch=yes Module=$1
</code>```

Body:
I am new to the oracle apps form development.
i am unable to generate .FMX file using below command in putty.

frmcmp_batch.sh module=/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/EMP.fmb
userid=apps/apps
    output_file=/u01/install/APPS/apps/apps_st/appl/po/12.0.0/forms/US/EMP.fmx module_type=form

Please help me on the same.

Thanks&Regards,
Vivek

Body:
you may call a script from the command line

$ appCompile.sh EMP.fmb

where appCompile.sh maybe like below one

ORACLE_HOME=/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US; export ORACLE_HOME
export NLS_LANG=american_america.we8iso8859p9 #for Turkish
NLS_DATE_FORMAT=DD/MM/YYYY; export NLS_DATE_FORMAT
FORMS_PATH=/data/aski_kodlar/standard; export FORMS_PATH
alias oh='cd $ORACLE_HOME'
LD_LIBRARY_PATH=/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/lib:/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/jdk/jre/lib/sparcv9:
/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/jdk/jre/lib/sparcv9/server:/u01/install/APPS/apps/apps_st/appl/au/12.0.0/forms/US/jdk/jre/lib/sparcv9/native_threads
export LD_LIBRARY_PATH
export ORACLE_TERM=vt220
export TERM=xterm
type=$2

if test "$type" = ""
then
 type=form
fi

echo Compiling Form $1 ....
filename=`echo $1|cut -f1 -d.`
/u01/install/APPS/apps/apps_st/appl/scripts/frmcmp_batch.sh userid=apps/apps@db_name Module_Type=$type  compile_all=yes window_state=minimize batch=yes Module=$1


问:
Pattern match an array of Regex's in Scala
I have an array of regex's in Scala, and am trying to verify that a message body contains anything in the regex. However, in the messageBody variable I'm getting a Pattern type is incompatible with given type, expected Array[Regex], found Array[String]. How can I pass in a proper case?

A few other posts have suggested using Pattern but that hasn't worked in my case.

```<code>  val messageBody: Array[String] = message.body.split(' ')
  val unsubscribeTriggers: Array[Regex] = Array("unsubscribe/i".r, "stop/i".r, "stopall/i".r, "cancel/i".r, "end/i".r, "quit/i".r)\

  if (messageBody.length == 1) {
        unsubscribeTriggers match {
          case `messageBody` => true

          case _ => false

        }
}
</code>```

答:
You can match on regex individual variables pretty cleanly also.</p>

```<code>val messageBody: Array[String] = message.body.split(' ')

val unsubscribe = "(?i)unsubscribe".r
val stop = "(?i)stop".r
val stopall = "(?i)stopall".r
val cancel = "(?i)cancel".r
val end = "(?i)end".r
val quit = "(?i)quit".r

val shouldUnsubscribe = messageBody.headOption.exists {
  case unsubscribe() => true
  case stop() => true
  case stopall() => true
  case cancel() => true
  case end() => true
  case quit() => true
  case _ => false
}
</code>```

Body:
I have an array of regex's in Scala, and am trying to verify that a message body contains anything in the regex. However, in the messageBody variable I'm getting a Pattern type is incompatible with given type, expected Array[Regex], found Array[String]. How can I pass in a proper case?

A few other posts have suggested using Pattern but that hasn't worked in my case.

  val messageBody: Array[String] = message.body.split(' ')
  val unsubscribeTriggers: Array[Regex] = Array("unsubscribe/i".r, "stop/i".r, "stopall/i".r, "cancel/i".r, "end/i".r, "quit/i".r)\

  if (messageBody.length == 1) {
        unsubscribeTriggers match {
          case `messageBody` => true

          case _ => false

        }
}

Body:
You can match on regex individual variables pretty cleanly also.

val messageBody: Array[String] = message.body.split(' ')

val unsubscribe = "(?i)unsubscribe".r
val stop = "(?i)stop".r
val stopall = "(?i)stopall".r
val cancel = "(?i)cancel".r
val end = "(?i)end".r
val quit = "(?i)quit".r

val shouldUnsubscribe = messageBody.headOption.exists {
  case unsubscribe() => true
  case stop() => true
  case stopall() => true
  case cancel() => true
  case end() => true
  case quit() => true
  case _ => false
}


问:
JQuery on media query elements
```<code> <div class = "header>
</div>

.header{
position:relative
color:green;
}

@media only screen and (max-width : 400px) {
.header{
position:fixed
color:blue;
}
}
</code>```

I have a div that has a positioning of relative, and in a media query I change that to fixed. I am now trying to target the media query div, however it's modifying the original div. Any suggestions? My attempt was to make the JS check the screen width but this did not work.

Just to clarify I would like my Javascript to apply for the media query div header.

```<code>if(screen.width<400){
        console.log('yes');
    $(window).scroll(function(){
        $(".header").css("top", Math.max(0,30 - $(this).scrollTop()));
    });}
</code>```

答:
Ok let me clarify... you don't have 2 divs. You have 1 div and the browser applies the style indicated... ie: when the screen is large, it applies the regular style :

```<code>.header{
    position:relative
    color:green;
}
</code>```

When you are in mobile it applies:

```<code>@media only screen and (max-width : 400px) {
    .header{
        position:fixed
        color:blue;
    }
}
</code>```

They are both acting on the exact same thing.. just different rules on styling. So you can't "target" one or the other because they are the same exact element. If you could put this into a jsfiddle or a codepen to replicate, it would be easier to see what you have.

If you are just trying to overwrite the media query style, what you are doing should work, or using getComputedStyle(element).[property]

Title: JQuery on media query elements

Body:
.header{
position:relative
color:green;
}

@media only screen and (max-width : 400px) {
.header{
position:fixed
color:blue;
}
}

I have a div that has a positioning of relative, and in a media query I change that to fixed. I am now trying to target the media query div, however it's modifying the original div. Any suggestions? My attempt was to make the JS check the screen width but this did not work.

Just to clarify I would like my Javascript to apply for the media query div header.

if(screen.width<400){
        console.log('yes');
    $(window).scroll(function(){
        $(".header").css("top", Math.max(0,30 - $(this).scrollTop()));
    });}

Body:
Ok let me clarify... you don't have 2 divs. You have 1 div and the browser applies the style indicated... ie: when the screen is large, it applies the regular style :

.header{
    position:relative
    color:green;
}

When you are in mobile it applies:

@media only screen and (max-width : 400px) {
    .header{
        position:fixed
        color:blue;
    }
}

They are both acting on the exact same thing.. just different rules on styling. So you can't "target" one or the other because they are the same exact element. If you could put this into a jsfiddle or a codepen to replicate, it would be easier to see what you have.

If you are just trying to overwrite the media query style, what you are doing should work, or using getComputedStyle(element).[property]


问:
can't receive data from .net web server even it connect to .net web server
I am new to web services in iphone.

I fallow this tutorial

my code is as fallows

```<code>NSString *soapMsg =
    [NSString stringWithFormat:
     @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
     "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
     "<soap:Body>"
     "<GenericAndroidMethod xmlns=\"Mortgage\">"
     "<methodName>MortgageGetLoanOfficerInfo</methodName>"
      "<xmlParam><MortgageGetLoanOfficerInfo><PhoneNumber>919703661366</PhoneNumber></MortgageGetLoanOfficerInfo></xmlParam>"
     "</GenericAndroidMethod>"
     "</soap:Body>"
     "</soap:Envelope>"
     ];
    NSLog(@"%@",soapMsg);
    NSURL *url = [NSURL URLWithString:@"http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
    [req addValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [req addValue:@"Mortgage/GenericAndroidMethod"forHTTPHeaderField:@"SOAPAction"];
    [req addValue:msgLength
    forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (conn) {
        NSLog(@"connected %@",conn);
        webData = [[NSMutableData data] retain];
    }
}

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
    NSLog(@"connect %@",connection);
    [webData setLength: 0];
}

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
    NSLog(@"test %@",data);
    [webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
    NSLog(@"error will occer %@",error);
    [webData release];
    [connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    NSLog(@"recived data %@",webData);
    NSString *theXML = [[NSString alloc]
                        initWithBytes: [webData mutableBytes]
                        length:[webData length]
                        encoding:NSUTF8StringEncoding];
    //---shows the XML---
    NSLog(@"%@",theXML);
    [theXML release];

    [connection release];
    [webData release];
}
</code>```

In Console i got

```<code>2010-12-20 11:23:50.754 Hello_SOAP[1911:40b] <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GenericAndroidMethod xmlns="Mortgage"><methodName>MortgageGetLoanOfficerInfo</methodName><xmlParam><MortgageGetLoanOfficerInfo><PhoneNumber>919703661366</PhoneNumber></MortgageGetLoanOfficerInfo></xmlParam></GenericAndroidMethod></soap:Body></soap:Envelope>
2010-12-20 11:23:50.963 Hello_SOAP[1911:40b] connected <NSURLConnection: 0x5d3dc30, http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx>
2010-12-20 11:23:51.375 Hello_SOAP[1911:40b] connect <NSURLConnection: 0x5d3dc30, http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx>
2010-12-20 11:23:51.376 Hello_SOAP[1911:40b] DONE. Received Bytes: 0
2010-12-20 11:23:51.377 Hello_SOAP[1911:40b] recived data <>
</code>```

in  connection didReceiveData i did n't get any data

can any one pls help me why i did n't receive data.

Thank u in advance.

答:
try to see the headers from the didReceiveResponse method

```<code>NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [httpResponse allHeaderFields];
    NSLog([dictionary description]);
}
</code>```

see the description. It might give the response header received from the server. It contains Length parameter. If it is 0, the server is returning no data to the app.  One possible work around will be to change the header for the request.

Body:
I am new to web services in iphone.

I fallow this tutorial

my code is as fallows

NSString *soapMsg =
    [NSString stringWithFormat:
     @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
     "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
     "<soap:Body>"
     "<GenericAndroidMethod xmlns=\"Mortgage\">"
     "<methodName>MortgageGetLoanOfficerInfo</methodName>"
      "<xmlParam><MortgageGetLoanOfficerInfo><PhoneNumber>919703661366</PhoneNumber></MortgageGetLoanOfficerInfo></xmlParam>"
     "</GenericAndroidMethod>"
     "</soap:Body>"
     "</soap:Envelope>"
     ];
    NSLog(@"%@",soapMsg);
    NSURL *url = [NSURL URLWithString:@"http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
    [req addValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [req addValue:@"Mortgage/GenericAndroidMethod"forHTTPHeaderField:@"SOAPAction"];
    [req addValue:msgLength
    forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (conn) {
        NSLog(@"connected %@",conn);
        webData = [[NSMutableData data] retain];
    }
}

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
    NSLog(@"connect %@",connection);
    [webData setLength: 0];
}

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
    NSLog(@"test %@",data);
    [webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
    NSLog(@"error will occer %@",error);
    [webData release];
    [connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    NSLog(@"recived data %@",webData);
    NSString *theXML = [[NSString alloc]
                        initWithBytes: [webData mutableBytes]
                        length:[webData length]
                        encoding:NSUTF8StringEncoding];
    //---shows the XML---
    NSLog(@"%@",theXML);
    [theXML release];

    [connection release];
    [webData release];
}

In Console i got

2010-12-20 11:23:50.754 Hello_SOAP[1911:40b] <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GenericAndroidMethod xmlns="Mortgage"><methodName>MortgageGetLoanOfficerInfo</methodName><xmlParam><MortgageGetLoanOfficerInfo><PhoneNumber>919703661366</PhoneNumber></MortgageGetLoanOfficerInfo></xmlParam></GenericAndroidMethod></soap:Body></soap:Envelope>
2010-12-20 11:23:50.963 Hello_SOAP[1911:40b] connected <NSURLConnection: 0x5d3dc30, http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx>
2010-12-20 11:23:51.375 Hello_SOAP[1911:40b] connect <NSURLConnection: 0x5d3dc30, http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx>
2010-12-20 11:23:51.376 Hello_SOAP[1911:40b] DONE. Received Bytes: 0
2010-12-20 11:23:51.377 Hello_SOAP[1911:40b] recived data <>

in  connection didReceiveData i did n't get any data

can any one pls help me why i did n't receive data.

Thank u in advance.

Body:
try to see the headers from the didReceiveResponse method

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [httpResponse allHeaderFields];
    NSLog([dictionary description]);
}

see the description. It might give the response header received from the server. It contains Length parameter. If it is 0, the server is returning no data to the app.  One possible work around will be to change the header for the request.


问:
tf.train.shuffle_batch() ValueError: Cannot infer Tensor's rank: Tensor("PyFunc:0", dtype=uint8)
I am trying to feed my image data from my TFRecord files into tf.train.shuffle_batch().  I have a load_img_file() function that reads the TFRecord files, does preprocessing, and returns the images and one-hot labels in the format [[array of images, np.uint8 format], [array of labels, np.uint8 format]].  I made the op

```<code>load_img_file_op = tf.py_func(self.load_img_file, [], [np.uint8, np.uint8])
</code>```

which converts that function into an op.  I have verified that that op works by doing

```<code>data = tf.Session().run(load_img_file_op)
for n in range(50): #go through images
    print data[1][n] #print one-hot label
    self.image_set.display_img(data[0][n]) #display image
</code>```

which successfully prints the one-hot labels and displays the corresponding images.

However, when I try to do something like

```<code>self.batch = tf.train.shuffle_batch(load_img_file_op, batch_size=self.batch_size, capacity=q_capacity, min_after_dequeue=10000)
</code>```

I get the error

raise ValueError("Cannot infer Tensor's rank: %s" % tl[i])
  ValueError: Cannot infer Tensor's rank: Tensor("PyFunc:0", dtype=uint8)"

I have tried many variations to try to match what the guide does:

Instead of self.batch =, I have tried example_batch, label_batch = (trying to get two values instead of one)

setting enqueue_many to True

having my load_image_file() function and load_img_file_op return two separate values: images and labels. And then inputting them like tf.train.shuffle_batch([images, labels],...)

returning/inputting just one image and label at a time into tf.train.shuffle_batch()

using tf.train.shuffle_batch_join()

Nothing seems to work, but I feel like I am following the format of the guide and various other tutorials I have seen.  What am I doing wrong?  I apologize if my mistake is stupid or trivial (searches for this error do not seem to return anything relevant to me). Thank you for your help and time!

答:
The link in the comments helped a lot; thank you!  (The answer is that you have to give the shape when using py_func.)  Since I had to figure out a little bit more on top of that I will post the complete solution:

I had to make my function return two separate values so that they would be two different tensors and could be shaped separately:

```<code>return images, labels
</code>```

Then, proceeding as in the question above, but shaping:

```<code>load_img_file_op = tf.py_func(self.load_img_file, [], [np.uint8, np.uint8]) # turn the function into an op
images, labels = load_img_file_op
images.set_shape([imgs_per_file, height * width])
labels.set_shape([imgs_per_file, num_classes])
self.batch = tf.train.shuffle_batch([images, labels], batch_size=self.batch_size, capacity=q_capacity, min_after_dequeue=1000, enqueue_many = True)
</code>```

The enqueue_many is important so that the images will enter the queue individually.

Body:
I am trying to feed my image data from my TFRecord files into tf.train.shuffle_batch().  I have a load_img_file() function that reads the TFRecord files, does preprocessing, and returns the images and one-hot labels in the format [[array of images, np.uint8 format], [array of labels, np.uint8 format]].  I made the op

load_img_file_op = tf.py_func(self.load_img_file, [], [np.uint8, np.uint8])

which converts that function into an op.  I have verified that that op works by doing

data = tf.Session().run(load_img_file_op)
for n in range(50): #go through images
    print data[1][n] #print one-hot label
    self.image_set.display_img(data[0][n]) #display image

which successfully prints the one-hot labels and displays the corresponding images.

However, when I try to do something like

self.batch = tf.train.shuffle_batch(load_img_file_op, batch_size=self.batch_size, capacity=q_capacity, min_after_dequeue=10000)

I get the error

raise ValueError("Cannot infer Tensor's rank: %s" % tl[i])
  ValueError: Cannot infer Tensor's rank: Tensor("PyFunc:0", dtype=uint8)"

I have tried many variations to try to match what the guide does:

Instead of self.batch =, I have tried example_batch, label_batch = (trying to get two values instead of one)

setting enqueue_many to True

having my load_image_file() function and load_img_file_op return two separate values: images and labels. And then inputting them like tf.train.shuffle_batch([images, labels],...)

returning/inputting just one image and label at a time into tf.train.shuffle_batch()

using tf.train.shuffle_batch_join()

Nothing seems to work, but I feel like I am following the format of the guide and various other tutorials I have seen.  What am I doing wrong?  I apologize if my mistake is stupid or trivial (searches for this error do not seem to return anything relevant to me). Thank you for your help and time!

Body:
The link in the comments helped a lot; thank you!  (The answer is that you have to give the shape when using py_func.)  Since I had to figure out a little bit more on top of that I will post the complete solution:

I had to make my function return two separate values so that they would be two different tensors and could be shaped separately:

return images, labels

Then, proceeding as in the question above, but shaping:

load_img_file_op = tf.py_func(self.load_img_file, [], [np.uint8, np.uint8]) # turn the function into an op
images, labels = load_img_file_op
images.set_shape([imgs_per_file, height * width])
labels.set_shape([imgs_per_file, num_classes])
self.batch = tf.train.shuffle_batch([images, labels], batch_size=self.batch_size, capacity=q_capacity, min_after_dequeue=1000, enqueue_many = True)

The enqueue_many is important so that the images will enter the queue individually.


问:
VueFire vs Vue.js + Node.js vs Vue.js + Feathers advantages, disadvantages and differences
I have doing a lot of research about frontend frameworks and have decided that I would like to try Vue.js. However, I would also like to get a backend with real time "data updating". I have looked at VueFire (Vue.js + Firebase), Node.js and Feathers. It looks like Feathers has a limited amount of resources/documentation on using it with Vue while there seems to be a good amount of information on VueFire and Node.js with Vue.js.

What are the differences between those three backends?

What are the advantages/disadvantages of using one over the other?

答:
What are the differences between those three backends?

Let's clarify a few things.

Node.js is, as defined on their website: "a JavaScript runtime built on Chrome's V8 JavaScript engine."

Firebase is a platform as a service (PaaS).

Feathers is REST and realtime API framework, a back-end framework.

VueFire is just a wrapper around the Firebase JS SDK. It makes calling Firebase more "Vue" like.

Vue.js is a front-end framework or progressive framework as the creator calls it.

With that said we're comparing Feathers and Firebase. It's clear what the difference is and the advantages/disadvantages.

What are the advantages/disadvantages of using one over the other?

Firebase lets you hit the ground running. You create your Firebase account/project and you're set to go with all the products it offers. You do not have to worry about setting up your own database layer, authentication/security, or anything. It's all set up and managed for you, but at a cost. Besides the money factor, you've also locked yourself and depend heavy on a third party and things can change at anytime without any say in the matter.

Feathers is a framework. It gives to tools to create your own Firebase platform. You're free to configure it however you want. You're in full control and it's free. However, you will have to setup your own database layer, security, and likely more.

In the end it boils down to your needs/requirements. It's best to make a list of your specific needs and see what framework or service fulfills those needs. It's useless to search for advantages/disadvantages as you will get opinion-based answers.